title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
MySQL DELETE Statement
The DELETE statement is used to delete existing records in a table. Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted! Below is a selection from the "Customers" table in the Northwind sample database: The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table: The "Customers" table will now look like this: It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: The following SQL statement deletes all rows in the "Customers" table, without deleting the table: Delete all the records from the Customers table where the Country value is 'Norway'. Customers Country = 'Norway'; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 68, "s": 0, "text": "The DELETE statement is used to delete existing records in a table." }, { "code": null, "e": 305, "s": 68, "text": "Note: Be careful when deleting records in a table! Notice the \nWHERE clause in the \nDELETE statement.\nThe WHERE clause specifies which record(s) should be deleted. If \nyou omit the WHERE clause, all records in the table will be deleted!" }, { "code": null, "e": 388, "s": 305, "text": "Below is a selection from the \"Customers\" table in the Northwind sample \ndatabase:" }, { "code": null, "e": 488, "s": 388, "text": "The following SQL statement deletes the customer \"Alfreds Futterkiste\" from \nthe \"Customers\" table:" }, { "code": null, "e": 535, "s": 488, "text": "The \"Customers\" table will now look like this:" }, { "code": null, "e": 686, "s": 535, "text": "It is possible to delete all rows in a table without deleting the table. This \nmeans that the table structure, attributes, and indexes will be intact:" }, { "code": null, "e": 786, "s": 686, "text": "The following SQL statement deletes all rows in the \"Customers\" table, \nwithout deleting the table:" }, { "code": null, "e": 871, "s": 786, "text": "Delete all the records from the Customers table where the Country value is 'Norway'." }, { "code": null, "e": 904, "s": 871, "text": " Customers\n Country = 'Norway';\n" }, { "code": null, "e": 923, "s": 904, "text": "Start the Exercise" }, { "code": null, "e": 956, "s": 923, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 998, "s": 956, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1105, "s": 998, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1124, "s": 1105, "text": "[email protected]" } ]
Python Program to find the area of a circle
In this article, we will learn about the solution and approach to solve the given problem statement. Problem statement −Given the radius of a circle, we need to find a circle. The area of a circle can simply be evaluated using the following formula. Area = Pi*r*r Let’s see the implementation below − Live Demo def findArea(r): PI = 3.142 return PI * (r*r); # Driver method print("Area is %.6f" % findArea(5)); Area is 78.550000 All variables and functions are declared in the global scope as shown in the figure below. In this article, we learned about the approach to find whether it is possible to make a divisible by 3 numbers using all digits in an array.
[ { "code": null, "e": 1163, "s": 1062, "text": "In this article, we will learn about the solution and approach to solve the given problem statement." }, { "code": null, "e": 1238, "s": 1163, "text": "Problem statement −Given the radius of a circle, we need to find a circle." }, { "code": null, "e": 1312, "s": 1238, "text": "The area of a circle can simply be evaluated using the following formula." }, { "code": null, "e": 1326, "s": 1312, "text": "Area = Pi*r*r" }, { "code": null, "e": 1363, "s": 1326, "text": "Let’s see the implementation below −" }, { "code": null, "e": 1374, "s": 1363, "text": " Live Demo" }, { "code": null, "e": 1480, "s": 1374, "text": "def findArea(r):\n PI = 3.142\n return PI * (r*r);\n# Driver method\nprint(\"Area is %.6f\" % findArea(5));" }, { "code": null, "e": 1498, "s": 1480, "text": "Area is 78.550000" }, { "code": null, "e": 1589, "s": 1498, "text": "All variables and functions are declared in the global scope as shown in the figure below." }, { "code": null, "e": 1730, "s": 1589, "text": "In this article, we learned about the approach to find whether it is possible to make a divisible by 3 numbers using all digits in an array." } ]
How to create a JSON using JsonObjectBuilder and JsonArrayBuilder in Java?
The JsonObjectBuilder can be used for creating JsonObject models whereas the JsonArrayBuilder can be used for creating JsonArray models. The JsonObjectBuilder can be created using the Json class, it contains methods to create the builder object and build an empty JsonObject instance using the Json.createObjectBuilder().build(). The JsonArrayBuilder can be created using the Json class, it contains methods to create the builder object and build an empty JsonArray instance using Json.createArrayBuilder().build(). import java.io.*; import javax.json.*; public class JsonObjectTest { public static void main(String[] args) { JsonObject empObject = Json.createObjectBuilder().add("empName", "Jai") .add("empAge", "25") .add("empSalary", "40000") .add("empAddress", Json.createObjectBuilder().add("street", "IDPL Colony") .add("city", "Hyderabad") .add("pinCode", "500072") .build() ) .add("phoneNumber", Json.createArrayBuilder().add("9959984000") .add("7702144400") .build() ) .build(); System.out.println(empObject); } } {"empName":"Jai","empAge":"25","empSalary":"40000","empAddress":{"street":"IDPL Colony","city":"Hyderabad","pinCode":"500072"},"phoneNumber":["9959984000","7702144400"]}
[ { "code": null, "e": 1578, "s": 1062, "text": "The JsonObjectBuilder can be used for creating JsonObject models whereas the JsonArrayBuilder can be used for creating JsonArray models. The JsonObjectBuilder can be created using the Json class, it contains methods to create the builder object and build an empty JsonObject instance using the Json.createObjectBuilder().build(). The JsonArrayBuilder can be created using the Json class, it contains methods to create the builder object and build an empty JsonArray instance using Json.createArrayBuilder().build()." }, { "code": null, "e": 2722, "s": 1578, "text": "import java.io.*;\nimport javax.json.*;\npublic class JsonObjectTest {\n public static void main(String[] args) {\n JsonObject empObject = Json.createObjectBuilder().add(\"empName\", \"Jai\")\n .add(\"empAge\", \"25\")\n .add(\"empSalary\", \"40000\")\n .add(\"empAddress\",\n Json.createObjectBuilder().add(\"street\", \"IDPL Colony\")\n .add(\"city\", \"Hyderabad\")\n .add(\"pinCode\", \"500072\")\n .build()\n )\n .add(\"phoneNumber\",\n Json.createArrayBuilder().add(\"9959984000\")\n .add(\"7702144400\")\n .build()\n )\n .build();\n System.out.println(empObject);\n }\n}" }, { "code": null, "e": 2892, "s": 2722, "text": "{\"empName\":\"Jai\",\"empAge\":\"25\",\"empSalary\":\"40000\",\"empAddress\":{\"street\":\"IDPL Colony\",\"city\":\"Hyderabad\",\"pinCode\":\"500072\"},\"phoneNumber\":[\"9959984000\",\"7702144400\"]}" } ]
Tcl - Basic Syntax
Tcl is quite simple to learn and let's start creating our first Tcl program! Let us write a simple Tcl program. All Tcl files will have an extension, i.e., .tcl. So, put the following source code in a test.tcl file. #!/usr/bin/tclsh puts "Hello, World!" Assuming, Tcl environment is setup correctly; let's run the program after switching to file's directory and then execute the program using − $ tclsh test.tcl We will get the following output − Hello, World! Let us now see the basic structure of Tcl program, so that it will be easy for you to understand basic building blocks of the Tcl language. In Tcl, we use new line or semicolon to terminate the previous line of code. But semicolon is not necessary, if you are using newline for each command. Comments are like helping text in your Tcl program and the interpreter ignores them. Comments can be written using a hash_(#) sign in the beginning. #!/usr/bin/tclsh # my first program in Tcl puts "Hello World!" When the above code is executed, it produces the following result − Hello World! Multiline or block comment is written using 'if' with condition '0'. An example is shown below. #!/usr/bin/tclsh if 0 { my first program in Tcl program Its very simple } puts "Hello World!" When the above code is executed, it produces the following result − Hello World! Inline comments use ;#. An example is given below. #!/usr/bin/tclsh puts "Hello World!" ;# my first print in Tcl program When the above code is executed, it produces the following result − Hello World! A Tcl identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, dollars ($) , and digits (0 to 9). Tcl does not allow punctuation characters such as @, and % within identifiers. Tcl is a case sensitive_ language. Thus Manpower and manpower are two different identifiers in Tcl. Here are some of the examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal A line containing only whitespace, possibly with a comment, is known as a blank line, and a Tcl interpreter totally ignores it. Whitespace is the term used in Tcl to describe blanks, tabs, newline characters, and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as puts, ends and the next element begins. Therefore, in the following statement − #!/usr/bin/tclsh puts "Hello World!" There must be at least one whitespace character (usually a space) between “puts” and "Hello World!" for the interpreter to be able to distinguish them. On the other hand, in the following statement − #!/usr/bin/tclsh puts [expr 3 + 2] ;# print sum of the 3 and 2 When the above code is executed, it produces the following result − 5 No whitespace characters are necessary between 3 and +, or between + and 2; although, you are free to include some if you wish for the readability purpose. Print Add Notes Bookmark this page
[ { "code": null, "e": 2278, "s": 2201, "text": "Tcl is quite simple to learn and let's start creating our first Tcl program!" }, { "code": null, "e": 2417, "s": 2278, "text": "Let us write a simple Tcl program. All Tcl files will have an extension, i.e., .tcl. So, put the following source code in a test.tcl file." }, { "code": null, "e": 2457, "s": 2417, "text": "#!/usr/bin/tclsh\n\nputs \"Hello, World!\" " }, { "code": null, "e": 2598, "s": 2457, "text": "Assuming, Tcl environment is setup correctly; let's run the program after switching to file's directory and then execute the program using −" }, { "code": null, "e": 2616, "s": 2598, "text": "$ tclsh test.tcl\n" }, { "code": null, "e": 2651, "s": 2616, "text": "We will get the following output −" }, { "code": null, "e": 2666, "s": 2651, "text": "Hello, World!\n" }, { "code": null, "e": 2958, "s": 2666, "text": "Let us now see the basic structure of Tcl program, so that it will be easy for you to understand basic building blocks of the Tcl language. In Tcl, we use new line or semicolon to terminate the previous line of code. But semicolon is not necessary, if you are using newline for each command." }, { "code": null, "e": 3107, "s": 2958, "text": "Comments are like helping text in your Tcl program and the interpreter ignores them. Comments can be written using a hash_(#) sign in the beginning." }, { "code": null, "e": 3172, "s": 3107, "text": "#!/usr/bin/tclsh\n\n# my first program in Tcl\nputs \"Hello World!\" " }, { "code": null, "e": 3240, "s": 3172, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3254, "s": 3240, "text": "Hello World!\n" }, { "code": null, "e": 3350, "s": 3254, "text": "Multiline or block comment is written using 'if' with condition '0'. An example is shown below." }, { "code": null, "e": 3452, "s": 3350, "text": "#!/usr/bin/tclsh\n\nif 0 {\n my first program in Tcl program\n Its very simple\n}\nputs \"Hello World!\" " }, { "code": null, "e": 3520, "s": 3452, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3534, "s": 3520, "text": "Hello World!\n" }, { "code": null, "e": 3585, "s": 3534, "text": "Inline comments use ;#. An example is given below." }, { "code": null, "e": 3656, "s": 3585, "text": "#!/usr/bin/tclsh\n\nputs \"Hello World!\" ;# my first print in Tcl program" }, { "code": null, "e": 3724, "s": 3656, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3738, "s": 3724, "text": "Hello World!\n" }, { "code": null, "e": 3991, "s": 3738, "text": "A Tcl identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, dollars ($) , and digits (0 to 9)." }, { "code": null, "e": 4228, "s": 3991, "text": "Tcl does not allow punctuation characters such as @, and % within identifiers. Tcl is a case sensitive_ language. Thus Manpower and manpower are two different identifiers in Tcl. Here are some of the examples of acceptable identifiers −" }, { "code": null, "e": 4314, "s": 4228, "text": "mohd zara abc move_name a_123\nmyname50 _temp j a23b9 retVal\n" }, { "code": null, "e": 4442, "s": 4314, "text": "A line containing only whitespace, possibly with a comment, is known as a blank line, and a Tcl interpreter totally ignores it." }, { "code": null, "e": 4757, "s": 4442, "text": "Whitespace is the term used in Tcl to describe blanks, tabs, newline characters, and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as puts, ends and the next element begins. Therefore, in the following statement −" }, { "code": null, "e": 4796, "s": 4757, "text": "#!/usr/bin/tclsh\n\nputs \"Hello World!\" " }, { "code": null, "e": 4996, "s": 4796, "text": "There must be at least one whitespace character (usually a space) between “puts” and \"Hello World!\" for the interpreter to be able to distinguish them. On the other hand, in the following statement −" }, { "code": null, "e": 5060, "s": 4996, "text": "#!/usr/bin/tclsh\n\nputs [expr 3 + 2] ;# print sum of the 3 and 2" }, { "code": null, "e": 5128, "s": 5060, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 5131, "s": 5128, "text": "5\n" }, { "code": null, "e": 5287, "s": 5131, "text": "No whitespace characters are necessary between 3 and +, or between + and 2; although, you are free to include some if you wish for the readability purpose." }, { "code": null, "e": 5294, "s": 5287, "text": " Print" }, { "code": null, "e": 5305, "s": 5294, "text": " Add Notes" } ]
Python | os.path.normcase() method
09 Mar, 2022 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.os.path.normcase() method in Python is used to normalize the case of specified path name. On windows, this method converts all characters in the specified path to the lowercase and forward slash (‘/’) to backslash (‘\’). This method returns the specified path unchanged on operating systems other than Windows. Syntax: os.path.normcase(path)Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the normalized case in the specified path. Code #1: Use of os.path.normcase() method (On Windows) Python3 # Python program to explain os.path.normcase() method # importing os.path moduleimport os.path # Pathpath = r'C:\User\admin\Documents' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # Pathpath = '/hoMe/UseR/' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # Pathpath = r'C:\Users/Desktop' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) c:\\user\\admin\\documents \\home\\user c:\\users\\desktop Code #2: Use of os.path.normcase() method (On operating systems other than Windows) Python3 # Python program to explain os.path.normcase() method # importing os.path moduleimport os.path # Pathpath = '/home/UseR/Documents' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # Pathpath = '/hoMe/UseR/' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # os.path.norcase() method will return# the specified path as it as# on operating systems# other than Windows /home/UseR/Documents /hoMe/UseR/ Reference: https://docs.python.org/3/library/os.path.html ManasChhabra2 sumitgumber28 Python OS-path-module python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2022" }, { "code": null, "e": 651, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.os.path.normcase() method in Python is used to normalize the case of specified path name. On windows, this method converts all characters in the specified path to the lowercase and forward slash (‘/’) to backslash (‘\\’). This method returns the specified path unchanged on operating systems other than Windows. " }, { "code": null, "e": 860, "s": 651, "text": "Syntax: os.path.normcase(path)Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the normalized case in the specified path. " }, { "code": null, "e": 917, "s": 860, "text": "Code #1: Use of os.path.normcase() method (On Windows) " }, { "code": null, "e": 925, "s": 917, "text": "Python3" }, { "code": "# Python program to explain os.path.normcase() method # importing os.path moduleimport os.path # Pathpath = r'C:\\User\\admin\\Documents' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # Pathpath = '/hoMe/UseR/' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # Pathpath = r'C:\\Users/Desktop' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path)", "e": 1538, "s": 925, "text": null }, { "code": null, "e": 1597, "s": 1538, "text": "c:\\\\user\\\\admin\\\\documents\n\\\\home\\\\user\nc:\\\\users\\\\desktop" }, { "code": null, "e": 1685, "s": 1599, "text": "Code #2: Use of os.path.normcase() method (On operating systems other than Windows) " }, { "code": null, "e": 1693, "s": 1685, "text": "Python3" }, { "code": "# Python program to explain os.path.normcase() method # importing os.path moduleimport os.path # Pathpath = '/home/UseR/Documents' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # Pathpath = '/hoMe/UseR/' # Normalize the case of # characters in the specified pathnorm_path = os.path.normcase(path) # Print the normalized path print(norm_path) # os.path.norcase() method will return# the specified path as it as# on operating systems# other than Windows", "e": 2241, "s": 1693, "text": null }, { "code": null, "e": 2274, "s": 2241, "text": "/home/UseR/Documents\n/hoMe/UseR/" }, { "code": null, "e": 2335, "s": 2276, "text": "Reference: https://docs.python.org/3/library/os.path.html " }, { "code": null, "e": 2349, "s": 2335, "text": "ManasChhabra2" }, { "code": null, "e": 2363, "s": 2349, "text": "sumitgumber28" }, { "code": null, "e": 2385, "s": 2363, "text": "Python OS-path-module" }, { "code": null, "e": 2402, "s": 2385, "text": "python-os-module" }, { "code": null, "e": 2409, "s": 2402, "text": "Python" }, { "code": null, "e": 2507, "s": 2409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2539, "s": 2507, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2566, "s": 2539, "text": "Python Classes and Objects" }, { "code": null, "e": 2587, "s": 2566, "text": "Python OOPs Concepts" }, { "code": null, "e": 2610, "s": 2587, "text": "Introduction To PYTHON" }, { "code": null, "e": 2666, "s": 2610, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2697, "s": 2666, "text": "Python | os.path.join() method" }, { "code": null, "e": 2739, "s": 2697, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2781, "s": 2739, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2820, "s": 2781, "text": "Python | Get unique values from a list" } ]
SQL Snapshots
23 Oct, 2020 Snapshot is a recent copy of the table from the database or a subset of rows/columns of a table. The SQL statement that creates and subsequently maintains a snapshot normally reads data from the database residing server. A snapshot is created on the destination system with the create snapshot SQL command. The remote table is immediately defined and populated from the master table. These are used to dynamically replicate data between distributed databases. Two types of snapshots are available. Simple snapshotsComplex snapshots Simple snapshots Complex snapshots Simple snapshot :In simple snapshot, each row is based on a single row in a single remote table. This consists of either a single table or a simple SELECT of rows from a single table. Example – CREATE SNAPSHOT emp_snap as select * from emp; Complex snapshot :In complex snapshot, a row may be based on more than one row in a remote table via GROUP BY operation or result of Multi-Table Join. This consists of joined tables, views, or grouped and complex SELECT statement queries. Example – CREATE SNAPSHOT sampleSnps1 AS SELECT student.rollno, student.name FROM student UNION ALL SELECT new_student.rollno, new_student.name FROM new_student; Advantages : Response time is improved when local read-only copy of table exists. Once snapshot is built on remote database, if node containing data from which the snapshot is built is not available. Snapshot can be used without need to access the unavailable database. Ease network loads. Data subsetting. Disconnected computing. Mass deployment. Disadvantages : Snapshots are not reachable when primary database goes offline. It does not support full text indexing. Snapshot runs out of disk if data changes frequently faster. As no.of snapshots increases, disk space becomes problematic. Applications : Protects data. Maintains history of data. Used in testing application software. Used in data mining. Recovers data when information is lost because of human error or corruption of data. DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python RANK() Function in SQL Server SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Oct, 2020" }, { "code": null, "e": 412, "s": 28, "text": "Snapshot is a recent copy of the table from the database or a subset of rows/columns of a table. The SQL statement that creates and subsequently maintains a snapshot normally reads data from the database residing server. A snapshot is created on the destination system with the create snapshot SQL command. The remote table is immediately defined and populated from the master table." }, { "code": null, "e": 526, "s": 412, "text": "These are used to dynamically replicate data between distributed databases. Two types of snapshots are available." }, { "code": null, "e": 560, "s": 526, "text": "Simple snapshotsComplex snapshots" }, { "code": null, "e": 577, "s": 560, "text": "Simple snapshots" }, { "code": null, "e": 595, "s": 577, "text": "Complex snapshots" }, { "code": null, "e": 779, "s": 595, "text": "Simple snapshot :In simple snapshot, each row is based on a single row in a single remote table. This consists of either a single table or a simple SELECT of rows from a single table." }, { "code": null, "e": 789, "s": 779, "text": "Example –" }, { "code": null, "e": 838, "s": 789, "text": "CREATE SNAPSHOT emp_snap \nas select * from emp;\n" }, { "code": null, "e": 1077, "s": 838, "text": "Complex snapshot :In complex snapshot, a row may be based on more than one row in a remote table via GROUP BY operation or result of Multi-Table Join. This consists of joined tables, views, or grouped and complex SELECT statement queries." }, { "code": null, "e": 1087, "s": 1077, "text": "Example –" }, { "code": null, "e": 1243, "s": 1087, "text": "CREATE SNAPSHOT sampleSnps1 \nAS SELECT student.rollno, student.name \nFROM student\nUNION ALL\nSELECT new_student.rollno, new_student.name \nFROM new_student;\n" }, { "code": null, "e": 1256, "s": 1243, "text": "Advantages :" }, { "code": null, "e": 1325, "s": 1256, "text": "Response time is improved when local read-only copy of table exists." }, { "code": null, "e": 1513, "s": 1325, "text": "Once snapshot is built on remote database, if node containing data from which the snapshot is built is not available. Snapshot can be used without need to access the unavailable database." }, { "code": null, "e": 1533, "s": 1513, "text": "Ease network loads." }, { "code": null, "e": 1550, "s": 1533, "text": "Data subsetting." }, { "code": null, "e": 1574, "s": 1550, "text": "Disconnected computing." }, { "code": null, "e": 1591, "s": 1574, "text": "Mass deployment." }, { "code": null, "e": 1607, "s": 1591, "text": "Disadvantages :" }, { "code": null, "e": 1671, "s": 1607, "text": "Snapshots are not reachable when primary database goes offline." }, { "code": null, "e": 1711, "s": 1671, "text": "It does not support full text indexing." }, { "code": null, "e": 1772, "s": 1711, "text": "Snapshot runs out of disk if data changes frequently faster." }, { "code": null, "e": 1834, "s": 1772, "text": "As no.of snapshots increases, disk space becomes problematic." }, { "code": null, "e": 1849, "s": 1834, "text": "Applications :" }, { "code": null, "e": 1864, "s": 1849, "text": "Protects data." }, { "code": null, "e": 1891, "s": 1864, "text": "Maintains history of data." }, { "code": null, "e": 1929, "s": 1891, "text": "Used in testing application software." }, { "code": null, "e": 1950, "s": 1929, "text": "Used in data mining." }, { "code": null, "e": 2035, "s": 1950, "text": "Recovers data when information is lost because of human error or corruption of data." }, { "code": null, "e": 2044, "s": 2035, "text": "DBMS-SQL" }, { "code": null, "e": 2048, "s": 2044, "text": "SQL" }, { "code": null, "e": 2052, "s": 2048, "text": "SQL" }, { "code": null, "e": 2150, "s": 2052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2216, "s": 2150, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2240, "s": 2216, "text": "Window functions in SQL" }, { "code": null, "e": 2272, "s": 2240, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2305, "s": 2272, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2322, "s": 2305, "text": "SQL using Python" }, { "code": null, "e": 2352, "s": 2322, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2430, "s": 2352, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2466, "s": 2430, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2497, "s": 2466, "text": "SQL Query to Compare Two Dates" } ]
How to run bash script in Python?
26 Mar, 2021 If you are using any major operating system you are indirectly interacting with bash. If you are running Ubuntu, Linux Mint, or any other Linux distribution, you are interacting with bash every time you use the terminal. Suppose you have written your bash script that needs to be invoked from python code. The module designed to spawn new processes and communicate with them has a name subprocess. Let’s consider such a simple example, presenting a recommended approach to invoking subprocesses. As an argument, you have to pass the command you want to invoke and its arguments, all wrapped in a list. Python3 import subprocess # execute commandsubprocess.run(["echo", "Geeks for geeks"]) Output: CompletedProcess(args=[‘echo’, ‘Geeks for geeks’], returncode=0) A new process is created and command echo is invoked with the argument “Geeks for geeks”. Although, the command’s result is not captured by the python script. We can do it by adding optional keyword argument capture_output=True to run the function, or by invoking check_output function from the same module. Both functions invoke the command, but the first one is available in Python3.7 and newer versions. Python3 import subprocess # From Python3.7 you can add # keyword argument capture_outputprint(subprocess.run(["echo", "Geeks for geeks"], capture_output=True)) # For older versions of Python:print(subprocess.check_output(["echo", "Geeks for geeks"])) Output: CompletedProcess(args=[‘echo’, ‘Geeks for geeks’], returncode=0, stdout=b’Geeks for geeks\n’, stderr=b”) b’Geeks for geeks\n’ What about invoking already existing shell script from python code? It’s also done by run command! Python3 import subprocess # If your shell script has shebang, # you can omit shell=True argument.subprocess.run(["/path/to/your/shell/script", "arguments"], shell=True) Output: CompletedProcess(args=[‘/path/to/your/shell/script’, ‘arguments’], returncode=127) Common problems with invoking shell script and how to solve them: Permission denied when invoking script — don’t forget to make your script executable! Use chmod +x /path/to/your/script OSError: [Errno 8] Exec format error — run functions lacks shell=True option or script has no shebang. Picked 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 ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2021" }, { "code": null, "e": 426, "s": 28, "text": "If you are using any major operating system you are indirectly interacting with bash. If you are running Ubuntu, Linux Mint, or any other Linux distribution, you are interacting with bash every time you use the terminal. Suppose you have written your bash script that needs to be invoked from python code. The module designed to spawn new processes and communicate with them has a name subprocess." }, { "code": null, "e": 630, "s": 426, "text": "Let’s consider such a simple example, presenting a recommended approach to invoking subprocesses. As an argument, you have to pass the command you want to invoke and its arguments, all wrapped in a list." }, { "code": null, "e": 638, "s": 630, "text": "Python3" }, { "code": "import subprocess # execute commandsubprocess.run([\"echo\", \"Geeks for geeks\"])", "e": 720, "s": 638, "text": null }, { "code": null, "e": 728, "s": 720, "text": "Output:" }, { "code": null, "e": 793, "s": 728, "text": "CompletedProcess(args=[‘echo’, ‘Geeks for geeks’], returncode=0)" }, { "code": null, "e": 1200, "s": 793, "text": "A new process is created and command echo is invoked with the argument “Geeks for geeks”. Although, the command’s result is not captured by the python script. We can do it by adding optional keyword argument capture_output=True to run the function, or by invoking check_output function from the same module. Both functions invoke the command, but the first one is available in Python3.7 and newer versions." }, { "code": null, "e": 1208, "s": 1200, "text": "Python3" }, { "code": "import subprocess # From Python3.7 you can add # keyword argument capture_outputprint(subprocess.run([\"echo\", \"Geeks for geeks\"], capture_output=True)) # For older versions of Python:print(subprocess.check_output([\"echo\", \"Geeks for geeks\"]))", "e": 1507, "s": 1208, "text": null }, { "code": null, "e": 1515, "s": 1507, "text": "Output:" }, { "code": null, "e": 1620, "s": 1515, "text": "CompletedProcess(args=[‘echo’, ‘Geeks for geeks’], returncode=0, stdout=b’Geeks for geeks\\n’, stderr=b”)" }, { "code": null, "e": 1641, "s": 1620, "text": "b’Geeks for geeks\\n’" }, { "code": null, "e": 1740, "s": 1641, "text": "What about invoking already existing shell script from python code? It’s also done by run command!" }, { "code": null, "e": 1748, "s": 1740, "text": "Python3" }, { "code": "import subprocess # If your shell script has shebang, # you can omit shell=True argument.subprocess.run([\"/path/to/your/shell/script\", \"arguments\"], shell=True)", "e": 1928, "s": 1748, "text": null }, { "code": null, "e": 1936, "s": 1928, "text": "Output:" }, { "code": null, "e": 2019, "s": 1936, "text": "CompletedProcess(args=[‘/path/to/your/shell/script’, ‘arguments’], returncode=127)" }, { "code": null, "e": 2085, "s": 2019, "text": "Common problems with invoking shell script and how to solve them:" }, { "code": null, "e": 2205, "s": 2085, "text": "Permission denied when invoking script — don’t forget to make your script executable! Use chmod +x /path/to/your/script" }, { "code": null, "e": 2308, "s": 2205, "text": "OSError: [Errno 8] Exec format error — run functions lacks shell=True option or script has no shebang." }, { "code": null, "e": 2315, "s": 2308, "text": "Picked" }, { "code": null, "e": 2330, "s": 2315, "text": "python-utility" }, { "code": null, "e": 2337, "s": 2330, "text": "Python" }, { "code": null, "e": 2435, "s": 2337, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2467, "s": 2435, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2494, "s": 2467, "text": "Python Classes and Objects" }, { "code": null, "e": 2515, "s": 2494, "text": "Python OOPs Concepts" }, { "code": null, "e": 2538, "s": 2515, "text": "Introduction To PYTHON" }, { "code": null, "e": 2594, "s": 2538, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2625, "s": 2594, "text": "Python | os.path.join() method" }, { "code": null, "e": 2667, "s": 2625, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2709, "s": 2667, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2748, "s": 2709, "text": "Python | Get unique values from a list" } ]
How to create the boilerplate code in VS Code?
31 May, 2021 While programming, there is often a piece of code that needs to be written repetitively. For example, loops (for loop, while loop, do-while loop), or classes and functions. To write such a piece of code, again and again, becomes a daunting task, and often copy and paste is done, which definitely takes a lot of time and effort. The above problem can be solved using Code-Snippets or boilerplates. Boilerplate or a code-snippet are solution provided by IDEs like VS Code, where a repetitive code can be called within a program by typing prefix names. Code snippets for loops and classes are already provided in the IDE. C++ // C++ program to demonstrate the// boilerplate code#include <iostream>using namespace std; // Driver Codeint main(){ return 0;} Let’s see how to create a Code-Snippet/ Boilerplate for our basic C++ programs in the VS Code. Step 1: Locating the C++ JSON file for adding the snippet: Open your VS Code and click on the settings button in the bottom-left corner. Click on User Snippets. You’ll see a dropdown at the top of a list of various JSON files. Click on cpp.json Step 2: Adding the C++ code to the JSON file: Remove all the code from this file and write down the code given below. C++ // Write this code in the cpp.json file{ "cpp snippets": { "prefix" : "boilerplate", "body" : [ "#include<iostream>", "using namespace std;", "int main()", "{", " return 0;", "}" ], "description" : "to produce the main snippet for cpp" }} After writing the code, press Ctrl + S to save the changes that have been made. Explanation of the above code: prefix: It is used to trigger the snippet or the boilerplate ( Your boilerplate can have any random name, here I have used ‘boilerplate’ itself)body: It contains the reusable code, which we’ll call with the help of a prefix.description: It contains a small definition of the snippet, which explains the purpose behind it. prefix: It is used to trigger the snippet or the boilerplate ( Your boilerplate can have any random name, here I have used ‘boilerplate’ itself) body: It contains the reusable code, which we’ll call with the help of a prefix. description: It contains a small definition of the snippet, which explains the purpose behind it. Step 3: Calling the Boilerplate in our program: Create a new C++ file in the current folder. Type in the prefix which we used for our Boilerplate. You will notice that VS Code automatically suggests your prefix name while you are halfway typing the name. Now press ENTER. Now we have created a basic boilerplate for everyday programming. CPP-Basics C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2021" }, { "code": null, "e": 450, "s": 52, "text": "While programming, there is often a piece of code that needs to be written repetitively. For example, loops (for loop, while loop, do-while loop), or classes and functions. To write such a piece of code, again and again, becomes a daunting task, and often copy and paste is done, which definitely takes a lot of time and effort. The above problem can be solved using Code-Snippets or boilerplates." }, { "code": null, "e": 603, "s": 450, "text": "Boilerplate or a code-snippet are solution provided by IDEs like VS Code, where a repetitive code can be called within a program by typing prefix names." }, { "code": null, "e": 672, "s": 603, "text": "Code snippets for loops and classes are already provided in the IDE." }, { "code": null, "e": 676, "s": 672, "text": "C++" }, { "code": "// C++ program to demonstrate the// boilerplate code#include <iostream>using namespace std; // Driver Codeint main(){ return 0;}", "e": 809, "s": 676, "text": null }, { "code": null, "e": 904, "s": 809, "text": "Let’s see how to create a Code-Snippet/ Boilerplate for our basic C++ programs in the VS Code." }, { "code": null, "e": 963, "s": 904, "text": "Step 1: Locating the C++ JSON file for adding the snippet:" }, { "code": null, "e": 1041, "s": 963, "text": "Open your VS Code and click on the settings button in the bottom-left corner." }, { "code": null, "e": 1065, "s": 1041, "text": "Click on User Snippets." }, { "code": null, "e": 1131, "s": 1065, "text": "You’ll see a dropdown at the top of a list of various JSON files." }, { "code": null, "e": 1149, "s": 1131, "text": "Click on cpp.json" }, { "code": null, "e": 1195, "s": 1149, "text": "Step 2: Adding the C++ code to the JSON file:" }, { "code": null, "e": 1267, "s": 1195, "text": "Remove all the code from this file and write down the code given below." }, { "code": null, "e": 1271, "s": 1267, "text": "C++" }, { "code": "// Write this code in the cpp.json file{ \"cpp snippets\": { \"prefix\" : \"boilerplate\", \"body\" : [ \"#include<iostream>\", \"using namespace std;\", \"int main()\", \"{\", \" return 0;\", \"}\" ], \"description\" : \"to produce the main snippet for cpp\" }}", "e": 1726, "s": 1271, "text": null }, { "code": null, "e": 1806, "s": 1726, "text": "After writing the code, press Ctrl + S to save the changes that have been made." }, { "code": null, "e": 1837, "s": 1806, "text": "Explanation of the above code:" }, { "code": null, "e": 2159, "s": 1837, "text": "prefix: It is used to trigger the snippet or the boilerplate ( Your boilerplate can have any random name, here I have used ‘boilerplate’ itself)body: It contains the reusable code, which we’ll call with the help of a prefix.description: It contains a small definition of the snippet, which explains the purpose behind it." }, { "code": null, "e": 2304, "s": 2159, "text": "prefix: It is used to trigger the snippet or the boilerplate ( Your boilerplate can have any random name, here I have used ‘boilerplate’ itself)" }, { "code": null, "e": 2385, "s": 2304, "text": "body: It contains the reusable code, which we’ll call with the help of a prefix." }, { "code": null, "e": 2483, "s": 2385, "text": "description: It contains a small definition of the snippet, which explains the purpose behind it." }, { "code": null, "e": 2531, "s": 2483, "text": "Step 3: Calling the Boilerplate in our program:" }, { "code": null, "e": 2738, "s": 2531, "text": "Create a new C++ file in the current folder. Type in the prefix which we used for our Boilerplate. You will notice that VS Code automatically suggests your prefix name while you are halfway typing the name." }, { "code": null, "e": 2755, "s": 2738, "text": "Now press ENTER." }, { "code": null, "e": 2821, "s": 2755, "text": "Now we have created a basic boilerplate for everyday programming." }, { "code": null, "e": 2832, "s": 2821, "text": "CPP-Basics" }, { "code": null, "e": 2836, "s": 2832, "text": "C++" }, { "code": null, "e": 2849, "s": 2836, "text": "C++ Programs" }, { "code": null, "e": 2853, "s": 2849, "text": "CPP" } ]
Grab where current date and the day before with MySQL?
You can grab the current date with CURDATE() and the day before with MySQL using DATE_SUB() with INTERVAL 1 DAY. The syntax is as follows: SELECT DATE_SUB(CURDATE(),INTERVAL 1 DAY); The syntax is as follows to get curdate and the day before with date_sub(). SELECT *FROM yourTableName WHERE yourColumnName = CURDATE() OR yourColumnName = DATE_SUB(CURDATE(),INTERVAL 1 DAY); To understand the above syntax, let us create a table. The query to create a table is as follows: mysql> create table ProductDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> ProductName varchar(20), -> ProductOfferDate datetime, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.54 sec) Insert some records in the table using insert command. Here, we have added the products and the product offer date. The query is as follows: mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-11','2017-05-21'); Query OK, 1 row affected (0.25 sec) mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-22','2019-01-15'); Query OK, 1 row affected (0.16 sec) mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-21','2019-01-14'); Query OK, 1 row affected (0.14 sec) mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-91','2018-10-23'); Query OK, 1 row affected (0.26 sec) mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-133','2019-01-24'); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from ProductDemo; The following is the output: +----+-------------+---------------------+ | Id | ProductName | ProductOfferDate | +----+-------------+---------------------+ | 1 | Product-11 | 2017-05-21 00:00:00 | | 2 | Product-22 | 2019-01-15 00:00:00 | | 3 | Product-21 | 2019-01-14 00:00:00 | | 4 | Product-91 | 2018-10-23 00:00:00 | | 5 | Product-133 | 2019-01-24 00:00:00 | +----+-------------+---------------------+ 5 rows in set (0.00 sec) The following is the query to grab the product with current date and the day before: mysql> select *from ProductDemo -> where ProductOfferDate = CURDATE() OR ProductOfferDate = date_sub(curdate(),interval 1 day); The following is the output: +----+-------------+---------------------+ | Id | ProductName | ProductOfferDate | +----+-------------+---------------------+ | 2 | Product-22 | 2019-01-15 00:00:00 | | 3 | Product-21 | 2019-01-14 00:00:00 | +----+-------------+---------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1326, "s": 1187, "text": "You can grab the current date with CURDATE() and the day before with MySQL using DATE_SUB() with INTERVAL 1 DAY. The syntax is as follows:" }, { "code": null, "e": 1369, "s": 1326, "text": "SELECT DATE_SUB(CURDATE(),INTERVAL 1 DAY);" }, { "code": null, "e": 1445, "s": 1369, "text": "The syntax is as follows to get curdate and the day before with date_sub()." }, { "code": null, "e": 1561, "s": 1445, "text": "SELECT *FROM yourTableName WHERE yourColumnName = CURDATE() OR yourColumnName = DATE_SUB(CURDATE(),INTERVAL 1 DAY);" }, { "code": null, "e": 1659, "s": 1561, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows:" }, { "code": null, "e": 1869, "s": 1659, "text": "mysql> create table ProductDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> ProductName varchar(20),\n -> ProductOfferDate datetime,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.54 sec)" }, { "code": null, "e": 2010, "s": 1869, "text": "Insert some records in the table using insert command. Here, we have added the products and the product offer date. The query is as follows:" }, { "code": null, "e": 2675, "s": 2010, "text": "mysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-11','2017-05-21');\nQuery OK, 1 row affected (0.25 sec)\n\nmysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-22','2019-01-15');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-21','2019-01-14');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-91','2018-10-23');\nQuery OK, 1 row affected (0.26 sec)\n\nmysql> insert into ProductDemo(ProductName,ProductOfferDate) values('Product-133','2019-01-24');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 2759, "s": 2675, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 2792, "s": 2759, "text": "mysql> select *from ProductDemo;" }, { "code": null, "e": 2821, "s": 2792, "text": "The following is the output:" }, { "code": null, "e": 3224, "s": 2821, "text": "+----+-------------+---------------------+\n| Id | ProductName | ProductOfferDate |\n+----+-------------+---------------------+\n| 1 | Product-11 | 2017-05-21 00:00:00 |\n| 2 | Product-22 | 2019-01-15 00:00:00 |\n| 3 | Product-21 | 2019-01-14 00:00:00 |\n| 4 | Product-91 | 2018-10-23 00:00:00 |\n| 5 | Product-133 | 2019-01-24 00:00:00 |\n+----+-------------+---------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 3309, "s": 3224, "text": "The following is the query to grab the product with current date and the day before:" }, { "code": null, "e": 3440, "s": 3309, "text": "mysql> select *from ProductDemo\n -> where ProductOfferDate = CURDATE() OR ProductOfferDate = date_sub(curdate(),interval 1 day);" }, { "code": null, "e": 3469, "s": 3440, "text": "The following is the output:" }, { "code": null, "e": 3752, "s": 3469, "text": "+----+-------------+---------------------+\n| Id | ProductName | ProductOfferDate |\n+----+-------------+---------------------+\n| 2 | Product-22 | 2019-01-15 00:00:00 |\n| 3 | Product-21 | 2019-01-14 00:00:00 |\n+----+-------------+---------------------+\n2 rows in set (0.00 sec)" } ]
K- Fibonacci series
04 Feb, 2022 Given integers ‘K’ and ‘N’, the task is to find the Nth term of the K-Fibonacci series. In K – Fibonacci series, the first ‘K’ terms will be ‘1’ and after that every ith term of the series will be the sum of previous ‘K’ elements in the same series. Examples: Input: N = 4, K = 2 Output: 3 The K-Fibonacci series for K=2 is 1, 1, 2, 3, ... And, the 4th element is 3. Input: N = 5, K = 6 Output: 1 The K-Fibonacci series for K=6 is 1, 1, 1, 1, 1, 1, 6, 11, ... A simple approach: First, initialize the first ‘K’ elements to ‘1’. Then, calculate the sum of previous ‘K’ elements by running a loop from ‘i-k’ to ‘i-1’. Set the ith value to the sum. Time Complexity: O(N*K)An efficient approach: First, initialize the first ‘K’ elements to ‘1’. Create a variable named ‘sum’ which will be initialized with ‘K’. Set the value of (K+1)th element to sum. Set the next values as Array[i] = sum – Array[i-k-1] + Array[i-1] then update sum = Array[i]. In the end, display the Nth term of the array. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that finds the Nth// element of K-Fibonacci seriesvoid solve(int N, int K){ vector<long long int> Array(N + 1, 0); // If N is less than K // then the element is '1' if (N <= K) { cout << "1" << endl; return; } long long int i = 0, sum = K; // first k elements are 1 for (i = 1; i <= K; ++i) { Array[i] = 1; } // (K+1)th element is K Array[i] = sum; // find the elements of the // K-Fibonacci series for (int i = K + 2; i <= N; ++i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) Array[i] = sum - Array[i - K - 1] + Array[i - 1]; // set the new sum sum = Array[i]; } cout << Array[N] << endl;} // Driver codeint main(){ long long int N = 4, K = 2; // get the Nth value // of K-Fibonacci series solve(N, K); return 0;} // Java implementation of above approach public class GFG { // Function that finds the Nth // element of K-Fibonacci series static void solve(int N, int K) { int Array[] = new int[N + 1]; // If N is less than K // then the element is '1' if (N <= K) { System.out.println("1") ; return; } int i = 0 ; int sum = K; // first k elements are 1 for (i = 1; i <= K; ++i) { Array[i] = 1; } // (K+1)th element is K Array[i] = sum; // find the elements of the // K-Fibonacci series for (i = K + 2; i <= N; ++i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) Array[i] = sum - Array[i - K - 1] + Array[i - 1]; // set the new sum sum = Array[i]; } System.out.println(Array[N]); } public static void main(String args[]) { int N = 4, K = 2; // get the Nth value // of K-Fibonacci series solve(N, K); } // This code is contributed by ANKITRAI1} # Python3 implementation of above approach # Function that finds the Nth# element of K-Fibonacci seriesdef solve(N, K) : Array = [0] * (N + 1) # If N is less than K # then the element is '1' if (N <= K) : print("1") return i = 0 sm = K # first k elements are 1 for i in range(1, K + 1) : Array[i] = 1 # (K+1)th element is K Array[i + 1] = sm # find the elements of the # K-Fibonacci series for i in range(K + 2, N + 1) : # subtract the element at index i-k-1 # and add the element at index i-i # from the sum (sum contains the sum # of previous 'K' elements ) Array[i] = sm - Array[i - K - 1] + Array[i - 1] # set the new sum sm = Array[i] print(Array[N]) # Driver codeN = 4K = 2 # get the Nth value# of K-Fibonacci seriessolve(N, K) # This code is contributed by Nikita Tiwari. // C# implementation of above approachusing System; class GFG { // Function that finds the Nth // element of K-Fibonacci series public static void solve(int N, int K) { int[] Array = new int[N + 1]; // If N is less than K // then the element is '1' if (N <= K) { Console.WriteLine("1"); return; } int i = 0; int sum = K; // first k elements are 1 for (i = 1; i <= K; ++i) { Array[i] = 1; } // (K+1)th element is K Array[i] = sum; // find the elements of the // K-Fibonacci series for (i = K + 2; i <= N; ++i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) Array[i] = sum - Array[i - K - 1] + Array[i - 1]; // set the new sum sum = Array[i]; } Console.WriteLine(Array[N]); } // Main Method public static void Main(string[] args) { int N = 4, K = 2; // get the Nth value // of K-Fibonacci series solve(N, K); } } // This code is contributed// by Shrikant13 <?php// PHP implementation of above approach // Function that finds the Nth// element of K-Fibonacci seriesfunction solve($N, $K){ $Array = array_fill(0, $N + 1, NULL); // If N is less than K // then the element is '1' if ($N <= $K) { echo "1" ."\n"; return; } $i = 0; $sum = $K; // first k elements are 1 for ($i = 1; $i <= $K; ++$i) { $Array[$i] = 1; } // (K+1)th element is K $Array[$i] = $sum; // find the elements of the // K-Fibonacci series for ($i = $K + 2; $i <= $N; ++$i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) $Array[$i] = $sum - $Array[$i - $K - 1] + $Array[$i - 1]; // set the new sum $sum = $Array[$i]; } echo $Array[$N] . "\n";} // Driver code$N = 4;$K = 2; // get the Nth value// of K-Fibonacci seriessolve($N, $K); // This code is contributed// by ChitraNayal?> <script> //Javascript program to find// next greater number than N // Function that finds the Nth// element of K-Fibonacci seriesfunction solve(N, K){ var Arr = new Array(N + 1); // If N is less than K // then the element is '1' if (N <= K) { document.write( "1" + "<br>"); return; } var i = 0, sum = K; // first k elements are 1 for (i = 1; i <= K; ++i) { Arr[i] = 1; } // (K+1)th element is K Arr[i] = sum; // find the elements of the // K-Fibonacci series for (var i = K + 2; i <= N; ++i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) Arr[i] = sum - Arr[i - K - 1] + Arr[i - 1]; // set the new sum sum = Arr[i]; } document.write( Arr[N] + "<br>");} var N = 4, K = 2; // get the Nth value // of K-Fibonacci series solve(N, K); // This code is contributed by SoumikMondal </script> 3 Time Complexity: O(N) ankthon shrikanth13 ukasp Nikita tiwari SoumikMondal sumitgumber28 Fibonacci Competitive Programming Dynamic Programming Dynamic Programming Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of strings whose prefix match with the given string to a given length k Most important type of Algorithms The Ultimate Beginner's Guide For DSA Find two numbers from their sum and XOR C++: Methods of code shortening in competitive programming Largest Sum Contiguous Subarray Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Feb, 2022" }, { "code": null, "e": 143, "s": 54, "text": "Given integers ‘K’ and ‘N’, the task is to find the Nth term of the K-Fibonacci series. " }, { "code": null, "e": 307, "s": 143, "text": "In K – Fibonacci series, the first ‘K’ terms will be ‘1’ and after that every ith term of the series will be the sum of previous ‘K’ elements in the same series. " }, { "code": null, "e": 319, "s": 307, "text": "Examples: " }, { "code": null, "e": 520, "s": 319, "text": "Input: N = 4, K = 2\nOutput: 3\nThe K-Fibonacci series for K=2 is 1, 1, 2, 3, ...\nAnd, the 4th element is 3.\n\nInput: N = 5, K = 6\nOutput: 1\nThe K-Fibonacci series for K=6 is 1, 1, 1, 1, 1, 1, 6, 11, ..." }, { "code": null, "e": 543, "s": 522, "text": "A simple approach: " }, { "code": null, "e": 592, "s": 543, "text": "First, initialize the first ‘K’ elements to ‘1’." }, { "code": null, "e": 680, "s": 592, "text": "Then, calculate the sum of previous ‘K’ elements by running a loop from ‘i-k’ to ‘i-1’." }, { "code": null, "e": 710, "s": 680, "text": "Set the ith value to the sum." }, { "code": null, "e": 758, "s": 710, "text": "Time Complexity: O(N*K)An efficient approach: " }, { "code": null, "e": 807, "s": 758, "text": "First, initialize the first ‘K’ elements to ‘1’." }, { "code": null, "e": 873, "s": 807, "text": "Create a variable named ‘sum’ which will be initialized with ‘K’." }, { "code": null, "e": 914, "s": 873, "text": "Set the value of (K+1)th element to sum." }, { "code": null, "e": 1008, "s": 914, "text": "Set the next values as Array[i] = sum – Array[i-k-1] + Array[i-1] then update sum = Array[i]." }, { "code": null, "e": 1055, "s": 1008, "text": "In the end, display the Nth term of the array." }, { "code": null, "e": 1108, "s": 1055, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1112, "s": 1108, "text": "C++" }, { "code": null, "e": 1117, "s": 1112, "text": "Java" }, { "code": null, "e": 1125, "s": 1117, "text": "Python3" }, { "code": null, "e": 1128, "s": 1125, "text": "C#" }, { "code": null, "e": 1132, "s": 1128, "text": "PHP" }, { "code": null, "e": 1143, "s": 1132, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that finds the Nth// element of K-Fibonacci seriesvoid solve(int N, int K){ vector<long long int> Array(N + 1, 0); // If N is less than K // then the element is '1' if (N <= K) { cout << \"1\" << endl; return; } long long int i = 0, sum = K; // first k elements are 1 for (i = 1; i <= K; ++i) { Array[i] = 1; } // (K+1)th element is K Array[i] = sum; // find the elements of the // K-Fibonacci series for (int i = K + 2; i <= N; ++i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) Array[i] = sum - Array[i - K - 1] + Array[i - 1]; // set the new sum sum = Array[i]; } cout << Array[N] << endl;} // Driver codeint main(){ long long int N = 4, K = 2; // get the Nth value // of K-Fibonacci series solve(N, K); return 0;}", "e": 2196, "s": 1143, "text": null }, { "code": "// Java implementation of above approach public class GFG { // Function that finds the Nth // element of K-Fibonacci series static void solve(int N, int K) { int Array[] = new int[N + 1]; // If N is less than K // then the element is '1' if (N <= K) { System.out.println(\"1\") ; return; } int i = 0 ; int sum = K; // first k elements are 1 for (i = 1; i <= K; ++i) { Array[i] = 1; } // (K+1)th element is K Array[i] = sum; // find the elements of the // K-Fibonacci series for (i = K + 2; i <= N; ++i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) Array[i] = sum - Array[i - K - 1] + Array[i - 1]; // set the new sum sum = Array[i]; } System.out.println(Array[N]); } public static void main(String args[]) { int N = 4, K = 2; // get the Nth value // of K-Fibonacci series solve(N, K); } // This code is contributed by ANKITRAI1}", "e": 3441, "s": 2196, "text": null }, { "code": "# Python3 implementation of above approach # Function that finds the Nth# element of K-Fibonacci seriesdef solve(N, K) : Array = [0] * (N + 1) # If N is less than K # then the element is '1' if (N <= K) : print(\"1\") return i = 0 sm = K # first k elements are 1 for i in range(1, K + 1) : Array[i] = 1 # (K+1)th element is K Array[i + 1] = sm # find the elements of the # K-Fibonacci series for i in range(K + 2, N + 1) : # subtract the element at index i-k-1 # and add the element at index i-i # from the sum (sum contains the sum # of previous 'K' elements ) Array[i] = sm - Array[i - K - 1] + Array[i - 1] # set the new sum sm = Array[i] print(Array[N]) # Driver codeN = 4K = 2 # get the Nth value# of K-Fibonacci seriessolve(N, K) # This code is contributed by Nikita Tiwari.", "e": 4381, "s": 3441, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG { // Function that finds the Nth // element of K-Fibonacci series public static void solve(int N, int K) { int[] Array = new int[N + 1]; // If N is less than K // then the element is '1' if (N <= K) { Console.WriteLine(\"1\"); return; } int i = 0; int sum = K; // first k elements are 1 for (i = 1; i <= K; ++i) { Array[i] = 1; } // (K+1)th element is K Array[i] = sum; // find the elements of the // K-Fibonacci series for (i = K + 2; i <= N; ++i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) Array[i] = sum - Array[i - K - 1] + Array[i - 1]; // set the new sum sum = Array[i]; } Console.WriteLine(Array[N]); } // Main Method public static void Main(string[] args) { int N = 4, K = 2; // get the Nth value // of K-Fibonacci series solve(N, K); } } // This code is contributed// by Shrikant13", "e": 5699, "s": 4381, "text": null }, { "code": "<?php// PHP implementation of above approach // Function that finds the Nth// element of K-Fibonacci seriesfunction solve($N, $K){ $Array = array_fill(0, $N + 1, NULL); // If N is less than K // then the element is '1' if ($N <= $K) { echo \"1\" .\"\\n\"; return; } $i = 0; $sum = $K; // first k elements are 1 for ($i = 1; $i <= $K; ++$i) { $Array[$i] = 1; } // (K+1)th element is K $Array[$i] = $sum; // find the elements of the // K-Fibonacci series for ($i = $K + 2; $i <= $N; ++$i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) $Array[$i] = $sum - $Array[$i - $K - 1] + $Array[$i - 1]; // set the new sum $sum = $Array[$i]; } echo $Array[$N] . \"\\n\";} // Driver code$N = 4;$K = 2; // get the Nth value// of K-Fibonacci seriessolve($N, $K); // This code is contributed// by ChitraNayal?>", "e": 6748, "s": 5699, "text": null }, { "code": "<script> //Javascript program to find// next greater number than N // Function that finds the Nth// element of K-Fibonacci seriesfunction solve(N, K){ var Arr = new Array(N + 1); // If N is less than K // then the element is '1' if (N <= K) { document.write( \"1\" + \"<br>\"); return; } var i = 0, sum = K; // first k elements are 1 for (i = 1; i <= K; ++i) { Arr[i] = 1; } // (K+1)th element is K Arr[i] = sum; // find the elements of the // K-Fibonacci series for (var i = K + 2; i <= N; ++i) { // subtract the element at index i-k-1 // and add the element at index i-i // from the sum (sum contains the sum // of previous 'K' elements ) Arr[i] = sum - Arr[i - K - 1] + Arr[i - 1]; // set the new sum sum = Arr[i]; } document.write( Arr[N] + \"<br>\");} var N = 4, K = 2; // get the Nth value // of K-Fibonacci series solve(N, K); // This code is contributed by SoumikMondal </script>", "e": 7773, "s": 6748, "text": null }, { "code": null, "e": 7775, "s": 7773, "text": "3" }, { "code": null, "e": 7800, "s": 7777, "text": "Time Complexity: O(N) " }, { "code": null, "e": 7808, "s": 7800, "text": "ankthon" }, { "code": null, "e": 7820, "s": 7808, "text": "shrikanth13" }, { "code": null, "e": 7826, "s": 7820, "text": "ukasp" }, { "code": null, "e": 7840, "s": 7826, "text": "Nikita tiwari" }, { "code": null, "e": 7853, "s": 7840, "text": "SoumikMondal" }, { "code": null, "e": 7867, "s": 7853, "text": "sumitgumber28" }, { "code": null, "e": 7877, "s": 7867, "text": "Fibonacci" }, { "code": null, "e": 7901, "s": 7877, "text": "Competitive Programming" }, { "code": null, "e": 7921, "s": 7901, "text": "Dynamic Programming" }, { "code": null, "e": 7941, "s": 7921, "text": "Dynamic Programming" }, { "code": null, "e": 7951, "s": 7941, "text": "Fibonacci" }, { "code": null, "e": 8049, "s": 7951, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8127, "s": 8049, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 8161, "s": 8127, "text": "Most important type of Algorithms" }, { "code": null, "e": 8199, "s": 8161, "text": "The Ultimate Beginner's Guide For DSA" }, { "code": null, "e": 8239, "s": 8199, "text": "Find two numbers from their sum and XOR" }, { "code": null, "e": 8298, "s": 8239, "text": "C++: Methods of code shortening in competitive programming" }, { "code": null, "e": 8330, "s": 8298, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 8360, "s": 8330, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 8389, "s": 8360, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 8423, "s": 8389, "text": "Longest Common Subsequence | DP-4" } ]
Pass by Value and Pass by Reference in Javascript
19 Jan, 2021 In this article, we will talk about Pass by value and Pass by Reference in JavaScript . Pass By Value: In Pass by value, function is called by directly passing the value of the variable as an argument. So any changes made inside the function does not affect the original value. In Pass by value, parameters passed as an arguments create its own copy. So any changes made inside the function is made to the copied value not to the original value . Let us take an example to understand better: Javascript function Passbyvalue(a, b) { let tmp; tmp = b; b = a; a = tmp; console.log(`Inside Pass by value function -> a = ${a} b = ${b}`);} let a = 1;let b = 2;console.log(`Before calling Pass by value Function -> a = ${a} b = ${b}`); Passbyvalue(a, b); console.log(`After calling Pass by value Function -> a =${a} b = ${b}`); Output: Before calling Pass by value Function -> a = 1 b = 2 Inside Pass by value function -> a = 2 b = 1 After calling Pass by value Function -> a =1 b = 2 Pass by Reference: In Pass by Reference, Function is called by directly passing the reference/address of the variable as an argument. So changing the value inside the function also change the original value. In JavaScript array and Object follows pass by reference property. In Pass by reference, parameters passed as an arguments does not create its own copy, it refers to the original value so changes made inside function affect the original value. let us take an example to understand better. Javascript function PassbyReference(obj) { let tmp = obj.a; obj.a = obj.b; obj.b = tmp; console.log(`Inside Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`);} let obj = { a: 10, b: 20 }console.log(`Before calling Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`); PassbyReference(obj) console.log(`After calling Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`); Output: Before calling Pass By Reference Function -> a = 10 b = 20 Inside Pass By Reference Function -> a = 20 b = 10 After calling Pass By Reference Function -> a = 20 b = 10 Note: In Pass by Reference, we are mutating the original value. when we pass an object as an arguments and update that object’s reference in the function’s context, that won’t affect the object value. But if we mutate the object internally, It will affect the object . Example 1: Updating the object reference in the function. Javascript function PassbyReference(obj) { // Changing the reference of the object obj = { a: 10, b: 20, c: "GEEKSFORGEEKS" } console.log(`Inside Pass by Reference Function -> obj `); console.log(obj);} let obj = { a: 10, b: 20 }console.log(`Updating the object reference -> `)console.log(`Before calling Pass By Reference Function -> obj`);console.log(obj); PassbyReference(obj)console.log(`After calling Pass By Reference Function -> obj`);console.log(obj); Output: Updating the object reference -> Before calling PassByReference Function -> obj {a: 10, b: 20} Inside PassbyReference Function -> obj {a: 10, b: 20, c: "GEEKSFORGEEKS"} After calling PassByReference Function -> obj {a: 10, b: 20} Example 2: Mutating the original Object. Javascript function PassbyReference(obj) { // Mutating the origanal object obj.c = "GEEKSFORGEEKS"; console.log(`Inside Pass by Reference Function -> obj `); console.log(obj);} let obj = { a: 10, b: 20 }console.log(`Mutating the origanal object -> `)console.log(`Before calling Pass By Reference Function -> obj`);console.log(obj); PassbyReference(obj)console.log(`After calling Pass By Reference Function -> obj`);console.log(obj); Output: Mutating the origanal object -> Before calling PassByReference Function -> obj {a: 10, b: 20} Inside PassbyReference Function -> obj {a: 10, b: 20, c: "GEEKSFORGEEKS"} After calling PassByReference Function -> obj {a: 10, b: 20, c: "GEEKSFORGEEKS"} javascript-basics Picked Technical Scripter 2020 JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Jan, 2021" }, { "code": null, "e": 144, "s": 54, "text": "In this article, we will talk about Pass by value and Pass by Reference in JavaScript . " }, { "code": null, "e": 334, "s": 144, "text": "Pass By Value: In Pass by value, function is called by directly passing the value of the variable as an argument. So any changes made inside the function does not affect the original value." }, { "code": null, "e": 503, "s": 334, "text": "In Pass by value, parameters passed as an arguments create its own copy. So any changes made inside the function is made to the copied value not to the original value ." }, { "code": null, "e": 548, "s": 503, "text": "Let us take an example to understand better:" }, { "code": null, "e": 559, "s": 548, "text": "Javascript" }, { "code": "function Passbyvalue(a, b) { let tmp; tmp = b; b = a; a = tmp; console.log(`Inside Pass by value function -> a = ${a} b = ${b}`);} let a = 1;let b = 2;console.log(`Before calling Pass by value Function -> a = ${a} b = ${b}`); Passbyvalue(a, b); console.log(`After calling Pass by value Function -> a =${a} b = ${b}`);", "e": 918, "s": 559, "text": null }, { "code": null, "e": 926, "s": 918, "text": "Output:" }, { "code": null, "e": 1075, "s": 926, "text": "Before calling Pass by value Function -> a = 1 b = 2\nInside Pass by value function -> a = 2 b = 1\nAfter calling Pass by value Function -> a =1 b = 2" }, { "code": null, "e": 1350, "s": 1075, "text": "Pass by Reference: In Pass by Reference, Function is called by directly passing the reference/address of the variable as an argument. So changing the value inside the function also change the original value. In JavaScript array and Object follows pass by reference property." }, { "code": null, "e": 1528, "s": 1350, "text": "In Pass by reference, parameters passed as an arguments does not create its own copy, it refers to the original value so changes made inside function affect the original value. " }, { "code": null, "e": 1573, "s": 1528, "text": "let us take an example to understand better." }, { "code": null, "e": 1584, "s": 1573, "text": "Javascript" }, { "code": "function PassbyReference(obj) { let tmp = obj.a; obj.a = obj.b; obj.b = tmp; console.log(`Inside Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`);} let obj = { a: 10, b: 20 }console.log(`Before calling Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`); PassbyReference(obj) console.log(`After calling Pass By Reference Function -> a = ${obj.a} b = ${obj.b}`);", "e": 2001, "s": 1584, "text": null }, { "code": null, "e": 2009, "s": 2001, "text": "Output:" }, { "code": null, "e": 2177, "s": 2009, "text": "Before calling Pass By Reference Function -> a = 10 b = 20\nInside Pass By Reference Function -> a = 20 b = 10\nAfter calling Pass By Reference Function -> a = 20 b = 10" }, { "code": null, "e": 2446, "s": 2177, "text": "Note: In Pass by Reference, we are mutating the original value. when we pass an object as an arguments and update that object’s reference in the function’s context, that won’t affect the object value. But if we mutate the object internally, It will affect the object ." }, { "code": null, "e": 2504, "s": 2446, "text": "Example 1: Updating the object reference in the function." }, { "code": null, "e": 2515, "s": 2504, "text": "Javascript" }, { "code": "function PassbyReference(obj) { // Changing the reference of the object obj = { a: 10, b: 20, c: \"GEEKSFORGEEKS\" } console.log(`Inside Pass by Reference Function -> obj `); console.log(obj);} let obj = { a: 10, b: 20 }console.log(`Updating the object reference -> `)console.log(`Before calling Pass By Reference Function -> obj`);console.log(obj); PassbyReference(obj)console.log(`After calling Pass By Reference Function -> obj`);console.log(obj);", "e": 3045, "s": 2515, "text": null }, { "code": null, "e": 3053, "s": 3045, "text": "Output:" }, { "code": null, "e": 3285, "s": 3053, "text": "Updating the object reference -> \nBefore calling PassByReference Function -> obj\n{a: 10, b: 20}\nInside PassbyReference Function -> obj \n{a: 10, b: 20, c: \"GEEKSFORGEEKS\"}\nAfter calling PassByReference Function -> obj\n{a: 10, b: 20}" }, { "code": null, "e": 3326, "s": 3285, "text": "Example 2: Mutating the original Object." }, { "code": null, "e": 3337, "s": 3326, "text": "Javascript" }, { "code": "function PassbyReference(obj) { // Mutating the origanal object obj.c = \"GEEKSFORGEEKS\"; console.log(`Inside Pass by Reference Function -> obj `); console.log(obj);} let obj = { a: 10, b: 20 }console.log(`Mutating the origanal object -> `)console.log(`Before calling Pass By Reference Function -> obj`);console.log(obj); PassbyReference(obj)console.log(`After calling Pass By Reference Function -> obj`);console.log(obj);", "e": 3805, "s": 3337, "text": null }, { "code": null, "e": 3813, "s": 3805, "text": "Output:" }, { "code": null, "e": 4064, "s": 3813, "text": "Mutating the origanal object -> \nBefore calling PassByReference Function -> obj\n{a: 10, b: 20}\nInside PassbyReference Function -> obj \n{a: 10, b: 20, c: \"GEEKSFORGEEKS\"}\nAfter calling PassByReference Function -> obj\n{a: 10, b: 20, c: \"GEEKSFORGEEKS\"}" }, { "code": null, "e": 4082, "s": 4064, "text": "javascript-basics" }, { "code": null, "e": 4089, "s": 4082, "text": "Picked" }, { "code": null, "e": 4113, "s": 4089, "text": "Technical Scripter 2020" }, { "code": null, "e": 4124, "s": 4113, "text": "JavaScript" }, { "code": null, "e": 4143, "s": 4124, "text": "Technical Scripter" }, { "code": null, "e": 4160, "s": 4143, "text": "Web Technologies" } ]
Java program to find the average of given numbers using arrays
You can read data from the user using scanner class. Using the nextInt() method of this class get the number of elements from the user. Create an empty array. Store the elements entered by the user in the array created above. Finally, Add all the elements in the array and divide the sub by the number of elements. import java.util.Scanner; public class AverageUsingArrays { public static void main(String args[]){ //Reading total no.of elements Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements/numbers"); int num = sc.nextInt(); //Creating an array int[] myArray = new int[num]; //Read numbers from user and store it in an array System.out.println("Enter the numbers one by one : "); System.out.println("Press Enter button after each number : "); for(int i =0; i<num; i++){ myArray[i] = sc.nextInt(); } //Calculate the average double average = 0; for(int i =0; i<num; i++){ average = average + myArray[i]; } average = average/num; System.out.println("Average of given numbers :: "+average); } } Enter the number of elements/numbers 5 Enter the numbers one by one : Press Enter button after each number : 55 66 55 55 66 Average of given numbers :: 59.4
[ { "code": null, "e": 1115, "s": 1062, "text": "You can read data from the user using scanner class." }, { "code": null, "e": 1198, "s": 1115, "text": "Using the nextInt() method of this class get the number of elements from the user." }, { "code": null, "e": 1221, "s": 1198, "text": "Create an empty array." }, { "code": null, "e": 1288, "s": 1221, "text": "Store the elements entered by the user in the array created above." }, { "code": null, "e": 1377, "s": 1288, "text": "Finally, Add all the elements in the array and divide the sub by the number of elements." }, { "code": null, "e": 2227, "s": 1377, "text": "import java.util.Scanner;\npublic class AverageUsingArrays {\n public static void main(String args[]){\n\n //Reading total no.of elements\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the number of elements/numbers\");\n int num = sc.nextInt();\n\n //Creating an array\n int[] myArray = new int[num];\n\n //Read numbers from user and store it in an array\n System.out.println(\"Enter the numbers one by one : \");\n System.out.println(\"Press Enter button after each number : \");\n\n for(int i =0; i<num; i++){\n myArray[i] = sc.nextInt();\n }\n\n //Calculate the average\n double average = 0;\n for(int i =0; i<num; i++){\n average = average + myArray[i];\n }\n\n average = average/num;\n System.out.println(\"Average of given numbers :: \"+average);\n }\n}" }, { "code": null, "e": 2384, "s": 2227, "text": "Enter the number of elements/numbers\n5\nEnter the numbers one by one :\nPress Enter button after each number :\n55\n66\n55\n55\n66\nAverage of given numbers :: 59.4" } ]
Python - Add a prefix to column names in a Pandas DataFrame
To add a prefix to all the column names, use the add_prefix() method. At first, import the required Pandas library − import pandas as pd Create a DataFrame with 4 columns − dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250] }) Add a prefix to _column to every column using add_prefix() − dataFrame.add_prefix('column_') Following is the code − import pandas as pd # creating dataframe dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250] }) print"DataFrame ...\n",dataFrame print"\nUpdated DataFrame...\n",dataFrame.add_prefix('column_') This will produce the following output − DataFrame ... Car Cubic_Capacity Reg_Price Units_Sold 0 BMW 2000 7000 100 1 Lexus 1800 1500 120 2 Tesla 1500 5000 150 3 Mustang 2500 8000 110 4 Mercedes 2200 9000 200 5 Jaguar 3000 6000 250 Updated DataFrame... column_Car column_Cubic_Capacity column_Reg_Price column_Units_Sold 0 BMW 2000 7000 100 1 Lexus 1800 1500 120 2 Tesla 1500 5000 150 3 Mustang 2500 8000 110 4 Mercedes 2200 9000 200 5 Jaguar 3000 6000 250
[ { "code": null, "e": 1179, "s": 1062, "text": "To add a prefix to all the column names, use the add_prefix() method. At first, import the required Pandas library −" }, { "code": null, "e": 1199, "s": 1179, "text": "import pandas as pd" }, { "code": null, "e": 1235, "s": 1199, "text": "Create a DataFrame with 4 columns −" }, { "code": null, "e": 1481, "s": 1235, "text": "dataFrame = pd.DataFrame({\"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Cubic_Capacity\": [2000, 1800, 1500, 2500, 2200, 3000],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units_Sold\": [ 100, 120, 150, 110, 200, 250]\n})" }, { "code": null, "e": 1542, "s": 1481, "text": "Add a prefix to _column to every column using add_prefix() −" }, { "code": null, "e": 1575, "s": 1542, "text": "dataFrame.add_prefix('column_')\n" }, { "code": null, "e": 1599, "s": 1575, "text": "Following is the code −" }, { "code": null, "e": 1986, "s": 1599, "text": "import pandas as pd\n\n# creating dataframe\ndataFrame = pd.DataFrame({\"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Cubic_Capacity\": [2000, 1800, 1500, 2500, 2200, 3000],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\"Units_Sold\": [ 100, 120, 150, 110, 200, 250]\n})\n\nprint\"DataFrame ...\\n\",dataFrame\n\nprint\"\\nUpdated DataFrame...\\n\",dataFrame.add_prefix('column_')" }, { "code": null, "e": 2027, "s": 1986, "text": "This will produce the following output −" }, { "code": null, "e": 2973, "s": 2027, "text": "DataFrame ...\n Car Cubic_Capacity Reg_Price Units_Sold\n0 BMW 2000 7000 100\n1 Lexus 1800 1500 120\n2 Tesla 1500 5000 150\n3 Mustang 2500 8000 110\n4 Mercedes 2200 9000 200\n5 Jaguar 3000 6000 250\n\nUpdated DataFrame...\n column_Car column_Cubic_Capacity column_Reg_Price column_Units_Sold\n0 BMW 2000 7000 100\n1 Lexus 1800 1500 120\n2 Tesla 1500 5000 150\n3 Mustang 2500 8000 110\n4 Mercedes 2200 9000 200\n5 Jaguar 3000 6000 250" } ]
Use BigQuery free — without a credit card: Discover, learn and share | by Felipe Hoffa | Towards Data Science
Important update: I left Google and joined Snowflake in 2020 — so I’m unable to keep my older posts updated. If you want to try Snowflake, join us — I’m having a lot of fun ❄️. signup.snowflake.com See the official blog post “Query without a credit card: introducing BigQuery sandbox” for more details. Here we are going to focus on you getting started and querying as quickly as possible. Get into the BigQuery web UI and then follow the prompts. In 60 seconds and less than 4 steps you’ll be ready to start querying. Let’s find out who the most famous Alan is, according to Wikipedia. Enter this query into the new BigQuery web UI, and then click ‘run’: SELECT title, SUM(views) viewsFROM `fh-bigquery.wikipedia_v3.pageviews_2019`WHERE DATE(datehour) BETWEEN '2019-01-01' AND '2019-01-10'AND wiki='en'AND title LIKE r'Alan\_%'GROUP BY titleORDER BY views DESCLIMIT 10 Turns out Alan Turing was the one Alan with the largest # of pageviews in the English Wikipedia during the first 10 days of 2019. Try looking for other names or time periods. Can you guess who’s the most famous Steve? Let’s dissect the query, in case you’re new to BigQuery’s standard SQL: SELECT title, SUM(views) views: This gives me the total number of pageviews for each title. FROM `fh-bigquery.wikipedia_v3.pageviews_2019`: Scanning Wikipedia’s 2019 pageviews table. This table is shared by me. WHERE datehour BETWEEN ‘2019–01–01’ AND ‘2019–01–10’: We are only going to scan the first 10 days of 2019. AND wiki=’en’: There are many Wikipedias — and I want to focus only on the English one. This filter works well because the table primary clustering is which Wikipedia I want to query. Oh, had I filtered for en.m instead — the English Wikipedia for mobile — I would have received different results. AND title LIKE r’Alan\_%’: Asking for all Wikipedia pages that start with “Alan_”. This filter works well with the secondary clustering by title. Note that I need to escape the _ when doing a LIKE. GROUP BY title: We are going to get the SUM(views) for each title. ORDER BY views DESC: Sorting results by which page got most views. LIMIT 10: We only want to see the top 10. Some interesting things happened here: During these 10 days Wikipedia had more than 5.6 billion pageviews. Inside BigQuery this is represented by more than 72 GB of data. At a larger scale, the table for all 2018 Wikipedia pageviews is 2.25 TB. The cost of using BigQuery is proportional to the size of the columns scanned — and we have good news here: This gets much better when using tables that have been date partitioned and clustered. For example, the Alan query was going to cost me 73 GB, but thanks to partitions and clusters, it ended up scanning only 2 GB. This is a huge difference — it means I can perform 500 queries like this for free every month, instead of only 12. Let’s say we want to dive into all questions about Tensorflow on Stack Overflow. We can write a query like this: SELECT view_count, answer_count, DATE(creation_date) date, title FROM `bigquery-public-data.stackoverflow.posts_questions`WHERE 'tensorflow' IN UNNEST(SPLIT(tags, '|'))ORDER BY view_count DESCLIMIT 10 This query used 1.66 GB of our free quota — and each similar query will have a similar cost. We can do better: Extract the data you are interested in to a new table. With BigQuery’s sandbox mode now you also get 10 GB of storage for free. So instead of running new queries every time over the whole dataset, we can extract all Tensorflow questions to a new table. To create a new table, first create a dataset. Note that without a credit card associated to your account, BigQuery will limit the lifetime of any table to 60 days. To create a new table out of our previous query, BigQuery now supports DDL and DML SQL commands: CREATE TABLE `deleting.tensorflow_questions`ASSELECT view_count, answer_count, DATE(creation_date) date, title FROM `bigquery-public-data.stackoverflow.posts_questions`WHERE 'tensorflow' IN UNNEST(SPLIT(tags, '|')) Now I can write queries like this over my new table: SELECT view_count, answer_count, date, title FROM `deleting.tensorflow_questions`ORDER BY view_count DESC Good news: This query now scans only 3 MB, which gives me a lot more freedom to experiment. I can execute more than 300,000 queries like this for free every month! With BigQuery you can share your results and findings with your closest friends or the whole world. This is still not implemented on the new web UI, but it’s really easy on the BigQuery classic web UI: Multiple tools and frameworks can connect straight to BigQuery — we love them all. And now in the new BigQuery web UI you have a quick way to get your results into Data Studio: Subscribe to/r/bigquery to keep in touch with all of the BigQuery latest news. Check out our official public datasets and also some unofficial ones. Stuck? Ask the community on Stack Overflow. Missing me? Follow my latest posts on Medium and on Twitter @felipehoffa.
[ { "code": null, "e": 348, "s": 171, "text": "Important update: I left Google and joined Snowflake in 2020 — so I’m unable to keep my older posts updated. If you want to try Snowflake, join us — I’m having a lot of fun ❄️." }, { "code": null, "e": 369, "s": 348, "text": "signup.snowflake.com" }, { "code": null, "e": 561, "s": 369, "text": "See the official blog post “Query without a credit card: introducing BigQuery sandbox” for more details. Here we are going to focus on you getting started and querying as quickly as possible." }, { "code": null, "e": 690, "s": 561, "text": "Get into the BigQuery web UI and then follow the prompts. In 60 seconds and less than 4 steps you’ll be ready to start querying." }, { "code": null, "e": 827, "s": 690, "text": "Let’s find out who the most famous Alan is, according to Wikipedia. Enter this query into the new BigQuery web UI, and then click ‘run’:" }, { "code": null, "e": 1041, "s": 827, "text": "SELECT title, SUM(views) viewsFROM `fh-bigquery.wikipedia_v3.pageviews_2019`WHERE DATE(datehour) BETWEEN '2019-01-01' AND '2019-01-10'AND wiki='en'AND title LIKE r'Alan\\_%'GROUP BY titleORDER BY views DESCLIMIT 10" }, { "code": null, "e": 1259, "s": 1041, "text": "Turns out Alan Turing was the one Alan with the largest # of pageviews in the English Wikipedia during the first 10 days of 2019. Try looking for other names or time periods. Can you guess who’s the most famous Steve?" }, { "code": null, "e": 1331, "s": 1259, "text": "Let’s dissect the query, in case you’re new to BigQuery’s standard SQL:" }, { "code": null, "e": 1423, "s": 1331, "text": "SELECT title, SUM(views) views: This gives me the total number of pageviews for each title." }, { "code": null, "e": 1542, "s": 1423, "text": "FROM `fh-bigquery.wikipedia_v3.pageviews_2019`: Scanning Wikipedia’s 2019 pageviews table. This table is shared by me." }, { "code": null, "e": 1649, "s": 1542, "text": "WHERE datehour BETWEEN ‘2019–01–01’ AND ‘2019–01–10’: We are only going to scan the first 10 days of 2019." }, { "code": null, "e": 1947, "s": 1649, "text": "AND wiki=’en’: There are many Wikipedias — and I want to focus only on the English one. This filter works well because the table primary clustering is which Wikipedia I want to query. Oh, had I filtered for en.m instead — the English Wikipedia for mobile — I would have received different results." }, { "code": null, "e": 2145, "s": 1947, "text": "AND title LIKE r’Alan\\_%’: Asking for all Wikipedia pages that start with “Alan_”. This filter works well with the secondary clustering by title. Note that I need to escape the _ when doing a LIKE." }, { "code": null, "e": 2212, "s": 2145, "text": "GROUP BY title: We are going to get the SUM(views) for each title." }, { "code": null, "e": 2279, "s": 2212, "text": "ORDER BY views DESC: Sorting results by which page got most views." }, { "code": null, "e": 2321, "s": 2279, "text": "LIMIT 10: We only want to see the top 10." }, { "code": null, "e": 2360, "s": 2321, "text": "Some interesting things happened here:" }, { "code": null, "e": 2566, "s": 2360, "text": "During these 10 days Wikipedia had more than 5.6 billion pageviews. Inside BigQuery this is represented by more than 72 GB of data. At a larger scale, the table for all 2018 Wikipedia pageviews is 2.25 TB." }, { "code": null, "e": 3003, "s": 2566, "text": "The cost of using BigQuery is proportional to the size of the columns scanned — and we have good news here: This gets much better when using tables that have been date partitioned and clustered. For example, the Alan query was going to cost me 73 GB, but thanks to partitions and clusters, it ended up scanning only 2 GB. This is a huge difference — it means I can perform 500 queries like this for free every month, instead of only 12." }, { "code": null, "e": 3116, "s": 3003, "text": "Let’s say we want to dive into all questions about Tensorflow on Stack Overflow. We can write a query like this:" }, { "code": null, "e": 3317, "s": 3116, "text": "SELECT view_count, answer_count, DATE(creation_date) date, title FROM `bigquery-public-data.stackoverflow.posts_questions`WHERE 'tensorflow' IN UNNEST(SPLIT(tags, '|'))ORDER BY view_count DESCLIMIT 10" }, { "code": null, "e": 3681, "s": 3317, "text": "This query used 1.66 GB of our free quota — and each similar query will have a similar cost. We can do better: Extract the data you are interested in to a new table. With BigQuery’s sandbox mode now you also get 10 GB of storage for free. So instead of running new queries every time over the whole dataset, we can extract all Tensorflow questions to a new table." }, { "code": null, "e": 3846, "s": 3681, "text": "To create a new table, first create a dataset. Note that without a credit card associated to your account, BigQuery will limit the lifetime of any table to 60 days." }, { "code": null, "e": 3943, "s": 3846, "text": "To create a new table out of our previous query, BigQuery now supports DDL and DML SQL commands:" }, { "code": null, "e": 4158, "s": 3943, "text": "CREATE TABLE `deleting.tensorflow_questions`ASSELECT view_count, answer_count, DATE(creation_date) date, title FROM `bigquery-public-data.stackoverflow.posts_questions`WHERE 'tensorflow' IN UNNEST(SPLIT(tags, '|'))" }, { "code": null, "e": 4211, "s": 4158, "text": "Now I can write queries like this over my new table:" }, { "code": null, "e": 4317, "s": 4211, "text": "SELECT view_count, answer_count, date, title FROM `deleting.tensorflow_questions`ORDER BY view_count DESC" }, { "code": null, "e": 4481, "s": 4317, "text": "Good news: This query now scans only 3 MB, which gives me a lot more freedom to experiment. I can execute more than 300,000 queries like this for free every month!" }, { "code": null, "e": 4683, "s": 4481, "text": "With BigQuery you can share your results and findings with your closest friends or the whole world. This is still not implemented on the new web UI, but it’s really easy on the BigQuery classic web UI:" }, { "code": null, "e": 4860, "s": 4683, "text": "Multiple tools and frameworks can connect straight to BigQuery — we love them all. And now in the new BigQuery web UI you have a quick way to get your results into Data Studio:" }, { "code": null, "e": 4939, "s": 4860, "text": "Subscribe to/r/bigquery to keep in touch with all of the BigQuery latest news." }, { "code": null, "e": 5009, "s": 4939, "text": "Check out our official public datasets and also some unofficial ones." }, { "code": null, "e": 5053, "s": 5009, "text": "Stuck? Ask the community on Stack Overflow." } ]
How to make a Tkinter window not resizable?
Tkinter initially creates a resizable window for every application. Let us suppose that we want to make a non-resizable window in an application. In this case, we can use resizable(height, width) and pass the value of height=None and width=None. The method also works by passing Boolean values as resizable(False, False). #Import the required libraries from tkinter import * #Create an instance of tkinter frame win= Tk() #Set the geometry of frame win.geometry("600x250") #Set the resizable property False win.resizable(False, False) #Create a label for the window or frame Label(win, text="Hello World!", font=('Helvetica bold',20), anchor="center").pack(pady=20) win.mainloop() Running the above code will display a non-resizable window.
[ { "code": null, "e": 1384, "s": 1062, "text": "Tkinter initially creates a resizable window for every application. Let us suppose that we want to make a non-resizable window in an application. In this case, we can use resizable(height, width) and pass the value of height=None and width=None. The method also works by passing Boolean values as resizable(False, False)." }, { "code": null, "e": 1748, "s": 1384, "text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry of frame\nwin.geometry(\"600x250\")\n\n#Set the resizable property False\nwin.resizable(False, False)\n\n#Create a label for the window or frame\nLabel(win, text=\"Hello World!\", font=('Helvetica bold',20),\nanchor=\"center\").pack(pady=20)\n\nwin.mainloop()" }, { "code": null, "e": 1808, "s": 1748, "text": "Running the above code will display a non-resizable window." } ]
MySQLi - SSL Set
bool mysqli_ssl_set ( mysqli $link , string $key , string $cert , string $ca , string $capath , string $cipher ) It is used for establishing secure connections using SSL Try out following example − <?php $servername = "localhost:3306"; $username = "root"; $password = ""; $dbname = "TUTORIALS"; $con = mysqli_init(); if (!$con){ die("mysqli_init failed"); } mysqli_ssl_set($con,"key.pem","cert.pem","cacert.pem",NULL,NULL); $conn = new mysqli($servername, $username, $password, $dbname); if (!$conn->real_connect($con,$servername, $username, $password, $dbname)) { die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error()); } echo "Database connected"; printf("Client version: %d\n", mysqli_get_client_version()); mysqli_close($con); ?> The sample output of the above code should be like this − Database connected Client version: 50011 14 Lectures 1.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2381, "s": 2263, "text": "bool mysqli_ssl_set ( \n mysqli $link , string $key , string $cert , string $ca , string $capath , string $cipher )\n" }, { "code": null, "e": 2438, "s": 2381, "text": "It is used for establishing secure connections using SSL" }, { "code": null, "e": 2466, "s": 2438, "text": "Try out following example −" }, { "code": null, "e": 3087, "s": 2466, "text": "<?php\n $servername = \"localhost:3306\";\n $username = \"root\";\n $password = \"\";\n $dbname = \"TUTORIALS\";\n $con = mysqli_init();\n\n if (!$con){\n die(\"mysqli_init failed\");\n }\n mysqli_ssl_set($con,\"key.pem\",\"cert.pem\",\"cacert.pem\",NULL,NULL); \n $conn = new mysqli($servername, $username, $password, $dbname);\n \n if (!$conn->real_connect($con,$servername, $username, $password, $dbname)) {\n die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());\n }\n echo \"Database connected\";\n printf(\"Client version: %d\\n\", mysqli_get_client_version());\n\n mysqli_close($con);\n?>" }, { "code": null, "e": 3145, "s": 3087, "text": "The sample output of the above code should be like this −" }, { "code": null, "e": 3187, "s": 3145, "text": "Database connected Client version: 50011\n" }, { "code": null, "e": 3222, "s": 3187, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3245, "s": 3222, "text": " Stone River ELearning" }, { "code": null, "e": 3252, "s": 3245, "text": " Print" }, { "code": null, "e": 3263, "s": 3252, "text": " Add Notes" } ]
Seven Jupyter Notebook Setups to Improve Readability | by Sabi Horvat | Towards Data Science
Using coding blocks, or cells, that execute separately- although they may have a sequence dependency- is very useful for data model development. The Jupyter Notebooks interface has a simplicity that is easy to learn. Once you are versed in the basics, allow me to share seven setup modifications or enhancements that increase the readability of these notebooks. Seven Jupyter Notebook setups to increase readability: Dark ThemesExecution TimeScratchpadSplit CellsCodefoldingCollapsible HeadingsTable of Contents (2) Dark Themes Execution Time Scratchpad Split Cells Codefolding Collapsible Headings Table of Contents (2) Nbextensions options account for setups 2–7 (all except the Dark Themes). Most of these seven setups include options from within the jupyter_contrib_nbextensions. Please see the installation steps at readthedocs. For example, with pip: pip install jupyter_contrib_nbextensions or pip install https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tarball/master Once installed, when you launch Jupyter Notebooks you’ll see the Nbextensions option at the top. Upon clicking on Nbextensions, you’ll receive many options below. When you click on an option, a description of the option will appear below the list (scroll down in the Jupyter Notebook). While the description for Split Cells Notebook below is brief, some extensions have more detailed descriptions. Safety first. Dark themes are usually my first modification to default settings on software. Dark themes reduce the amount of eye strain by limiting the bright white lights which are more common as defaults. If I forget to set a dark theme, it doesn’t take long before I notice a drop in productivity and think to adjust the defaults. To install Jupyter Themes: pip install jupyterthemes To view the theme options available type jt -l: jt -l Output: Available Themes: chesterish grade3 gruvboxd gruvboxl monokai oceans16 onedork solarizedd solarizedl Not all of themes are dark themes actually. Examples of the themes are available on dunovank’s GitHub. If you want to customize your own theme, that is also available on the main GitHub page for Jupyter-Themes. I prefer the chesterish theme. In order to see the toolbars, name, and kernels in the Jupyter environment after changing themes, you’ll want to add -T -N and -kl to the command respectively. jt -t chesterish -T -N -kl Restart the Jupyter kernel, re-open your notebook, and voila! You now have the same theme as the screen captures in this article. However, plots and other images may not display as they would on a white background. For seaborn plots, the following command fixes this. import seaborn as snssns.set_theme(style=”whitegrid”) The Execution Time option allows you to see how long each cell takes to complete. Anyone working with models that take more than a couple minutes to execute can appreciate the ease of this time logging, but this is also helpful when comparing different options for cells while developing a new model. Enable the ExecuteTime option in Nbextensions and see the execution time shared below the executed code block. In this case the cell executed in 203ms. The Scratchpad option allows you to test code without temporarily creating and then deleting cell blocks. Enable the Scratchpad option in Nbextensions. The scratchpad button appears in the bottom right corner of the notebook. Click on the Scratchpad button to open the scratchpad. The scratchpad is an empty cell block that can utilize what has already run on the notebook kernel. But the Scratchpad can be modified and run without modifying any of the notebook cells. I find this a convenient place to lookup help details, print variables, or try something new without changing the existing notebook cells. The Split Cells option is helpful for notebook appearance and readability. Enable the Split Cells Notebook option in Nbextensions. Play around with pressing the ← → button to make a cell half-width, then go either above or below the cell to the previous or next cell and press the button again to bring cells that were previously separated horizontally to the new vertical separation. This can be particularly helpful with displaying data frames next to visualizations. This way, there is no need to scroll down to see either the data frame or visualization. The Codefolding option enables an expansion arrow that is used to hide indented code, enhancing notebook readability and appearance. Enable the Codefolding option in Nbextensions. Click on the arrow that appears for the option to hide indented code. The Collapsible Headings option is also helpful for notebook appearance and readability. Enable the Collapsible Headings option in Nbextensions. Using the arrows that are generated next to headings, collapse and expand the headings. The Table of Contents (2) option is another great way to navigate through a lengthy notebook fast. Enable the Table of Contents (2) option in Nbextensions. Click on the Table of Contents icon that appears after enabled. The table with hyperlinks will load at the top left of the notebook, under the toolbar icons. Drag it downward into a comfortable position such as below. When the need to navigate swiftly or read an overview of the section has passed, the Table of Contents can be removed from the notebook space by pressing its button once more. These are relatively quick Jupyter setups that I find quite useful for readability. But there are many more great packages that work with Jupyter. I’d like to share three honorable mentions that are wonderful for certain situations, although not necessary for every notebook. Honorable mentions: LaTeX for markdown, such as MacTex Autopep8 for the PEP 8 Style Guide Jupyter Slideshows using RISE
[ { "code": null, "e": 534, "s": 172, "text": "Using coding blocks, or cells, that execute separately- although they may have a sequence dependency- is very useful for data model development. The Jupyter Notebooks interface has a simplicity that is easy to learn. Once you are versed in the basics, allow me to share seven setup modifications or enhancements that increase the readability of these notebooks." }, { "code": null, "e": 589, "s": 534, "text": "Seven Jupyter Notebook setups to increase readability:" }, { "code": null, "e": 688, "s": 589, "text": "Dark ThemesExecution TimeScratchpadSplit CellsCodefoldingCollapsible HeadingsTable of Contents (2)" }, { "code": null, "e": 700, "s": 688, "text": "Dark Themes" }, { "code": null, "e": 715, "s": 700, "text": "Execution Time" }, { "code": null, "e": 726, "s": 715, "text": "Scratchpad" }, { "code": null, "e": 738, "s": 726, "text": "Split Cells" }, { "code": null, "e": 750, "s": 738, "text": "Codefolding" }, { "code": null, "e": 771, "s": 750, "text": "Collapsible Headings" }, { "code": null, "e": 793, "s": 771, "text": "Table of Contents (2)" }, { "code": null, "e": 867, "s": 793, "text": "Nbextensions options account for setups 2–7 (all except the Dark Themes)." }, { "code": null, "e": 1029, "s": 867, "text": "Most of these seven setups include options from within the jupyter_contrib_nbextensions. Please see the installation steps at readthedocs. For example, with pip:" }, { "code": null, "e": 1070, "s": 1029, "text": "pip install jupyter_contrib_nbextensions" }, { "code": null, "e": 1073, "s": 1070, "text": "or" }, { "code": null, "e": 1164, "s": 1073, "text": "pip install https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tarball/master" }, { "code": null, "e": 1261, "s": 1164, "text": "Once installed, when you launch Jupyter Notebooks you’ll see the Nbextensions option at the top." }, { "code": null, "e": 1327, "s": 1261, "text": "Upon clicking on Nbextensions, you’ll receive many options below." }, { "code": null, "e": 1562, "s": 1327, "text": "When you click on an option, a description of the option will appear below the list (scroll down in the Jupyter Notebook). While the description for Split Cells Notebook below is brief, some extensions have more detailed descriptions." }, { "code": null, "e": 1897, "s": 1562, "text": "Safety first. Dark themes are usually my first modification to default settings on software. Dark themes reduce the amount of eye strain by limiting the bright white lights which are more common as defaults. If I forget to set a dark theme, it doesn’t take long before I notice a drop in productivity and think to adjust the defaults." }, { "code": null, "e": 1924, "s": 1897, "text": "To install Jupyter Themes:" }, { "code": null, "e": 1950, "s": 1924, "text": "pip install jupyterthemes" }, { "code": null, "e": 1998, "s": 1950, "text": "To view the theme options available type jt -l:" }, { "code": null, "e": 2004, "s": 1998, "text": "jt -l" }, { "code": null, "e": 2012, "s": 2004, "text": "Output:" }, { "code": null, "e": 2114, "s": 2012, "text": "Available Themes: chesterish grade3 gruvboxd gruvboxl monokai oceans16 onedork solarizedd solarizedl" }, { "code": null, "e": 2325, "s": 2114, "text": "Not all of themes are dark themes actually. Examples of the themes are available on dunovank’s GitHub. If you want to customize your own theme, that is also available on the main GitHub page for Jupyter-Themes." }, { "code": null, "e": 2516, "s": 2325, "text": "I prefer the chesterish theme. In order to see the toolbars, name, and kernels in the Jupyter environment after changing themes, you’ll want to add -T -N and -kl to the command respectively." }, { "code": null, "e": 2543, "s": 2516, "text": "jt -t chesterish -T -N -kl" }, { "code": null, "e": 2673, "s": 2543, "text": "Restart the Jupyter kernel, re-open your notebook, and voila! You now have the same theme as the screen captures in this article." }, { "code": null, "e": 2811, "s": 2673, "text": "However, plots and other images may not display as they would on a white background. For seaborn plots, the following command fixes this." }, { "code": null, "e": 2865, "s": 2811, "text": "import seaborn as snssns.set_theme(style=”whitegrid”)" }, { "code": null, "e": 3166, "s": 2865, "text": "The Execution Time option allows you to see how long each cell takes to complete. Anyone working with models that take more than a couple minutes to execute can appreciate the ease of this time logging, but this is also helpful when comparing different options for cells while developing a new model." }, { "code": null, "e": 3318, "s": 3166, "text": "Enable the ExecuteTime option in Nbextensions and see the execution time shared below the executed code block. In this case the cell executed in 203ms." }, { "code": null, "e": 3424, "s": 3318, "text": "The Scratchpad option allows you to test code without temporarily creating and then deleting cell blocks." }, { "code": null, "e": 3470, "s": 3424, "text": "Enable the Scratchpad option in Nbextensions." }, { "code": null, "e": 3544, "s": 3470, "text": "The scratchpad button appears in the bottom right corner of the notebook." }, { "code": null, "e": 3787, "s": 3544, "text": "Click on the Scratchpad button to open the scratchpad. The scratchpad is an empty cell block that can utilize what has already run on the notebook kernel. But the Scratchpad can be modified and run without modifying any of the notebook cells." }, { "code": null, "e": 3926, "s": 3787, "text": "I find this a convenient place to lookup help details, print variables, or try something new without changing the existing notebook cells." }, { "code": null, "e": 4001, "s": 3926, "text": "The Split Cells option is helpful for notebook appearance and readability." }, { "code": null, "e": 4057, "s": 4001, "text": "Enable the Split Cells Notebook option in Nbextensions." }, { "code": null, "e": 4311, "s": 4057, "text": "Play around with pressing the ← → button to make a cell half-width, then go either above or below the cell to the previous or next cell and press the button again to bring cells that were previously separated horizontally to the new vertical separation." }, { "code": null, "e": 4485, "s": 4311, "text": "This can be particularly helpful with displaying data frames next to visualizations. This way, there is no need to scroll down to see either the data frame or visualization." }, { "code": null, "e": 4618, "s": 4485, "text": "The Codefolding option enables an expansion arrow that is used to hide indented code, enhancing notebook readability and appearance." }, { "code": null, "e": 4665, "s": 4618, "text": "Enable the Codefolding option in Nbextensions." }, { "code": null, "e": 4735, "s": 4665, "text": "Click on the arrow that appears for the option to hide indented code." }, { "code": null, "e": 4824, "s": 4735, "text": "The Collapsible Headings option is also helpful for notebook appearance and readability." }, { "code": null, "e": 4880, "s": 4824, "text": "Enable the Collapsible Headings option in Nbextensions." }, { "code": null, "e": 4968, "s": 4880, "text": "Using the arrows that are generated next to headings, collapse and expand the headings." }, { "code": null, "e": 5067, "s": 4968, "text": "The Table of Contents (2) option is another great way to navigate through a lengthy notebook fast." }, { "code": null, "e": 5124, "s": 5067, "text": "Enable the Table of Contents (2) option in Nbextensions." }, { "code": null, "e": 5342, "s": 5124, "text": "Click on the Table of Contents icon that appears after enabled. The table with hyperlinks will load at the top left of the notebook, under the toolbar icons. Drag it downward into a comfortable position such as below." }, { "code": null, "e": 5518, "s": 5342, "text": "When the need to navigate swiftly or read an overview of the section has passed, the Table of Contents can be removed from the notebook space by pressing its button once more." }, { "code": null, "e": 5794, "s": 5518, "text": "These are relatively quick Jupyter setups that I find quite useful for readability. But there are many more great packages that work with Jupyter. I’d like to share three honorable mentions that are wonderful for certain situations, although not necessary for every notebook." }, { "code": null, "e": 5814, "s": 5794, "text": "Honorable mentions:" }, { "code": null, "e": 5849, "s": 5814, "text": "LaTeX for markdown, such as MacTex" }, { "code": null, "e": 5884, "s": 5849, "text": "Autopep8 for the PEP 8 Style Guide" } ]
ArrayList vs LinkedList in Java - GeeksforGeeks
27 Aug, 2021 An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the difference between two classes that are implemented to solve this problem named ArrayList and LinkedList is discussed. ArrayList is a part of the collection framework. It is present in the java.util package and provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. We can dynamically add and remove items. It automatically resizes itself. The following is an example to demonstrate the implementation of the ArrayList. Example Java // Java program to Illustrate Working of an ArrayList // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList of Integer type ArrayList<Integer> arrli = new ArrayList<Integer>(); // Appending the new elements // at the end of the list // using add () method via for loops for (int i = 1; i <= 5; i++) arrli.add(i); // Printing the ArrayList System.out.println(arrli); // Removing an element at index 3 // from the ArrayList // using remove() method arrli.remove(3); // Printing the ArrayList after // removing the element System.out.println(arrli); }} [1, 2, 3, 4, 5] [1, 2, 3, 5] LinkedList is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. The following is an example to demonstrate the implementation of the LinkedList. Note: This class implements the LinkedList Data Structure. Example Java // Java program to Demonstrate Working of a LinkedList // Importing required classesimport java.util.*; // Main classclass GFG { // main driver method public static void main(String args[]) { // Creating an object of the // class linked list LinkedList<String> object = new LinkedList<String>(); // Adding the elements to the object created // using add() and addLast() method // Custom input elements object.add("A"); object.add("B"); object.addLast("C"); // Print the current LinkedList System.out.println(object); // Removing elements from the List object // using remove() and removeFirst() method object.remove("B"); object.removeFirst(); System.out.println("Linked list after " + "deletion: " + object); }} [A, B, C] Linked list after deletion: [C] Now after having an adequate understanding of both of them let us do discuss the differences between ArrayList and LinkedList in Java KaashyapMSK vigneshrajan523 surinderdawra388 Java-ArrayList Java-Collections java-LinkedList java-list Difference Between Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Process and Thread Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Stack vs Heap Memory Allocation Difference Between Spark DataFrame and Pandas DataFrame Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java HashMap in Java with Examples
[ { "code": null, "e": 24640, "s": 24612, "text": "\n27 Aug, 2021" }, { "code": null, "e": 25055, "s": 24640, "text": "An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the difference between two classes that are implemented to solve this problem named ArrayList and LinkedList is discussed." }, { "code": null, "e": 25466, "s": 25055, "text": "ArrayList is a part of the collection framework. It is present in the java.util package and provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. We can dynamically add and remove items. It automatically resizes itself. The following is an example to demonstrate the implementation of the ArrayList. " }, { "code": null, "e": 25474, "s": 25466, "text": "Example" }, { "code": null, "e": 25479, "s": 25474, "text": "Java" }, { "code": "// Java program to Illustrate Working of an ArrayList // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an ArrayList of Integer type ArrayList<Integer> arrli = new ArrayList<Integer>(); // Appending the new elements // at the end of the list // using add () method via for loops for (int i = 1; i <= 5; i++) arrli.add(i); // Printing the ArrayList System.out.println(arrli); // Removing an element at index 3 // from the ArrayList // using remove() method arrli.remove(3); // Printing the ArrayList after // removing the element System.out.println(arrli); }}", "e": 26298, "s": 25479, "text": null }, { "code": null, "e": 26327, "s": 26298, "text": "[1, 2, 3, 4, 5]\n[1, 2, 3, 5]" }, { "code": null, "e": 26762, "s": 26327, "text": "LinkedList is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. The following is an example to demonstrate the implementation of the LinkedList. " }, { "code": null, "e": 26821, "s": 26762, "text": "Note: This class implements the LinkedList Data Structure." }, { "code": null, "e": 26829, "s": 26821, "text": "Example" }, { "code": null, "e": 26834, "s": 26829, "text": "Java" }, { "code": "// Java program to Demonstrate Working of a LinkedList // Importing required classesimport java.util.*; // Main classclass GFG { // main driver method public static void main(String args[]) { // Creating an object of the // class linked list LinkedList<String> object = new LinkedList<String>(); // Adding the elements to the object created // using add() and addLast() method // Custom input elements object.add(\"A\"); object.add(\"B\"); object.addLast(\"C\"); // Print the current LinkedList System.out.println(object); // Removing elements from the List object // using remove() and removeFirst() method object.remove(\"B\"); object.removeFirst(); System.out.println(\"Linked list after \" + \"deletion: \" + object); }}", "e": 27715, "s": 26834, "text": null }, { "code": null, "e": 27757, "s": 27715, "text": "[A, B, C]\nLinked list after deletion: [C]" }, { "code": null, "e": 27893, "s": 27759, "text": "Now after having an adequate understanding of both of them let us do discuss the differences between ArrayList and LinkedList in Java" }, { "code": null, "e": 27905, "s": 27893, "text": "KaashyapMSK" }, { "code": null, "e": 27921, "s": 27905, "text": "vigneshrajan523" }, { "code": null, "e": 27938, "s": 27921, "text": "surinderdawra388" }, { "code": null, "e": 27953, "s": 27938, "text": "Java-ArrayList" }, { "code": null, "e": 27970, "s": 27953, "text": "Java-Collections" }, { "code": null, "e": 27986, "s": 27970, "text": "java-LinkedList" }, { "code": null, "e": 27996, "s": 27986, "text": "java-list" }, { "code": null, "e": 28015, "s": 27996, "text": "Difference Between" }, { "code": null, "e": 28020, "s": 28015, "text": "Java" }, { "code": null, "e": 28025, "s": 28020, "text": "Java" }, { "code": null, "e": 28042, "s": 28025, "text": "Java-Collections" }, { "code": null, "e": 28140, "s": 28042, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28149, "s": 28140, "text": "Comments" }, { "code": null, "e": 28162, "s": 28149, "text": "Old Comments" }, { "code": null, "e": 28200, "s": 28162, "text": "Difference between Process and Thread" }, { "code": null, "e": 28261, "s": 28200, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28329, "s": 28261, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28361, "s": 28329, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 28417, "s": 28361, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 28432, "s": 28417, "text": "Arrays in Java" }, { "code": null, "e": 28476, "s": 28432, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28498, "s": 28476, "text": "For-each loop in Java" }, { "code": null, "e": 28523, "s": 28498, "text": "Reverse a string in Java" } ]
Python - math.atan() function - GeeksforGeeks
28 May, 2020 Math module contains a number of functions which is used for mathematical operations. The math.atan() function returns the arctangent of a number as a value. The value passed in this function should be between -PI/2 and PI/2 radians. Syntax: math.atan(x) Parameter:This method accepts only single parameters. x :This parameter is the value to be passed to atan() Returns:This function returns the arctangent of a number as a value. Below examples illustrate the use of above function: Example 1: # Python code to implement# the atan()function # importing "math"# for mathematical operations import math a = math.pi / 6 # returning the value of arctangent of pi / 6 print ("The value of tangent of pi / 6 is : ", end ="") print (math.atan(a)) Output: The value of tangent of pi / 6 is : 0.48234790710102493 Example 2: # Python code to implement# the atan()functionimport math import numpy as np import matplotlib.pyplot as plt in_array = np.linspace(0, np.pi, 10) out_array = [] for i in range(len(in_array)): out_array.append(math.atan(in_array[i])) i += 1 print("Input_Array : \n", in_array) print("\nOutput_Array : \n", out_array) plt.plot(in_array, out_array, "go:") plt.title("math.atan()") plt.xlabel("X") plt.ylabel("Y") plt.show() Output: Input_Array : [0. 0.34906585 0.6981317 1.04719755 1.3962634 1.74532925 2.0943951 2.44346095 2.7925268 3.14159265] Output_Array : [0.0, 0.3358423725664079, 0.6094709714274295, 0.808448792630022, 0.9492822422213403, 1.0504981725497873, 1.1253388328842984, 1.1823365638628716, 1.2269249964859286, 1.2626272556789118] Python math-library Python math-library-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n28 May, 2020" }, { "code": null, "e": 24135, "s": 23901, "text": "Math module contains a number of functions which is used for mathematical operations. The math.atan() function returns the arctangent of a number as a value. The value passed in this function should be between -PI/2 and PI/2 radians." }, { "code": null, "e": 24156, "s": 24135, "text": "Syntax: math.atan(x)" }, { "code": null, "e": 24210, "s": 24156, "text": "Parameter:This method accepts only single parameters." }, { "code": null, "e": 24264, "s": 24210, "text": "x :This parameter is the value to be passed to atan()" }, { "code": null, "e": 24333, "s": 24264, "text": "Returns:This function returns the arctangent of a number as a value." }, { "code": null, "e": 24386, "s": 24333, "text": "Below examples illustrate the use of above function:" }, { "code": null, "e": 24397, "s": 24386, "text": "Example 1:" }, { "code": "# Python code to implement# the atan()function # importing \"math\"# for mathematical operations import math a = math.pi / 6 # returning the value of arctangent of pi / 6 print (\"The value of tangent of pi / 6 is : \", end =\"\") print (math.atan(a)) ", "e": 24664, "s": 24397, "text": null }, { "code": null, "e": 24672, "s": 24664, "text": "Output:" }, { "code": null, "e": 24729, "s": 24672, "text": "The value of tangent of pi / 6 is : 0.48234790710102493\n" }, { "code": null, "e": 24740, "s": 24729, "text": "Example 2:" }, { "code": "# Python code to implement# the atan()functionimport math import numpy as np import matplotlib.pyplot as plt in_array = np.linspace(0, np.pi, 10) out_array = [] for i in range(len(in_array)): out_array.append(math.atan(in_array[i])) i += 1 print(\"Input_Array : \\n\", in_array) print(\"\\nOutput_Array : \\n\", out_array) plt.plot(in_array, out_array, \"go:\") plt.title(\"math.atan()\") plt.xlabel(\"X\") plt.ylabel(\"Y\") plt.show() ", "e": 25205, "s": 24740, "text": null }, { "code": null, "e": 25213, "s": 25205, "text": "Output:" }, { "code": null, "e": 25546, "s": 25213, "text": "Input_Array : \n [0. 0.34906585 0.6981317 1.04719755 1.3962634 1.74532925\n 2.0943951 2.44346095 2.7925268 3.14159265]\n\nOutput_Array : \n [0.0, 0.3358423725664079, 0.6094709714274295, 0.808448792630022, 0.9492822422213403, 1.0504981725497873, 1.1253388328842984, 1.1823365638628716, 1.2269249964859286, 1.2626272556789118]\n" }, { "code": null, "e": 25566, "s": 25546, "text": "Python math-library" }, { "code": null, "e": 25596, "s": 25566, "text": "Python math-library-functions" }, { "code": null, "e": 25603, "s": 25596, "text": "Python" }, { "code": null, "e": 25701, "s": 25603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25710, "s": 25701, "text": "Comments" }, { "code": null, "e": 25723, "s": 25710, "text": "Old Comments" }, { "code": null, "e": 25755, "s": 25723, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25811, "s": 25755, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25853, "s": 25811, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25895, "s": 25853, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25931, "s": 25895, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25970, "s": 25931, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25992, "s": 25970, "text": "Defaultdict in Python" }, { "code": null, "e": 26023, "s": 25992, "text": "Python | os.path.join() method" }, { "code": null, "e": 26050, "s": 26023, "text": "Python Classes and Objects" } ]
Analyze global COVID 19 data with Choropleth maps | by Mythili Krishnan | Towards Data Science
COVID-19 needs no introduction- it is the latest infectious disease that has gripped the whole world. So, have you wondered how the world has changed over this past few months? Can we visualize this change over months across different countries? Too many questions but we have a simple answer — we can easily do this using Choropleth maps and I will make it simple with minimum coding requirements. So without further ado let’s get started: This will be our agenda today: What is a Choropleth mapBrief about FoliumChoropleth maps using FoliumBrief about plotlyChoropleth maps using plotlyFew limitations of choropleth maps What is a Choropleth map Brief about Folium Choropleth maps using Folium Brief about plotly Choropleth maps using plotly Few limitations of choropleth maps Choropleth is a map or display that divides different geographical regions based on a statistical variable or data variable. It is a type of thematic map where different regions are shaded according to the variable in consideration and the proportion of representation of the variable for a region. For eg: consider Fig 1 below which shows the Per capita GDP across different countries: The map uses colour gradation with respect to GDP per capita to denote the different countries in the map above. Hence, 2 important things that we will require for creating the choropleth maps is: a) Geo-spatial data with the geographic boundaries like geo json files and b) Variables or data points for the colour coding Folium is a library in Python that can be used to visualize geo-spatial data. Leaflet.js is a java script library for creating maps and Folium combines the functionalities of Leaflet with python’s data wrangling abilities (i.e. cleaning and transforming complex datasets into simple formats) in order to create beautiful interactive maps. Folium helps to bind the data to create maps like choropleth and also enables marker features with HTML visualizations. Different map projections are also available like orthographic, natural earth etc and different map tiles like MapBox, StamenToner among others. Now let us consider the global COVID 19 dataset to create a choropleth map.You can get the dataset link in the References. a) First we need to generate the base map. Following code can be used for this: m = folium.Map(tiles = 'Stamen Terrain',min_zoom = 1.5)display(m) We will get an output like this: b) We have to get the geodata from the this link and then generate the choropleth map layer as given below: url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data'country_shapes = f'{url}/world-countries.json'folium.Choropleth( geo_data = country_shapes, min_zoom=2, name='Covid-19', data=df, columns=['Country', 'Confirmed'], key_on='feature.properties.name', fill_color='OrRd', nan_fill_color='black', legend_name = 'Total Confirmed COVID cases',).add_to(m)m c) Now we will add markers with details about the confirmed cases for each country with this code. The markers can be customized, we are using circular markers here: def plotDot(point): folium.CircleMarker(location = (point.latitude, point.longitude), radius = 5, weight = 2, popup = [point.Country, point.Confirmed, point.Recovered], fill_color = '#000000').add_to(m)covid_df.apply(plotDot, axis = 1)m.fit_bounds(m.get_bounds())m This is the final output with markers of Confirmed and Recovered cases.We can hover around the markers to look at the number of confirmed and recovered cases by country. In the plot below, the marker for India is highlighted: Now, we can create a similar map using plotly. Plotly is an open source Python visualization library.It can also be used to create html visualization with great animations. As with Folium, the graphs are interactive and comes with animation features. It is built on top of plotly.js and the visualization can be saved as an image as well. It also comes with a lot of customization and styling options with implementation being very simple. It is also compatible with dash which makes it easy to embed on blogs or other web applications. Dash is an open-source framework for building analytical applications, with no Java script required, and it is tightly integrated with the Plotly graphing library. Read more about it here. With more observations, plotly can give rise to performance issues. The recommendation is to use it offline. Let us now construct the choropleth map using plotly. This can be done by using a simple code with the same dataset as given below: fig = px.choropleth(df , locations = 'Country', locationmode = 'country names', color = 'Confirmed' ,animation_frame = 'Date')fig.update_layout(title_text = 'Global spread of Covid19')fig.show() The output is given below: Here we can have the animation pane by date that will provide the a view of how the confirmed cases has spread across different countries over the months and the rate of increase in the cases. The HTML visualization of the map can be saved using a single line of code and you can access the HTML version of the map here. import plotly.offline as py# html filepy.offline.plot(fig, filename='C:/plotlyplots/Global_covid.html') We learnt today how to use two different python libraries to create choropleth maps with the COVID-19 data. Plotly really scores in the area with easy zoom, filter and animation options in maps. However, there is no option of adding customized markers. Folium is especially helpful with choropleth and other maps as well. The customization options like custom pop ups, custom tiling, markers and other features make Folium a viable contender.Also, Folium is especially built for visualizing geo-spatial data while Plotly has a much wider usage. Finally few words on Choropleth maps: Choropleth maps are good for an overall view but some variations within a country/region might get missed because it assumes whole area has same value. There are few other limitations as well, like : a) Usage of absolute counts can be misleading at times, it is better to use standardized units of measurements like proportions/ratios b) Boundaries might not be continuous and large areas can dominate the display. c) There can be concerns in accuracy due to classification issues regarding how the data is classified. Unclassed choropleth maps with graphical values can eliminate the loss of information from classification. Despite these limitations, choropleth maps can be a very useful method for performing empirical studies and geo-spatial analysis. Do reach out to me in case you have any questions and drop in your comments. The full code can be accessed here on Github. I can be reached on medium, LinkedIn or Twitter. References: [1] Jochen Schiewe, Empirical Studies on the Visual Perception of Spatial Patterns in Choropleth Maps (2019), Springer [2] Jeffrey S. Torguson, Choropleth Map (2017), Wiley Online Library [3] Robert G Cromley and Ellen K Cromley, Choropleth map legend design for visualizing community health disparities (2009), International journal of heath geographics [3] Choropleth Maps in Python, Plotly Documentation [4] Choropleth Maps in Python, Folium Documentation [5] John Hopkins University,COVID-19 dataset references
[ { "code": null, "e": 417, "s": 171, "text": "COVID-19 needs no introduction- it is the latest infectious disease that has gripped the whole world. So, have you wondered how the world has changed over this past few months? Can we visualize this change over months across different countries?" }, { "code": null, "e": 570, "s": 417, "text": "Too many questions but we have a simple answer — we can easily do this using Choropleth maps and I will make it simple with minimum coding requirements." }, { "code": null, "e": 612, "s": 570, "text": "So without further ado let’s get started:" }, { "code": null, "e": 643, "s": 612, "text": "This will be our agenda today:" }, { "code": null, "e": 794, "s": 643, "text": "What is a Choropleth mapBrief about FoliumChoropleth maps using FoliumBrief about plotlyChoropleth maps using plotlyFew limitations of choropleth maps" }, { "code": null, "e": 819, "s": 794, "text": "What is a Choropleth map" }, { "code": null, "e": 838, "s": 819, "text": "Brief about Folium" }, { "code": null, "e": 867, "s": 838, "text": "Choropleth maps using Folium" }, { "code": null, "e": 886, "s": 867, "text": "Brief about plotly" }, { "code": null, "e": 915, "s": 886, "text": "Choropleth maps using plotly" }, { "code": null, "e": 950, "s": 915, "text": "Few limitations of choropleth maps" }, { "code": null, "e": 1337, "s": 950, "text": "Choropleth is a map or display that divides different geographical regions based on a statistical variable or data variable. It is a type of thematic map where different regions are shaded according to the variable in consideration and the proportion of representation of the variable for a region. For eg: consider Fig 1 below which shows the Per capita GDP across different countries:" }, { "code": null, "e": 1450, "s": 1337, "text": "The map uses colour gradation with respect to GDP per capita to denote the different countries in the map above." }, { "code": null, "e": 1534, "s": 1450, "text": "Hence, 2 important things that we will require for creating the choropleth maps is:" }, { "code": null, "e": 1609, "s": 1534, "text": "a) Geo-spatial data with the geographic boundaries like geo json files and" }, { "code": null, "e": 1659, "s": 1609, "text": "b) Variables or data points for the colour coding" }, { "code": null, "e": 1998, "s": 1659, "text": "Folium is a library in Python that can be used to visualize geo-spatial data. Leaflet.js is a java script library for creating maps and Folium combines the functionalities of Leaflet with python’s data wrangling abilities (i.e. cleaning and transforming complex datasets into simple formats) in order to create beautiful interactive maps." }, { "code": null, "e": 2118, "s": 1998, "text": "Folium helps to bind the data to create maps like choropleth and also enables marker features with HTML visualizations." }, { "code": null, "e": 2263, "s": 2118, "text": "Different map projections are also available like orthographic, natural earth etc and different map tiles like MapBox, StamenToner among others." }, { "code": null, "e": 2386, "s": 2263, "text": "Now let us consider the global COVID 19 dataset to create a choropleth map.You can get the dataset link in the References." }, { "code": null, "e": 2466, "s": 2386, "text": "a) First we need to generate the base map. Following code can be used for this:" }, { "code": null, "e": 2532, "s": 2466, "text": "m = folium.Map(tiles = 'Stamen Terrain',min_zoom = 1.5)display(m)" }, { "code": null, "e": 2565, "s": 2532, "text": "We will get an output like this:" }, { "code": null, "e": 2673, "s": 2565, "text": "b) We have to get the geodata from the this link and then generate the choropleth map layer as given below:" }, { "code": null, "e": 3088, "s": 2673, "text": "url = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data'country_shapes = f'{url}/world-countries.json'folium.Choropleth( geo_data = country_shapes, min_zoom=2, name='Covid-19', data=df, columns=['Country', 'Confirmed'], key_on='feature.properties.name', fill_color='OrRd', nan_fill_color='black', legend_name = 'Total Confirmed COVID cases',).add_to(m)m" }, { "code": null, "e": 3254, "s": 3088, "text": "c) Now we will add markers with details about the confirmed cases for each country with this code. The markers can be customized, we are using circular markers here:" }, { "code": null, "e": 3610, "s": 3254, "text": "def plotDot(point): folium.CircleMarker(location = (point.latitude, point.longitude), radius = 5, weight = 2, popup = [point.Country, point.Confirmed, point.Recovered], fill_color = '#000000').add_to(m)covid_df.apply(plotDot, axis = 1)m.fit_bounds(m.get_bounds())m" }, { "code": null, "e": 3836, "s": 3610, "text": "This is the final output with markers of Confirmed and Recovered cases.We can hover around the markers to look at the number of confirmed and recovered cases by country. In the plot below, the marker for India is highlighted:" }, { "code": null, "e": 3883, "s": 3836, "text": "Now, we can create a similar map using plotly." }, { "code": null, "e": 4373, "s": 3883, "text": "Plotly is an open source Python visualization library.It can also be used to create html visualization with great animations. As with Folium, the graphs are interactive and comes with animation features. It is built on top of plotly.js and the visualization can be saved as an image as well. It also comes with a lot of customization and styling options with implementation being very simple. It is also compatible with dash which makes it easy to embed on blogs or other web applications." }, { "code": null, "e": 4562, "s": 4373, "text": "Dash is an open-source framework for building analytical applications, with no Java script required, and it is tightly integrated with the Plotly graphing library. Read more about it here." }, { "code": null, "e": 4671, "s": 4562, "text": "With more observations, plotly can give rise to performance issues. The recommendation is to use it offline." }, { "code": null, "e": 4803, "s": 4671, "text": "Let us now construct the choropleth map using plotly. This can be done by using a simple code with the same dataset as given below:" }, { "code": null, "e": 5017, "s": 4803, "text": "fig = px.choropleth(df , locations = 'Country', locationmode = 'country names', color = 'Confirmed' ,animation_frame = 'Date')fig.update_layout(title_text = 'Global spread of Covid19')fig.show()" }, { "code": null, "e": 5044, "s": 5017, "text": "The output is given below:" }, { "code": null, "e": 5237, "s": 5044, "text": "Here we can have the animation pane by date that will provide the a view of how the confirmed cases has spread across different countries over the months and the rate of increase in the cases." }, { "code": null, "e": 5365, "s": 5237, "text": "The HTML visualization of the map can be saved using a single line of code and you can access the HTML version of the map here." }, { "code": null, "e": 5469, "s": 5365, "text": "import plotly.offline as py# html filepy.offline.plot(fig, filename='C:/plotlyplots/Global_covid.html')" }, { "code": null, "e": 6014, "s": 5469, "text": "We learnt today how to use two different python libraries to create choropleth maps with the COVID-19 data. Plotly really scores in the area with easy zoom, filter and animation options in maps. However, there is no option of adding customized markers. Folium is especially helpful with choropleth and other maps as well. The customization options like custom pop ups, custom tiling, markers and other features make Folium a viable contender.Also, Folium is especially built for visualizing geo-spatial data while Plotly has a much wider usage." }, { "code": null, "e": 6052, "s": 6014, "text": "Finally few words on Choropleth maps:" }, { "code": null, "e": 6252, "s": 6052, "text": "Choropleth maps are good for an overall view but some variations within a country/region might get missed because it assumes whole area has same value. There are few other limitations as well, like :" }, { "code": null, "e": 6387, "s": 6252, "text": "a) Usage of absolute counts can be misleading at times, it is better to use standardized units of measurements like proportions/ratios" }, { "code": null, "e": 6467, "s": 6387, "text": "b) Boundaries might not be continuous and large areas can dominate the display." }, { "code": null, "e": 6678, "s": 6467, "text": "c) There can be concerns in accuracy due to classification issues regarding how the data is classified. Unclassed choropleth maps with graphical values can eliminate the loss of information from classification." }, { "code": null, "e": 6808, "s": 6678, "text": "Despite these limitations, choropleth maps can be a very useful method for performing empirical studies and geo-spatial analysis." }, { "code": null, "e": 6885, "s": 6808, "text": "Do reach out to me in case you have any questions and drop in your comments." }, { "code": null, "e": 6931, "s": 6885, "text": "The full code can be accessed here on Github." }, { "code": null, "e": 6980, "s": 6931, "text": "I can be reached on medium, LinkedIn or Twitter." }, { "code": null, "e": 6992, "s": 6980, "text": "References:" }, { "code": null, "e": 7111, "s": 6992, "text": "[1] Jochen Schiewe, Empirical Studies on the Visual Perception of Spatial Patterns in Choropleth Maps (2019), Springer" }, { "code": null, "e": 7180, "s": 7111, "text": "[2] Jeffrey S. Torguson, Choropleth Map (2017), Wiley Online Library" }, { "code": null, "e": 7347, "s": 7180, "text": "[3] Robert G Cromley and Ellen K Cromley, Choropleth map legend design for visualizing community health disparities (2009), International journal of heath geographics" }, { "code": null, "e": 7399, "s": 7347, "text": "[3] Choropleth Maps in Python, Plotly Documentation" }, { "code": null, "e": 7451, "s": 7399, "text": "[4] Choropleth Maps in Python, Folium Documentation" } ]
PostgreSQL - Size of tablespace - GeeksforGeeks
22 Feb, 2021 In this article, we will look into the function that is used to get the size of the PostgreSQL database tablespace. The pg_tablespace_size() function is used to get the size of a tablespace of a table. This function accepts a tablespace name and returns the size in bytes. Syntax: select pg_tablespace_size('tablespace_name'); Example 1: Here we will query for the size of the pg_default tablespace using the below command: SELECT pg_size_pretty ( pg_tablespace_size ('pg_default') ); Output: Notice we used to make the pg_size_pretty() function to make the result humanly readable. The pg_size_pretty() function takes the result of another function and formats it using bytes, KB, MB, GB, or TB as required. Note: There is generally not much point in creating more than one tablespace per logical file system, since one cannot control the location of every individual file within a logical file system. However, PostgreSQL does not enforce limitations on creation of new tablespace, and indeed it is not directly aware of the file system boundaries on one’s system. It just stores files in the directories where one wants them to be stored. But for the sake of example, we will create a new tablespace and find its size. To create a new tablespace use the below command: CREATE TABLESPACE new_tablespace LOCATION 'C:\sample_tablespace\'; Now that we have created a new tablespace named new_tablespace, let’s find its size. Example 2: SELECT pg_size_pretty ( pg_tablespace_size ('new_tablespace') ); Output: RajuKumar19 PostgreSQL-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - LEFT JOIN PostgreSQL - Cursor PostgreSQL - Record type variable PostgreSQL - Copy Table PostgreSQL - Select Into PostgreSQL - Rename Table PostgreSQL - ROW_NUMBER Function PostgreSQL - TIME Data Type
[ { "code": null, "e": 23958, "s": 23930, "text": "\n22 Feb, 2021" }, { "code": null, "e": 24232, "s": 23958, "text": "In this article, we will look into the function that is used to get the size of the PostgreSQL database tablespace. The pg_tablespace_size() function is used to get the size of a tablespace of a table. This function accepts a tablespace name and returns the size in bytes. " }, { "code": null, "e": 24286, "s": 24232, "text": "Syntax: select pg_tablespace_size('tablespace_name');" }, { "code": null, "e": 24384, "s": 24286, "text": "Example 1: Here we will query for the size of the pg_default tablespace using the below command: " }, { "code": null, "e": 24461, "s": 24384, "text": "SELECT\n pg_size_pretty (\n pg_tablespace_size ('pg_default')\n );" }, { "code": null, "e": 24470, "s": 24461, "text": "Output: " }, { "code": null, "e": 24687, "s": 24470, "text": "Notice we used to make the pg_size_pretty() function to make the result humanly readable. The pg_size_pretty() function takes the result of another function and formats it using bytes, KB, MB, GB, or TB as required. " }, { "code": null, "e": 25121, "s": 24687, "text": "Note: There is generally not much point in creating more than one tablespace per logical file system, since one cannot control the location of every individual file within a logical file system. However, PostgreSQL does not enforce limitations on creation of new tablespace, and indeed it is not directly aware of the file system boundaries on one’s system. It just stores files in the directories where one wants them to be stored. " }, { "code": null, "e": 25252, "s": 25121, "text": "But for the sake of example, we will create a new tablespace and find its size. To create a new tablespace use the below command: " }, { "code": null, "e": 25319, "s": 25252, "text": "CREATE TABLESPACE new_tablespace LOCATION 'C:\\sample_tablespace\\';" }, { "code": null, "e": 25416, "s": 25319, "text": "Now that we have created a new tablespace named new_tablespace, let’s find its size. Example 2: " }, { "code": null, "e": 25497, "s": 25416, "text": "SELECT\n pg_size_pretty (\n pg_tablespace_size ('new_tablespace')\n );" }, { "code": null, "e": 25506, "s": 25497, "text": "Output: " }, { "code": null, "e": 25518, "s": 25506, "text": "RajuKumar19" }, { "code": null, "e": 25538, "s": 25518, "text": "PostgreSQL-function" }, { "code": null, "e": 25549, "s": 25538, "text": "PostgreSQL" }, { "code": null, "e": 25647, "s": 25549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25656, "s": 25647, "text": "Comments" }, { "code": null, "e": 25669, "s": 25656, "text": "Old Comments" }, { "code": null, "e": 25698, "s": 25669, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 25722, "s": 25698, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 25745, "s": 25722, "text": "PostgreSQL - LEFT JOIN" }, { "code": null, "e": 25765, "s": 25745, "text": "PostgreSQL - Cursor" }, { "code": null, "e": 25799, "s": 25765, "text": "PostgreSQL - Record type variable" }, { "code": null, "e": 25823, "s": 25799, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 25848, "s": 25823, "text": "PostgreSQL - Select Into" }, { "code": null, "e": 25874, "s": 25848, "text": "PostgreSQL - Rename Table" }, { "code": null, "e": 25907, "s": 25874, "text": "PostgreSQL - ROW_NUMBER Function" } ]
Python Program to Read Two Numbers and Print Their Quotient and Remainder
When it is required to read two numbers and print the quotient and remainder when they are divided, the ‘//’ and ‘%’ operators can be used. Below is a demonstration of the same − Live Demo first_num = int(input("Enter the first number...")) second_num = int(input("Enter the second number...")) print("The first number is ") print(first_num) print("The second number is ") print(second_num) quotient_val = first_num//second_num remainder_val = first_num%second_num print("The quotient is :") print(quotient_val) print("The remainder is :") print(remainder_val) Enter the first number...44 Enter the second number...56 The first number is 44 The second number is 56 The quotient is : 0 The remainder is : 44 The first and second numbers are taken as input from the user. The first and second numbers are taken as input from the user. They are displayed on the console. They are displayed on the console. To find the quotient, the ‘//’ operator is used. To find the quotient, the ‘//’ operator is used. To find the remainder, the ‘%’ operator is used. To find the remainder, the ‘%’ operator is used. The operations output is assigned to two variables respectively. The operations output is assigned to two variables respectively. This is displayed as output on the console. This is displayed as output on the console.
[ { "code": null, "e": 1202, "s": 1062, "text": "When it is required to read two numbers and print the quotient and remainder when they are divided, the ‘//’ and ‘%’ operators can be used." }, { "code": null, "e": 1241, "s": 1202, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1252, "s": 1241, "text": " Live Demo" }, { "code": null, "e": 1625, "s": 1252, "text": "first_num = int(input(\"Enter the first number...\"))\nsecond_num = int(input(\"Enter the second number...\"))\nprint(\"The first number is \")\nprint(first_num)\nprint(\"The second number is \")\nprint(second_num)\nquotient_val = first_num//second_num\nremainder_val = first_num%second_num\n\nprint(\"The quotient is :\")\nprint(quotient_val)\nprint(\"The remainder is :\")\nprint(remainder_val)" }, { "code": null, "e": 1771, "s": 1625, "text": "Enter the first number...44\nEnter the second number...56\nThe first number is\n44\nThe second number is\n56\nThe quotient is :\n0\nThe remainder is :\n44" }, { "code": null, "e": 1834, "s": 1771, "text": "The first and second numbers are taken as input from the user." }, { "code": null, "e": 1897, "s": 1834, "text": "The first and second numbers are taken as input from the user." }, { "code": null, "e": 1932, "s": 1897, "text": "They are displayed on the console." }, { "code": null, "e": 1967, "s": 1932, "text": "They are displayed on the console." }, { "code": null, "e": 2016, "s": 1967, "text": "To find the quotient, the ‘//’ operator is used." }, { "code": null, "e": 2065, "s": 2016, "text": "To find the quotient, the ‘//’ operator is used." }, { "code": null, "e": 2114, "s": 2065, "text": "To find the remainder, the ‘%’ operator is used." }, { "code": null, "e": 2163, "s": 2114, "text": "To find the remainder, the ‘%’ operator is used." }, { "code": null, "e": 2228, "s": 2163, "text": "The operations output is assigned to two variables respectively." }, { "code": null, "e": 2293, "s": 2228, "text": "The operations output is assigned to two variables respectively." }, { "code": null, "e": 2337, "s": 2293, "text": "This is displayed as output on the console." }, { "code": null, "e": 2381, "s": 2337, "text": "This is displayed as output on the console." } ]
Text Sentiment Analysis in NLP. Problems, use-cases, and methods: from... | by Arun Jagota | Towards Data Science
People like expressing sentiment. Happy or unhappy. Like or dislike. Praise or complain. Good or bad. That is, positive or negative. Sentiment analysis in NLP is about deciphering such sentiment from text. Is it positive, negative, both, or neither? If there is sentiment, which objects in the text the sentiment is referring to and the actual sentiment phrase such as poor, blurry, inexpensive, ... (Not just positive or negative.) This is also called aspect-based analysis [1]. As a technique, sentiment analysis is both interesting and useful. First, to the interesting part. It’s not always easy to tell, at least not for a computer algorithm, whether a text’s sentiment is positive, negative, both, or neither. The cues can be subtle. Overall sentiment aside, it’s even harder to tell which objects in the text are the subject of which sentiment, especially when both positive and negative sentiments are involved. Next, to the useful part. This is easy to explain. People who sell things want to know about how people feel about these things. It is called customer feedback 😊. Ignoring it is bad for business. There are other uses as well. Such as opinion mining, i.e. trying to figure out who holds (or held) what opinions. Such as, according to John Smith, the coronavirus will simply go away within six months. This task may be formalized as seeking (source, target, opinion) triples. In our example, source = John Smith, target = coronavirus, opinion = will simply go away within six months. (Many) Examples Sentiment analysis is what you might call a long-tail problem. Lots of varying scenarios and subtleties. Such problems are often best described by examples. First, let’s see some easy positives. Amazing customer service.Love it.Good price. Next, some positives and negatives a bit harder to discriminate. Positives: What is not to like about this product. Not bad. Not an issue. Not buggy.Negatives: Not happy. Not user-friendly. Not good.Definitely not positive: Is it any good? The positives in the above list are not the strongest ones. That said, they are especially good for training ML algorithms to make key distinctions, as we definitely don’t want these positives to be predicted as negatives. Positives: Low price.Negatives: Low quality. These instances are especially good for training ML algorithms to make key distinctions. Positives: Quick turn-around.Negatives: Quick to fail. The same point applies here. Positives: Inexpensive.Negatives: cheap. The same point applies here. Finally, some negatives which are a bit harder to decipher. I didn’t get what I was promised.My package hasn’t arrived yet.No one in your team has been able to solve my problem.I was put on hold for an hour!Why is this so hard to use?Why does it fail so easily? Use Cases It’s easy to imagine many. Here are some of the main specific ones. Discover negative reviews of your product or service. On blog posts or eCommerce sites or social media. More broadly anywhere on the web.Aggregate sentiment on financial instruments. Such as specific stocks. What is the recent market sentiment on stock xyz? Also, aspect-based variants. Such as according to analysts at financial company xyz, stock abc is likely to grow 20% in the coming year. Discerning who’s opinion it is provides more information, which may be used to assess credibility or lack thereof.Identify which components of your product or service are people complaining about? Especially strongly. For prioritizing tactical or long-term improvements.Track changes to customer sentiment over time for a specific product or service (or a line of these). To check if things have been getting better ...Track shifting opinions of politicians over time. Individuals or groups such as political parties. News media love to do this. To fuel nagging questions such as you said that then but now this!. Discover negative reviews of your product or service. On blog posts or eCommerce sites or social media. More broadly anywhere on the web. Aggregate sentiment on financial instruments. Such as specific stocks. What is the recent market sentiment on stock xyz? Also, aspect-based variants. Such as according to analysts at financial company xyz, stock abc is likely to grow 20% in the coming year. Discerning who’s opinion it is provides more information, which may be used to assess credibility or lack thereof. Identify which components of your product or service are people complaining about? Especially strongly. For prioritizing tactical or long-term improvements. Track changes to customer sentiment over time for a specific product or service (or a line of these). To check if things have been getting better ... Track shifting opinions of politicians over time. Individuals or groups such as political parties. News media love to do this. To fuel nagging questions such as you said that then but now this!. Computational Problems What we’ve discussed thus far may be crystallized into two distinct computational problems. What is the text’s overall sentiment: positive, negative, both, or neither?Which sentiment applies to which portions of the text. This is also called aspect-based sentiment analysis. What is the text’s overall sentiment: positive, negative, both, or neither? Which sentiment applies to which portions of the text. This is also called aspect-based sentiment analysis. Let’s start with the first problem, which we will call sentiment classification. Sentiment Classification Problem The input is text. The output we seek is whether the sentiment is positive, negative, both or neither. In a variant of this problem, which we will not address here, we are interested in additionally predicting the strengths of the positive and negative sentiments. You can imagine why. xyz phone really sucks is way more negative than I’m a little disappointed with xyz phone. Dictionary-based Approach The simplest approach is to create two dictionaries, of terms carrying positive and negative sentiment respectively. By term, we mean a word or a phrase. A text is classified as positive or negative based on hits of the terms in the text to these two dictionaries. A text is classified as neutral if it hits neither dictionary. A text is classified as both positive and negative if it hits in both dictionaries. This approach is worth considering when one wishes to quickly get a somewhat effective sentiment classifier off-the-ground and one doesn’t have a rich-enough data set of text labeled with the sentiment. Simplicity is one reason. The more important reason is that the machine learning alternative has its own obstacles to be overcome. We’ll delve into these in detail when we discuss that topic. Machine-learning obstacles notwithstanding, a dictionary-based approach will run into quality issues sooner or later. So if high precision and high recall of the various sentiment classes are important in your use case, you should consider biting the bullet upfront and investing in ML. Your task will become much easier if you can find a rich-enough labeled data set or come up with some creative ways to get one, possibly after some additional lightweight NLP (discussed in an upcoming section). Supervised Learning Challenges The first challenge is the necessity of having a large and diverse data set of texts labeled with their sentiment classes: positive, negative, both, or neither. The issue is this. Think of the text as being represented by a vector. For now in the usual vector space model, i.e. as a bag of words. That said, the challenge applies, albeit to a somewhat lesser extent, even to word embeddings. The vector space is huge. Each word in the lexicon has a dimension. The vast majority of the words in this space carry no sentiment. To train a machine learning classifier would require a huge training set. Much of what it would be doing is learning which words are “nuisance” words. That is, unlearning biases it collected along the way (see example below). Let’s see an example from which the classifier can learn to wrongly associate neutral words with positive or negative sentiment. xyz phone sucks → negative It will learn to associate the word phone with the sentiment negative. Obviously we don’t want this. Unlearning this will require training set instances with the word phone in them that are labeled neither (i.e., neutral). That being said, breaking up a large and diverse corpus (such as Wikipedia) into sentences and labeling each neutral might alleviate this problem. The intuition here is this. All words will initially learn to be neutral. Words such as sucks that repeatedly occur in text labeled negative will eventually ‘escape’ from their neutral label. Beyond Bag-of-words Features From the labeled examples we saw in an earlier section, it seems that a ‘?’ is a predictor of sentiment. This makes sense intuitively. Skeptics ask questions. Not true believers. Leveraging Dictionaries as Features If we already have dictionaries of phrases correlated with positive or negative sentiment (or find them easy to construct), why not use them as additional features. They don’t have to be complete. Just curated. So we can take advantage of their quality. In more detail, here’s how. Say not good is in the dictionary of negatives. We would create a boolean feature for this entry. This feature’s value is 1 if not good appears in text and 0 if not. We might also add the entry (not good, negative) to our training set. Note that here we are thinking of not good as the full text. Use Part-of-speech? Sentiment-rich words are often adjectives. This makes one wonder whether using information about the part-of-speech of each word in the text might be useful? As additional features or for pruning features. Let’s start by looking at the parts-of-speech of the words in our various examples. This analysis was done using the online pos-tagger at [2]. What thoughts does this trigger? The POS-tag adjective seems significantly correlated with sentiment polarity (positive or negative). The POS-tag adverb also. Determiners, prepositions, and pronouns seem to predict the neutral class. How might we take advantage of this? We could gate bag-of-words features on their parts-of-speech. For example, filter out all words whose POS-tag is determiner, preposition, or pronoun. This may be viewed as an elaborate form of stop-words removal. Feature Engineering: Some Observations Whereas these observations are general, they especially apply to our problem (sentiment classification). First, we don’t need strong evidence before we add a new feature. Merely a weak belief that it might help. The machine learning algorithm will figure out how predictive this feature is, possibly in conjunction with other features. As the training set gets richer over time, the ML will automatically learn to use this feature more effectively if this is possible. Weak features can add up. The only downside to this is that if we go overboard, i.e. add too many features, the feature space explosion may come back to haunt us. More on that later. Let’s expand on “weak belief that it might help”. Here, ‘help’ just means that the feature is predictive of some sentiment class. We don’t need to know which. The ML will figure this out. That is, which feature value predicts which sentiment class. By contrast, when setting up a rule-based system (of which dictionaries are a special case) one has to specify which combinations of feature values predict which sentiment class. Does This Risk Feature Space Explosion? We have already accepted that using bag-of-words features will explode our feature space. For reasons discussed earlier, we have decided to bite the bullet on this front. The question is, will the additional features mentioned in this section make the matter worse? Actually they will make it better. Let’s reason through this. First the question-mark feature. It is boolean-valued. No explosion here. Next, the dictionary-based features. These in fact reduce the noise in the space of word vectors as they surface sentiment-rich words and phrases. Finally, the part-of-speech features. Using them as suggested, for filtering (i.e. removing words), prunes the feature space. Word k-gram Features? We deliberately put this after the previous section because this does run a greater risk of exploding the feature space if not done right. The space of word k-grams even with k = 2 is huge. That said, pruning this space sensibly can potentially increase the benefit-to-cost ratio from these features. Below are some plausible ideas to consider. In the discussion, we limit ourselves to k=2, i.e. to bigrams, although it applies more generally. Prune away bigrams from the model that don’t have sufficient support in the training set. (By the support of a bigram we mean the number of times it occurs in the training set.)For additional pruning, consider parts-of-speech as well. Prune away bigrams from the model that don’t have sufficient support in the training set. (By the support of a bigram we mean the number of times it occurs in the training set.) For additional pruning, consider parts-of-speech as well. Taking Stock ... We’ll close this section by taking stock of what we have discussed here and its implications. First, we see that the ML approach can be empowered with a variety of features. We simply throw features into the mix. So long as there is a plausible case for each inclusion. We don’t worry about correlations among features. Too complicated to analyze. Let the ML sort it out. The end justifies the means. So long as we have a rich enough labeled data set which we can partition to train-and-test splits and reliably measure the quality of what we are referring to as ‘end’. We do need to think about the feature space explosion. We already did. Now a few words about the learning algorithm. We have lots of choices. Naive Bayes. Logistic Regression. Decision Tree. Random Forest. Gradient Boosting. Maybe even Deep Learning. The key point to bring to the surface is that these choices span varying levels of sophistication. Some can automatically discover multivariate features that are especially predictive of sentiment. The risk here is that many of the multivariate features they discover are also noisy. Okay so now we have lots of feature choices and lots of learning algorithm choices. Potentially very powerful. But also risky. As mentioned earlier, we can mitigate the risk by keeping in mind the feature-space explosion. Ultimately though we should focus on building as rich of a labeled data set, even if only incrementally. Longer-term this has more value than tactically optimizing features to compensate for not having a great training set. This is the single most important aspect of this problem. Invest in this. Target Variants To this point, we’ve been thinking of sentiment classification as a 4-class problem: positive, negative, both, neither. In some settings, the class both can be ignored. In such settings, we interpret neither as neutral. In most use cases, we only care about the first two. So neutral is a nuisance class. ‘Nuisance’ means it needs to be accounted for, even though it’s not what we seek. Why does it need to be accounted for? Well, we don’t want text that is neutral to get classified as positive or negative. Said another way, including the neutral class (backed by a sufficiently rich training set for it), improves the precision of the positives and negatives. This is easy to illustrate with an example. Remember the instance xyz phone sucks → negative We wouldn’t want the inference phone → sucks. Meaning that every phone sucks. By adding the neutral class, along with a suitably rich training set for it, the risk of this type of unwarranted inference reduces greatly. Probabilistic Classification Regardless of which learning algorithm we end up choosing — Naive Bayes, Logistic Regression, Decision Tree, Random Forest, Gradient Boosting, ... — we should consider leveraging the predicted probabilities of the various classes. For example, if the predicted probabilities on an input are roughly 50% (positive), 50% (negative), 0% (0) then we can interpret the text as having both positive and negative sentiments. How to build a training set efficiently Okay, so it’s clear that the ML approach is powerful. Let’s now look to “feeding the beast”, i.e. building a rich training set. Here’s an idea of how to quickly assemble a large set of texts that can be manually labeled efficiently. Pick a suitable source of unstructured text. Such as product reviews at an e-commerce site.Create two columns in a spreadsheet, one for text, one for label.Put each document (e.g. each product review) in its own cell in the column labeled text.Manually add the labels. Pick a suitable source of unstructured text. Such as product reviews at an e-commerce site. Create two columns in a spreadsheet, one for text, one for label. Put each document (e.g. each product review) in its own cell in the column labeled text. Manually add the labels. Let’s elaborate on step 4. Consider crowd-sourcing it. Or at least dividing up the work among team members. Plus adopt a convention that an empty cell in the label column denotes a specific label. A good choice is neither, i.e. neutral. You might be surprised at how quickly you can build up a rich training set using this process. If your product reviews data set comes with a star-rating attached to each review, you can use this rating to auto-label the positive and negative instances. This can speed up the labeling process. That said, you should make a manual pass after the auto-labeling to review it and correct those labels that are wrong. The assumption underlying this auto-labeling is that its quality is reasonably good. So that only a small proportion of the labels need fixing. You do have to look at them all. Still, visually scanning all labels has a much higher throughput than editing individual ones. Training Instance Granularity Generally speaking, to the extent possible, input instances should be more granular than coarser. Customer product reviews are generally granular enough. Especially if they are already tagged with the ratings, from which we might auto-derive the sentiment target. In this case, breaking longer reviews down to individual sentences and manually tagging them with an appropriate sentiment label might be too much work, whereas its benefit unclear. Next, consider starting points being longer documents. Such as full-length review articles of product classes. For example, The Best 10 Phones for 2020 or The Best 10 Stocks for 2020. The case for breaking these down into finer granularity such as paragraphs or even sentences is stronger. Clearly, if we can restrict the text to the region to which a specific sentiment is applicable, it can help improve the learning algorithm’s accuracy. As an extreme example, say you have a 20-page document, all of it neutral, except one sentence which has a strong sentiment. It makes sense to label this sentence with the sentiment and the rest of the text as neutral. That’ll likely work better than labeling the 20-page document with the sentiment in that one sentence. Granularity Of Instances In The Field As discussed above, for the training set, finer-grained instances in the training set are generally better than coarser-grained ones. This preference does not apply to classification time, i.e. the use of the classifier in the field. We should go ahead and predict the sentiment of whatever text we are given, be it a sentence or a chapter. Unlike during training, there is no downside to predicting the sentiment of a long document. It's just a question of expectations. If a user seeks a sentiment of a document longer than a paragraph, what she really means is she wants the overall general sentiment across the text. Is it positive overall, negative overall, both, or neither (neutral)? This is fine, sometimes that is what you want. And once you have discovered documents that carry some sentiment, you can always drill down to run the sentiment classifier on their individual sentences or paragraphs. In view of this, we should keep in mind that evaluation on a test set held-out from the labeled data set will not yield an accurate assessment of how well the classifier works in the field. The held-out test set is derived from the labeled data set, which is composed of granular instances for reasons discussed earlier. The field’s inputs are not necessarily always that granular. Aspect-based Sentiment Analysis Here, in addition to deciphering the various sentiments in the text we also seek to figure out which of them applies to what. Clearly such analysis can be very useful, as illustrated by the example below. The camera on my <xyz-brand> phone sucks. Apart from that, I’m happy. You clearly want to know what is being complained about and what is being liked. Often, we also care to extract the actual sentiment phrases. Consider the example below from a made-up holistic review of a new TV. Good price. Sharp image. Vivid colors. Static in Audio. Motion lags a bit. Ideally, we’d like to extract (aspect, sentiment-phrase, polarity) triples from it. Aspect: price image colors audio motionSentiment-phrase: good sharp vivid static lags a bitPolarity: + + + — - The polarities may help derive an overall quality score (e.g., here 3 out of 5). May have other uses as well. Extracting Aspects And Sentiment Phrases Let’s run this text through the POS-tagger at [2]. Recall that the POS-tag legend is What jumps out at you? As a first attempt, splitting the text into sentences, running a POS-tagger on each sentence, and if the tag sequence is deeming adjective to be the sentiment-phrase and noun to be the aspect works surprisingly well. In precision terms, that is. Not recall because this pattern is too-specific. For example, it doesn’t detect the aspect-sentiment phrase in Motion lags a bit. So how can we try to extend the idea of the previous paragraph to try to improve recall? Formulate this as a sequence labeling problem. See [3] for a detailed sequence-labeling formulation of a similar problem, named entity recognition. The text is tokenized as a sequence of words. Associated with this sequence is a label sequence, which indicates what is the aspect and what the sentiment-phrase. Below is our earlier example, reformulated in this convention, with A denoting aspect, S denoting sentiment-phrase, and N denoting neither. We’ve split the pair into two as it won’t fit in a horizontal line. words Good price. Sharp image. Vivid colors. Static in Audio.labels S A S A S A S N A words Motion lags a bit.labels A S S S In [3] we focused on Hidden Markov models for sequence labeling. Here, it is more natural to work with conditional Markov models [4], for reasons we explain below. First, what is a conditional Markov model? Recall that our inference problem is to input a sequence of words and find the most likely sequence of labels for it. For the token sequence [Motion, lags, a, bit] we would expect the best label sequence to be [A, S, S, S]. A conditional Markov model (CMM) models this inference problem as one of finding the label sequence L that maximizes the conditional probability P(L|T) for the given token sequence T. The Markov model makes certain assumptions which make this inference problem tractable. Specifically, P(L|T) is assumed to be factorable as P(L|T) = P(L1|L0,T1)*P(L2|L1,T2)*...*P(Ln|L_{n-1},Tn) Rather than explain it, let’s illustrate it with our example. We have added a label B denoting begin. P( [B,A,S,S,S] | [B, Motion, lags, a, bit] ) = P(A|B, Motion)*P(S|A, lags)*P(S|S, a)*P(S|S, bit) We won’t describe the inference algorithm. It is too complex for this post. Besides, this is not our focus. However, we will explain the individual probabilities in the above example qualitatively. Equipped with such an explanation, we can imagine trying out all possible label sequences, computing the probability of each, and finding the one that has the highest probability. Let’s start with P(A|B, Motion). This is influenced by two factors and their interaction. First, the likelihood that the first word is part of the aspect. Second, the likelihood that Motion is an aspect word. The first factor’s likelihood is significantly greater than 0. We can imagine many real examples in which the first word is an aspect word. Such as camera is low-resolution. It is the second factor’s likelihood that we’d like to dwell more on. Consider P(A|Motion), ignoring the influence of the previous state B. The CMM allows us to model this probability as being influenced by any features of our choice derived from the combination of A and Motion. Possibly overlapping. The HMM, by contrast, would work in terms of P(Motion|A) instead. It would treat Motion and A as symbols, not letting us exploit any features we may deem useful. In effect, we can think of P(A|Motion) as a supervised learning problem in which (A, Motion) is the input and P(A|Motion) the output. The power of this approach lies in its ability to learn complex mappings P(Li|Ti) in which we can use whatever features from the pair (Li, Ti) that we deem fit. Two features especially come to mind. The word’s part-of-speech and whether the word is labeled as being in a recognized named entity. (See [3] which covers named entity recognition in NLP with many real-world use cases and methods.) The part-of-speech feature has already been suggested by the examples we saw, in which the POS-tag noun seemed a predictor of the label aspect and adjective a predictor of sentiment-phrase. The named entity feature is motivated by the intuition that aspects are often objects of specific types. For instance, retail products. A NER that can recognize retail products and associated product features can be very useful to pick these out as aspects from sentiment-laden reviews. Typically we set up NER to recognize fine-grained entities. Such as product names. Not noun phrases. While in principle we could, noun phrases are too varied to model as NER. POS-tag is coarser-grained. In view of this, we can think of the benefit of combining the two features as follows. NER gives us precision. The POS feature helps with recall.
[ { "code": null, "e": 305, "s": 172, "text": "People like expressing sentiment. Happy or unhappy. Like or dislike. Praise or complain. Good or bad. That is, positive or negative." }, { "code": null, "e": 652, "s": 305, "text": "Sentiment analysis in NLP is about deciphering such sentiment from text. Is it positive, negative, both, or neither? If there is sentiment, which objects in the text the sentiment is referring to and the actual sentiment phrase such as poor, blurry, inexpensive, ... (Not just positive or negative.) This is also called aspect-based analysis [1]." }, { "code": null, "e": 719, "s": 652, "text": "As a technique, sentiment analysis is both interesting and useful." }, { "code": null, "e": 1092, "s": 719, "text": "First, to the interesting part. It’s not always easy to tell, at least not for a computer algorithm, whether a text’s sentiment is positive, negative, both, or neither. The cues can be subtle. Overall sentiment aside, it’s even harder to tell which objects in the text are the subject of which sentiment, especially when both positive and negative sentiments are involved." }, { "code": null, "e": 1288, "s": 1092, "text": "Next, to the useful part. This is easy to explain. People who sell things want to know about how people feel about these things. It is called customer feedback 😊. Ignoring it is bad for business." }, { "code": null, "e": 1674, "s": 1288, "text": "There are other uses as well. Such as opinion mining, i.e. trying to figure out who holds (or held) what opinions. Such as, according to John Smith, the coronavirus will simply go away within six months. This task may be formalized as seeking (source, target, opinion) triples. In our example, source = John Smith, target = coronavirus, opinion = will simply go away within six months." }, { "code": null, "e": 1690, "s": 1674, "text": "(Many) Examples" }, { "code": null, "e": 1847, "s": 1690, "text": "Sentiment analysis is what you might call a long-tail problem. Lots of varying scenarios and subtleties. Such problems are often best described by examples." }, { "code": null, "e": 1885, "s": 1847, "text": "First, let’s see some easy positives." }, { "code": null, "e": 1930, "s": 1885, "text": "Amazing customer service.Love it.Good price." }, { "code": null, "e": 1995, "s": 1930, "text": "Next, some positives and negatives a bit harder to discriminate." }, { "code": null, "e": 2186, "s": 1995, "text": "Positives: What is not to like about this product. Not bad. Not an issue. Not buggy.Negatives: Not happy. Not user-friendly. Not good.Definitely not positive: Is it any good?" }, { "code": null, "e": 2409, "s": 2186, "text": "The positives in the above list are not the strongest ones. That said, they are especially good for training ML algorithms to make key distinctions, as we definitely don’t want these positives to be predicted as negatives." }, { "code": null, "e": 2456, "s": 2409, "text": "Positives: Low price.Negatives: Low quality." }, { "code": null, "e": 2545, "s": 2456, "text": "These instances are especially good for training ML algorithms to make key distinctions." }, { "code": null, "e": 2604, "s": 2545, "text": "Positives: Quick turn-around.Negatives: Quick to fail." }, { "code": null, "e": 2633, "s": 2604, "text": "The same point applies here." }, { "code": null, "e": 2676, "s": 2633, "text": "Positives: Inexpensive.Negatives: cheap." }, { "code": null, "e": 2705, "s": 2676, "text": "The same point applies here." }, { "code": null, "e": 2765, "s": 2705, "text": "Finally, some negatives which are a bit harder to decipher." }, { "code": null, "e": 2967, "s": 2765, "text": "I didn’t get what I was promised.My package hasn’t arrived yet.No one in your team has been able to solve my problem.I was put on hold for an hour!Why is this so hard to use?Why does it fail so easily?" }, { "code": null, "e": 2977, "s": 2967, "text": "Use Cases" }, { "code": null, "e": 3045, "s": 2977, "text": "It’s easy to imagine many. Here are some of the main specific ones." }, { "code": null, "e": 4054, "s": 3045, "text": "Discover negative reviews of your product or service. On blog posts or eCommerce sites or social media. More broadly anywhere on the web.Aggregate sentiment on financial instruments. Such as specific stocks. What is the recent market sentiment on stock xyz? Also, aspect-based variants. Such as according to analysts at financial company xyz, stock abc is likely to grow 20% in the coming year. Discerning who’s opinion it is provides more information, which may be used to assess credibility or lack thereof.Identify which components of your product or service are people complaining about? Especially strongly. For prioritizing tactical or long-term improvements.Track changes to customer sentiment over time for a specific product or service (or a line of these). To check if things have been getting better ...Track shifting opinions of politicians over time. Individuals or groups such as political parties. News media love to do this. To fuel nagging questions such as you said that then but now this!." }, { "code": null, "e": 4192, "s": 4054, "text": "Discover negative reviews of your product or service. On blog posts or eCommerce sites or social media. More broadly anywhere on the web." }, { "code": null, "e": 4565, "s": 4192, "text": "Aggregate sentiment on financial instruments. Such as specific stocks. What is the recent market sentiment on stock xyz? Also, aspect-based variants. Such as according to analysts at financial company xyz, stock abc is likely to grow 20% in the coming year. Discerning who’s opinion it is provides more information, which may be used to assess credibility or lack thereof." }, { "code": null, "e": 4722, "s": 4565, "text": "Identify which components of your product or service are people complaining about? Especially strongly. For prioritizing tactical or long-term improvements." }, { "code": null, "e": 4872, "s": 4722, "text": "Track changes to customer sentiment over time for a specific product or service (or a line of these). To check if things have been getting better ..." }, { "code": null, "e": 5067, "s": 4872, "text": "Track shifting opinions of politicians over time. Individuals or groups such as political parties. News media love to do this. To fuel nagging questions such as you said that then but now this!." }, { "code": null, "e": 5090, "s": 5067, "text": "Computational Problems" }, { "code": null, "e": 5182, "s": 5090, "text": "What we’ve discussed thus far may be crystallized into two distinct computational problems." }, { "code": null, "e": 5365, "s": 5182, "text": "What is the text’s overall sentiment: positive, negative, both, or neither?Which sentiment applies to which portions of the text. This is also called aspect-based sentiment analysis." }, { "code": null, "e": 5441, "s": 5365, "text": "What is the text’s overall sentiment: positive, negative, both, or neither?" }, { "code": null, "e": 5549, "s": 5441, "text": "Which sentiment applies to which portions of the text. This is also called aspect-based sentiment analysis." }, { "code": null, "e": 5630, "s": 5549, "text": "Let’s start with the first problem, which we will call sentiment classification." }, { "code": null, "e": 5663, "s": 5630, "text": "Sentiment Classification Problem" }, { "code": null, "e": 6040, "s": 5663, "text": "The input is text. The output we seek is whether the sentiment is positive, negative, both or neither. In a variant of this problem, which we will not address here, we are interested in additionally predicting the strengths of the positive and negative sentiments. You can imagine why. xyz phone really sucks is way more negative than I’m a little disappointed with xyz phone." }, { "code": null, "e": 6066, "s": 6040, "text": "Dictionary-based Approach" }, { "code": null, "e": 6478, "s": 6066, "text": "The simplest approach is to create two dictionaries, of terms carrying positive and negative sentiment respectively. By term, we mean a word or a phrase. A text is classified as positive or negative based on hits of the terms in the text to these two dictionaries. A text is classified as neutral if it hits neither dictionary. A text is classified as both positive and negative if it hits in both dictionaries." }, { "code": null, "e": 6873, "s": 6478, "text": "This approach is worth considering when one wishes to quickly get a somewhat effective sentiment classifier off-the-ground and one doesn’t have a rich-enough data set of text labeled with the sentiment. Simplicity is one reason. The more important reason is that the machine learning alternative has its own obstacles to be overcome. We’ll delve into these in detail when we discuss that topic." }, { "code": null, "e": 7371, "s": 6873, "text": "Machine-learning obstacles notwithstanding, a dictionary-based approach will run into quality issues sooner or later. So if high precision and high recall of the various sentiment classes are important in your use case, you should consider biting the bullet upfront and investing in ML. Your task will become much easier if you can find a rich-enough labeled data set or come up with some creative ways to get one, possibly after some additional lightweight NLP (discussed in an upcoming section)." }, { "code": null, "e": 7402, "s": 7371, "text": "Supervised Learning Challenges" }, { "code": null, "e": 7563, "s": 7402, "text": "The first challenge is the necessity of having a large and diverse data set of texts labeled with their sentiment classes: positive, negative, both, or neither." }, { "code": null, "e": 7794, "s": 7563, "text": "The issue is this. Think of the text as being represented by a vector. For now in the usual vector space model, i.e. as a bag of words. That said, the challenge applies, albeit to a somewhat lesser extent, even to word embeddings." }, { "code": null, "e": 7862, "s": 7794, "text": "The vector space is huge. Each word in the lexicon has a dimension." }, { "code": null, "e": 8153, "s": 7862, "text": "The vast majority of the words in this space carry no sentiment. To train a machine learning classifier would require a huge training set. Much of what it would be doing is learning which words are “nuisance” words. That is, unlearning biases it collected along the way (see example below)." }, { "code": null, "e": 8282, "s": 8153, "text": "Let’s see an example from which the classifier can learn to wrongly associate neutral words with positive or negative sentiment." }, { "code": null, "e": 8309, "s": 8282, "text": "xyz phone sucks → negative" }, { "code": null, "e": 8532, "s": 8309, "text": "It will learn to associate the word phone with the sentiment negative. Obviously we don’t want this. Unlearning this will require training set instances with the word phone in them that are labeled neither (i.e., neutral)." }, { "code": null, "e": 8871, "s": 8532, "text": "That being said, breaking up a large and diverse corpus (such as Wikipedia) into sentences and labeling each neutral might alleviate this problem. The intuition here is this. All words will initially learn to be neutral. Words such as sucks that repeatedly occur in text labeled negative will eventually ‘escape’ from their neutral label." }, { "code": null, "e": 8900, "s": 8871, "text": "Beyond Bag-of-words Features" }, { "code": null, "e": 9079, "s": 8900, "text": "From the labeled examples we saw in an earlier section, it seems that a ‘?’ is a predictor of sentiment. This makes sense intuitively. Skeptics ask questions. Not true believers." }, { "code": null, "e": 9115, "s": 9079, "text": "Leveraging Dictionaries as Features" }, { "code": null, "e": 9369, "s": 9115, "text": "If we already have dictionaries of phrases correlated with positive or negative sentiment (or find them easy to construct), why not use them as additional features. They don’t have to be complete. Just curated. So we can take advantage of their quality." }, { "code": null, "e": 9694, "s": 9369, "text": "In more detail, here’s how. Say not good is in the dictionary of negatives. We would create a boolean feature for this entry. This feature’s value is 1 if not good appears in text and 0 if not. We might also add the entry (not good, negative) to our training set. Note that here we are thinking of not good as the full text." }, { "code": null, "e": 9714, "s": 9694, "text": "Use Part-of-speech?" }, { "code": null, "e": 9920, "s": 9714, "text": "Sentiment-rich words are often adjectives. This makes one wonder whether using information about the part-of-speech of each word in the text might be useful? As additional features or for pruning features." }, { "code": null, "e": 10063, "s": 9920, "text": "Let’s start by looking at the parts-of-speech of the words in our various examples. This analysis was done using the online pos-tagger at [2]." }, { "code": null, "e": 10297, "s": 10063, "text": "What thoughts does this trigger? The POS-tag adjective seems significantly correlated with sentiment polarity (positive or negative). The POS-tag adverb also. Determiners, prepositions, and pronouns seem to predict the neutral class." }, { "code": null, "e": 10547, "s": 10297, "text": "How might we take advantage of this? We could gate bag-of-words features on their parts-of-speech. For example, filter out all words whose POS-tag is determiner, preposition, or pronoun. This may be viewed as an elaborate form of stop-words removal." }, { "code": null, "e": 10586, "s": 10547, "text": "Feature Engineering: Some Observations" }, { "code": null, "e": 10691, "s": 10586, "text": "Whereas these observations are general, they especially apply to our problem (sentiment classification)." }, { "code": null, "e": 11081, "s": 10691, "text": "First, we don’t need strong evidence before we add a new feature. Merely a weak belief that it might help. The machine learning algorithm will figure out how predictive this feature is, possibly in conjunction with other features. As the training set gets richer over time, the ML will automatically learn to use this feature more effectively if this is possible. Weak features can add up." }, { "code": null, "e": 11238, "s": 11081, "text": "The only downside to this is that if we go overboard, i.e. add too many features, the feature space explosion may come back to haunt us. More on that later." }, { "code": null, "e": 11666, "s": 11238, "text": "Let’s expand on “weak belief that it might help”. Here, ‘help’ just means that the feature is predictive of some sentiment class. We don’t need to know which. The ML will figure this out. That is, which feature value predicts which sentiment class. By contrast, when setting up a rule-based system (of which dictionaries are a special case) one has to specify which combinations of feature values predict which sentiment class." }, { "code": null, "e": 11706, "s": 11666, "text": "Does This Risk Feature Space Explosion?" }, { "code": null, "e": 11972, "s": 11706, "text": "We have already accepted that using bag-of-words features will explode our feature space. For reasons discussed earlier, we have decided to bite the bullet on this front. The question is, will the additional features mentioned in this section make the matter worse?" }, { "code": null, "e": 12381, "s": 11972, "text": "Actually they will make it better. Let’s reason through this. First the question-mark feature. It is boolean-valued. No explosion here. Next, the dictionary-based features. These in fact reduce the noise in the space of word vectors as they surface sentiment-rich words and phrases. Finally, the part-of-speech features. Using them as suggested, for filtering (i.e. removing words), prunes the feature space." }, { "code": null, "e": 12403, "s": 12381, "text": "Word k-gram Features?" }, { "code": null, "e": 12704, "s": 12403, "text": "We deliberately put this after the previous section because this does run a greater risk of exploding the feature space if not done right. The space of word k-grams even with k = 2 is huge. That said, pruning this space sensibly can potentially increase the benefit-to-cost ratio from these features." }, { "code": null, "e": 12847, "s": 12704, "text": "Below are some plausible ideas to consider. In the discussion, we limit ourselves to k=2, i.e. to bigrams, although it applies more generally." }, { "code": null, "e": 13082, "s": 12847, "text": "Prune away bigrams from the model that don’t have sufficient support in the training set. (By the support of a bigram we mean the number of times it occurs in the training set.)For additional pruning, consider parts-of-speech as well." }, { "code": null, "e": 13260, "s": 13082, "text": "Prune away bigrams from the model that don’t have sufficient support in the training set. (By the support of a bigram we mean the number of times it occurs in the training set.)" }, { "code": null, "e": 13318, "s": 13260, "text": "For additional pruning, consider parts-of-speech as well." }, { "code": null, "e": 13335, "s": 13318, "text": "Taking Stock ..." }, { "code": null, "e": 13905, "s": 13335, "text": "We’ll close this section by taking stock of what we have discussed here and its implications. First, we see that the ML approach can be empowered with a variety of features. We simply throw features into the mix. So long as there is a plausible case for each inclusion. We don’t worry about correlations among features. Too complicated to analyze. Let the ML sort it out. The end justifies the means. So long as we have a rich enough labeled data set which we can partition to train-and-test splits and reliably measure the quality of what we are referring to as ‘end’." }, { "code": null, "e": 13976, "s": 13905, "text": "We do need to think about the feature space explosion. We already did." }, { "code": null, "e": 14440, "s": 13976, "text": "Now a few words about the learning algorithm. We have lots of choices. Naive Bayes. Logistic Regression. Decision Tree. Random Forest. Gradient Boosting. Maybe even Deep Learning. The key point to bring to the surface is that these choices span varying levels of sophistication. Some can automatically discover multivariate features that are especially predictive of sentiment. The risk here is that many of the multivariate features they discover are also noisy." }, { "code": null, "e": 14662, "s": 14440, "text": "Okay so now we have lots of feature choices and lots of learning algorithm choices. Potentially very powerful. But also risky. As mentioned earlier, we can mitigate the risk by keeping in mind the feature-space explosion." }, { "code": null, "e": 14960, "s": 14662, "text": "Ultimately though we should focus on building as rich of a labeled data set, even if only incrementally. Longer-term this has more value than tactically optimizing features to compensate for not having a great training set. This is the single most important aspect of this problem. Invest in this." }, { "code": null, "e": 14976, "s": 14960, "text": "Target Variants" }, { "code": null, "e": 15196, "s": 14976, "text": "To this point, we’ve been thinking of sentiment classification as a 4-class problem: positive, negative, both, neither. In some settings, the class both can be ignored. In such settings, we interpret neither as neutral." }, { "code": null, "e": 15639, "s": 15196, "text": "In most use cases, we only care about the first two. So neutral is a nuisance class. ‘Nuisance’ means it needs to be accounted for, even though it’s not what we seek. Why does it need to be accounted for? Well, we don’t want text that is neutral to get classified as positive or negative. Said another way, including the neutral class (backed by a sufficiently rich training set for it), improves the precision of the positives and negatives." }, { "code": null, "e": 15705, "s": 15639, "text": "This is easy to illustrate with an example. Remember the instance" }, { "code": null, "e": 15732, "s": 15705, "text": "xyz phone sucks → negative" }, { "code": null, "e": 15951, "s": 15732, "text": "We wouldn’t want the inference phone → sucks. Meaning that every phone sucks. By adding the neutral class, along with a suitably rich training set for it, the risk of this type of unwarranted inference reduces greatly." }, { "code": null, "e": 15980, "s": 15951, "text": "Probabilistic Classification" }, { "code": null, "e": 16398, "s": 15980, "text": "Regardless of which learning algorithm we end up choosing — Naive Bayes, Logistic Regression, Decision Tree, Random Forest, Gradient Boosting, ... — we should consider leveraging the predicted probabilities of the various classes. For example, if the predicted probabilities on an input are roughly 50% (positive), 50% (negative), 0% (0) then we can interpret the text as having both positive and negative sentiments." }, { "code": null, "e": 16438, "s": 16398, "text": "How to build a training set efficiently" }, { "code": null, "e": 16566, "s": 16438, "text": "Okay, so it’s clear that the ML approach is powerful. Let’s now look to “feeding the beast”, i.e. building a rich training set." }, { "code": null, "e": 16671, "s": 16566, "text": "Here’s an idea of how to quickly assemble a large set of texts that can be manually labeled efficiently." }, { "code": null, "e": 16940, "s": 16671, "text": "Pick a suitable source of unstructured text. Such as product reviews at an e-commerce site.Create two columns in a spreadsheet, one for text, one for label.Put each document (e.g. each product review) in its own cell in the column labeled text.Manually add the labels." }, { "code": null, "e": 17032, "s": 16940, "text": "Pick a suitable source of unstructured text. Such as product reviews at an e-commerce site." }, { "code": null, "e": 17098, "s": 17032, "text": "Create two columns in a spreadsheet, one for text, one for label." }, { "code": null, "e": 17187, "s": 17098, "text": "Put each document (e.g. each product review) in its own cell in the column labeled text." }, { "code": null, "e": 17212, "s": 17187, "text": "Manually add the labels." }, { "code": null, "e": 17449, "s": 17212, "text": "Let’s elaborate on step 4. Consider crowd-sourcing it. Or at least dividing up the work among team members. Plus adopt a convention that an empty cell in the label column denotes a specific label. A good choice is neither, i.e. neutral." }, { "code": null, "e": 17544, "s": 17449, "text": "You might be surprised at how quickly you can build up a rich training set using this process." }, { "code": null, "e": 17861, "s": 17544, "text": "If your product reviews data set comes with a star-rating attached to each review, you can use this rating to auto-label the positive and negative instances. This can speed up the labeling process. That said, you should make a manual pass after the auto-labeling to review it and correct those labels that are wrong." }, { "code": null, "e": 18133, "s": 17861, "text": "The assumption underlying this auto-labeling is that its quality is reasonably good. So that only a small proportion of the labels need fixing. You do have to look at them all. Still, visually scanning all labels has a much higher throughput than editing individual ones." }, { "code": null, "e": 18163, "s": 18133, "text": "Training Instance Granularity" }, { "code": null, "e": 18609, "s": 18163, "text": "Generally speaking, to the extent possible, input instances should be more granular than coarser. Customer product reviews are generally granular enough. Especially if they are already tagged with the ratings, from which we might auto-derive the sentiment target. In this case, breaking longer reviews down to individual sentences and manually tagging them with an appropriate sentiment label might be too much work, whereas its benefit unclear." }, { "code": null, "e": 18793, "s": 18609, "text": "Next, consider starting points being longer documents. Such as full-length review articles of product classes. For example, The Best 10 Phones for 2020 or The Best 10 Stocks for 2020." }, { "code": null, "e": 19050, "s": 18793, "text": "The case for breaking these down into finer granularity such as paragraphs or even sentences is stronger. Clearly, if we can restrict the text to the region to which a specific sentiment is applicable, it can help improve the learning algorithm’s accuracy." }, { "code": null, "e": 19372, "s": 19050, "text": "As an extreme example, say you have a 20-page document, all of it neutral, except one sentence which has a strong sentiment. It makes sense to label this sentence with the sentiment and the rest of the text as neutral. That’ll likely work better than labeling the 20-page document with the sentiment in that one sentence." }, { "code": null, "e": 19410, "s": 19372, "text": "Granularity Of Instances In The Field" }, { "code": null, "e": 19751, "s": 19410, "text": "As discussed above, for the training set, finer-grained instances in the training set are generally better than coarser-grained ones. This preference does not apply to classification time, i.e. the use of the classifier in the field. We should go ahead and predict the sentiment of whatever text we are given, be it a sentence or a chapter." }, { "code": null, "e": 20101, "s": 19751, "text": "Unlike during training, there is no downside to predicting the sentiment of a long document. It's just a question of expectations. If a user seeks a sentiment of a document longer than a paragraph, what she really means is she wants the overall general sentiment across the text. Is it positive overall, negative overall, both, or neither (neutral)?" }, { "code": null, "e": 20317, "s": 20101, "text": "This is fine, sometimes that is what you want. And once you have discovered documents that carry some sentiment, you can always drill down to run the sentiment classifier on their individual sentences or paragraphs." }, { "code": null, "e": 20699, "s": 20317, "text": "In view of this, we should keep in mind that evaluation on a test set held-out from the labeled data set will not yield an accurate assessment of how well the classifier works in the field. The held-out test set is derived from the labeled data set, which is composed of granular instances for reasons discussed earlier. The field’s inputs are not necessarily always that granular." }, { "code": null, "e": 20731, "s": 20699, "text": "Aspect-based Sentiment Analysis" }, { "code": null, "e": 20857, "s": 20731, "text": "Here, in addition to deciphering the various sentiments in the text we also seek to figure out which of them applies to what." }, { "code": null, "e": 20936, "s": 20857, "text": "Clearly such analysis can be very useful, as illustrated by the example below." }, { "code": null, "e": 21006, "s": 20936, "text": "The camera on my <xyz-brand> phone sucks. Apart from that, I’m happy." }, { "code": null, "e": 21087, "s": 21006, "text": "You clearly want to know what is being complained about and what is being liked." }, { "code": null, "e": 21219, "s": 21087, "text": "Often, we also care to extract the actual sentiment phrases. Consider the example below from a made-up holistic review of a new TV." }, { "code": null, "e": 21294, "s": 21219, "text": "Good price. Sharp image. Vivid colors. Static in Audio. Motion lags a bit." }, { "code": null, "e": 21378, "s": 21294, "text": "Ideally, we’d like to extract (aspect, sentiment-phrase, polarity) triples from it." }, { "code": null, "e": 21555, "s": 21378, "text": "Aspect: price image colors audio motionSentiment-phrase: good sharp vivid static lags a bitPolarity: + + + — -" }, { "code": null, "e": 21665, "s": 21555, "text": "The polarities may help derive an overall quality score (e.g., here 3 out of 5). May have other uses as well." }, { "code": null, "e": 21706, "s": 21665, "text": "Extracting Aspects And Sentiment Phrases" }, { "code": null, "e": 21757, "s": 21706, "text": "Let’s run this text through the POS-tagger at [2]." }, { "code": null, "e": 21791, "s": 21757, "text": "Recall that the POS-tag legend is" }, { "code": null, "e": 21935, "s": 21791, "text": "What jumps out at you? As a first attempt, splitting the text into sentences, running a POS-tagger on each sentence, and if the tag sequence is" }, { "code": null, "e": 22190, "s": 21935, "text": "deeming adjective to be the sentiment-phrase and noun to be the aspect works surprisingly well. In precision terms, that is. Not recall because this pattern is too-specific. For example, it doesn’t detect the aspect-sentiment phrase in Motion lags a bit." }, { "code": null, "e": 22427, "s": 22190, "text": "So how can we try to extend the idea of the previous paragraph to try to improve recall? Formulate this as a sequence labeling problem. See [3] for a detailed sequence-labeling formulation of a similar problem, named entity recognition." }, { "code": null, "e": 22590, "s": 22427, "text": "The text is tokenized as a sequence of words. Associated with this sequence is a label sequence, which indicates what is the aspect and what the sentiment-phrase." }, { "code": null, "e": 22798, "s": 22590, "text": "Below is our earlier example, reformulated in this convention, with A denoting aspect, S denoting sentiment-phrase, and N denoting neither. We’ve split the pair into two as it won’t fit in a horizontal line." }, { "code": null, "e": 22973, "s": 22798, "text": "words Good price. Sharp image. Vivid colors. Static in Audio.labels S A S A S A S N A words Motion lags a bit.labels A S S S" }, { "code": null, "e": 23137, "s": 22973, "text": "In [3] we focused on Hidden Markov models for sequence labeling. Here, it is more natural to work with conditional Markov models [4], for reasons we explain below." }, { "code": null, "e": 23404, "s": 23137, "text": "First, what is a conditional Markov model? Recall that our inference problem is to input a sequence of words and find the most likely sequence of labels for it. For the token sequence [Motion, lags, a, bit] we would expect the best label sequence to be [A, S, S, S]." }, { "code": null, "e": 23728, "s": 23404, "text": "A conditional Markov model (CMM) models this inference problem as one of finding the label sequence L that maximizes the conditional probability P(L|T) for the given token sequence T. The Markov model makes certain assumptions which make this inference problem tractable. Specifically, P(L|T) is assumed to be factorable as" }, { "code": null, "e": 23782, "s": 23728, "text": "P(L|T) = P(L1|L0,T1)*P(L2|L1,T2)*...*P(Ln|L_{n-1},Tn)" }, { "code": null, "e": 23884, "s": 23782, "text": "Rather than explain it, let’s illustrate it with our example. We have added a label B denoting begin." }, { "code": null, "e": 23981, "s": 23884, "text": "P( [B,A,S,S,S] | [B, Motion, lags, a, bit] ) = P(A|B, Motion)*P(S|A, lags)*P(S|S, a)*P(S|S, bit)" }, { "code": null, "e": 24359, "s": 23981, "text": "We won’t describe the inference algorithm. It is too complex for this post. Besides, this is not our focus. However, we will explain the individual probabilities in the above example qualitatively. Equipped with such an explanation, we can imagine trying out all possible label sequences, computing the probability of each, and finding the one that has the highest probability." }, { "code": null, "e": 24568, "s": 24359, "text": "Let’s start with P(A|B, Motion). This is influenced by two factors and their interaction. First, the likelihood that the first word is part of the aspect. Second, the likelihood that Motion is an aspect word." }, { "code": null, "e": 24742, "s": 24568, "text": "The first factor’s likelihood is significantly greater than 0. We can imagine many real examples in which the first word is an aspect word. Such as camera is low-resolution." }, { "code": null, "e": 25206, "s": 24742, "text": "It is the second factor’s likelihood that we’d like to dwell more on. Consider P(A|Motion), ignoring the influence of the previous state B. The CMM allows us to model this probability as being influenced by any features of our choice derived from the combination of A and Motion. Possibly overlapping. The HMM, by contrast, would work in terms of P(Motion|A) instead. It would treat Motion and A as symbols, not letting us exploit any features we may deem useful." }, { "code": null, "e": 25501, "s": 25206, "text": "In effect, we can think of P(A|Motion) as a supervised learning problem in which (A, Motion) is the input and P(A|Motion) the output. The power of this approach lies in its ability to learn complex mappings P(Li|Ti) in which we can use whatever features from the pair (Li, Ti) that we deem fit." }, { "code": null, "e": 25735, "s": 25501, "text": "Two features especially come to mind. The word’s part-of-speech and whether the word is labeled as being in a recognized named entity. (See [3] which covers named entity recognition in NLP with many real-world use cases and methods.)" }, { "code": null, "e": 26212, "s": 25735, "text": "The part-of-speech feature has already been suggested by the examples we saw, in which the POS-tag noun seemed a predictor of the label aspect and adjective a predictor of sentiment-phrase. The named entity feature is motivated by the intuition that aspects are often objects of specific types. For instance, retail products. A NER that can recognize retail products and associated product features can be very useful to pick these out as aspects from sentiment-laden reviews." } ]
Tailwind CSS Padding - GeeksforGeeks
23 Mar, 2022 This class accepts lots of values in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS Padding Property. This class is used to create space around the element, inside any defined border. We can set different paddings for individual sides (top, right, bottom, left). It is important to add border properties to implement padding properties. There are lots of CSS properties used for padding like CSS padding-top, CSS padding-bottom, CSS padding-right, CSS padding-left, etc. Padding classes: p-0: This class is used to define the padding on all the sides. py-0: This class is used to define padding on the y-axis i.e padding-top and padding-bottom. px-0: This class is used to define padding on the x-axis i.e padding-left and padding-right. pt-0: This class is specially used to add padding on top. pr-0: This class is specially used to add padding on right. pb-0: This class is specially used to add padding on the bottom. pl-0: This class is specially used to add padding on left. Note: You can change the number “0” with the valid “rem” values. p-0: This class is used to define the padding on all the sides. Syntax: <element class="p-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class="flex justify-center"> <div class="p-4 bg-green-300 w-24 h-24"> <div class="border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: py-0: This class is used to define padding on the y-axis means padding-top and padding-bottom. Syntax: <element class="py-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class="flex justify-center"> <div class="py-4 bg-green-300 w-24 h-24"> <div class="border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: px-0: This class is used to define padding on the x-axis means padding-left and padding-right. Syntax: <element class="px-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class="flex justify-center"> <div class="px-4 bg-green-300 w-24 h-24"> <div class="border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: pt-0: This class is specially used to add padding on top. Syntax: <element class="pt-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class="flex justify-center"> <div class="pt-4 bg-green-300 w-24 h-24"> <div class="border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: pr-0: This class is specially used to add padding on right. Syntax: <element class="pr-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class="flex justify-center"> <div class="pr-4 bg-green-300 w-24 h-24"> <div class="border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: pb-0: This class specially used to add padding on the bottom. Syntax: <element class="pb-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class="flex justify-center"> <div class="pr-4 bg-green-300 w-24 h-24"> <div class="border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: pl-0: This class specially used to add padding on the left. Syntax: <element class="pl-0">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class="flex justify-center"> <div class="pl-8 bg-green-300 w-24 h-24"> <div class="border-2 border-green-800 bg-green-600 w-16 h-16"> </div> </div> </div></body> </html> Output: Tailwind CSS Tailwind-Spacing Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Top 10 Angular Libraries For Web Developers How to calculate the number of days between two dates in javascript? How to create footer to stay at the bottom of a Web page? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 36084, "s": 36056, "text": "\n23 Mar, 2022" }, { "code": null, "e": 36609, "s": 36084, "text": "This class accepts lots of values in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS Padding Property. This class is used to create space around the element, inside any defined border. We can set different paddings for individual sides (top, right, bottom, left). It is important to add border properties to implement padding properties. There are lots of CSS properties used for padding like CSS padding-top, CSS padding-bottom, CSS padding-right, CSS padding-left, etc." }, { "code": null, "e": 36626, "s": 36609, "text": "Padding classes:" }, { "code": null, "e": 36690, "s": 36626, "text": "p-0: This class is used to define the padding on all the sides." }, { "code": null, "e": 36783, "s": 36690, "text": "py-0: This class is used to define padding on the y-axis i.e padding-top and padding-bottom." }, { "code": null, "e": 36876, "s": 36783, "text": "px-0: This class is used to define padding on the x-axis i.e padding-left and padding-right." }, { "code": null, "e": 36934, "s": 36876, "text": "pt-0: This class is specially used to add padding on top." }, { "code": null, "e": 36994, "s": 36934, "text": "pr-0: This class is specially used to add padding on right." }, { "code": null, "e": 37059, "s": 36994, "text": "pb-0: This class is specially used to add padding on the bottom." }, { "code": null, "e": 37118, "s": 37059, "text": "pl-0: This class is specially used to add padding on left." }, { "code": null, "e": 37183, "s": 37118, "text": "Note: You can change the number “0” with the valid “rem” values." }, { "code": null, "e": 37248, "s": 37183, "text": "p-0: This class is used to define the padding on all the sides. " }, { "code": null, "e": 37256, "s": 37248, "text": "Syntax:" }, { "code": null, "e": 37291, "s": 37256, "text": "<element class=\"p-0\">...</element>" }, { "code": null, "e": 37300, "s": 37291, "text": "Example:" }, { "code": null, "e": 37305, "s": 37300, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class=\"flex justify-center\"> <div class=\"p-4 bg-green-300 w-24 h-24\"> <div class=\"border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 37823, "s": 37305, "text": null }, { "code": null, "e": 37831, "s": 37823, "text": "Output:" }, { "code": null, "e": 37926, "s": 37831, "text": "py-0: This class is used to define padding on the y-axis means padding-top and padding-bottom." }, { "code": null, "e": 37934, "s": 37926, "text": "Syntax:" }, { "code": null, "e": 37970, "s": 37934, "text": "<element class=\"py-0\">...</element>" }, { "code": null, "e": 37979, "s": 37970, "text": "Example:" }, { "code": null, "e": 37984, "s": 37979, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class=\"flex justify-center\"> <div class=\"py-4 bg-green-300 w-24 h-24\"> <div class=\"border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 38503, "s": 37984, "text": null }, { "code": null, "e": 38511, "s": 38503, "text": "Output:" }, { "code": null, "e": 38606, "s": 38511, "text": "px-0: This class is used to define padding on the x-axis means padding-left and padding-right." }, { "code": null, "e": 38614, "s": 38606, "text": "Syntax:" }, { "code": null, "e": 38650, "s": 38614, "text": "<element class=\"px-0\">...</element>" }, { "code": null, "e": 38659, "s": 38650, "text": "Example:" }, { "code": null, "e": 38664, "s": 38659, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class=\"flex justify-center\"> <div class=\"px-4 bg-green-300 w-24 h-24\"> <div class=\"border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 39183, "s": 38664, "text": null }, { "code": null, "e": 39191, "s": 39183, "text": "Output:" }, { "code": null, "e": 39249, "s": 39191, "text": "pt-0: This class is specially used to add padding on top." }, { "code": null, "e": 39257, "s": 39249, "text": "Syntax:" }, { "code": null, "e": 39293, "s": 39257, "text": "<element class=\"pt-0\">...</element>" }, { "code": null, "e": 39302, "s": 39293, "text": "Example:" }, { "code": null, "e": 39307, "s": 39302, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class=\"flex justify-center\"> <div class=\"pt-4 bg-green-300 w-24 h-24\"> <div class=\"border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 39826, "s": 39307, "text": null }, { "code": null, "e": 39834, "s": 39826, "text": "Output:" }, { "code": null, "e": 39894, "s": 39834, "text": "pr-0: This class is specially used to add padding on right." }, { "code": null, "e": 39902, "s": 39894, "text": "Syntax:" }, { "code": null, "e": 39938, "s": 39902, "text": "<element class=\"pr-0\">...</element>" }, { "code": null, "e": 39947, "s": 39938, "text": "Example:" }, { "code": null, "e": 39952, "s": 39947, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class=\"flex justify-center\"> <div class=\"pr-4 bg-green-300 w-24 h-24\"> <div class=\"border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 40471, "s": 39952, "text": null }, { "code": null, "e": 40479, "s": 40471, "text": "Output:" }, { "code": null, "e": 40541, "s": 40479, "text": "pb-0: This class specially used to add padding on the bottom." }, { "code": null, "e": 40549, "s": 40541, "text": "Syntax:" }, { "code": null, "e": 40585, "s": 40549, "text": "<element class=\"pb-0\">...</element>" }, { "code": null, "e": 40594, "s": 40585, "text": "Example:" }, { "code": null, "e": 40599, "s": 40594, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class=\"flex justify-center\"> <div class=\"pr-4 bg-green-300 w-24 h-24\"> <div class=\"border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 41118, "s": 40599, "text": null }, { "code": null, "e": 41126, "s": 41118, "text": "Output:" }, { "code": null, "e": 41186, "s": 41126, "text": "pl-0: This class specially used to add padding on the left." }, { "code": null, "e": 41194, "s": 41186, "text": "Syntax:" }, { "code": null, "e": 41230, "s": 41194, "text": "<element class=\"pl-0\">...</element>" }, { "code": null, "e": 41239, "s": 41230, "text": "Example:" }, { "code": null, "e": 41244, "s": 41239, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Padding Class</b> <div class=\"flex justify-center\"> <div class=\"pl-8 bg-green-300 w-24 h-24\"> <div class=\"border-2 border-green-800 bg-green-600 w-16 h-16\"> </div> </div> </div></body> </html>", "e": 41763, "s": 41244, "text": null }, { "code": null, "e": 41771, "s": 41763, "text": "Output:" }, { "code": null, "e": 41784, "s": 41771, "text": "Tailwind CSS" }, { "code": null, "e": 41801, "s": 41784, "text": "Tailwind-Spacing" }, { "code": null, "e": 41818, "s": 41801, "text": "Web Technologies" }, { "code": null, "e": 41916, "s": 41818, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41925, "s": 41916, "text": "Comments" }, { "code": null, "e": 41938, "s": 41925, "text": "Old Comments" }, { "code": null, "e": 41980, "s": 41938, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 42013, "s": 41980, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42075, "s": 42013, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 42125, "s": 42075, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 42168, "s": 42125, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 42213, "s": 42168, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42257, "s": 42213, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 42326, "s": 42257, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 42384, "s": 42326, "text": "How to create footer to stay at the bottom of a Web page?" } ]
How to convert from Unix timestamp to MySQL timestamp value?
MySQL converts Unix timestamp to timestamp data type value with the help of FROM_UNIXTIME() function. mysql> Select FROM_UNIXTIME(1508622563); +-----------------------------+ | FROM_UNIXTIME(1508622563) | +-----------------------------+ | 2017-10-22 03:19:23 | +-----------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1165, "s": 1062, "text": "MySQL converts Unix timestamp to timestamp data type value with the help of FROM_UNIXTIME() function." }, { "code": null, "e": 1390, "s": 1165, "text": "mysql> Select FROM_UNIXTIME(1508622563);\n+-----------------------------+\n| FROM_UNIXTIME(1508622563) |\n+-----------------------------+\n| 2017-10-22 03:19:23 |\n+-----------------------------+\n1 row in set (0.00 sec)" } ]
Machine Learning in the Browser: Train and Serve a Mobilenet Model for Custom Image Classification | by Erdem Isbilen | Towards Data Science
There are several ways of fine-tuning a deep learning model but doing this on the web browser with WebGL acceleration is something that we experienced not such a long time ago, with the introduction of Tensorflow.js. I will use Tensorflow.js together with Angular to build a Web App that trains a convolutional neural network to detect malaria-infected cells with the help of Mobilenet and Kaggle dataset containing 27.558 infected and uninfected cell images. Visit the live demo application to see the codes in action. The application runs in the Google Chrome browser without any issue. Visit my GitHub repository for the full code of this project. You can find the images in the assets folder in this repository as well as the CSV file required to load the images into the browser. You should unzip the images and place them into the assets folder of the Angular project you are working on. As I mentioned above, I will use the ‘mobilenet’ as a base model for our custom image classifier. The pre-trained ‘mobilenet’ model, which is tensorflow.js compatible, is relatively small (20MB) and can be directly downloaded from the Google API storage folder. Uninfected and parasitized cells, which are 2 classes I would like to classify with our custom model whereas the original ‘mobilenet’ model is trained to classify 1000 different objects. I will use all ‘mobilenet’ layers other than the last 5 layers and add a dense layer with 2 units and softmax activation on top of this truncated model to make the modified model suitable for our classification task. I will not train all layers, as this will require a lot of time and computational power. It is also not necessary for our case as we use a pre-trained model which has a lot of representations learned already. Instead, I will freeze the majority of the layers and keep only the last 2 ones trainable. Before start coding, we have to think about how we will feed the images to our custom model during the training. The mobilenet model requires specific image sizes (224x224x3) and image pre-processing operations and we have to apply the same pre-processes to our images before feeding them to our model. Besides, not to make our model biased to one class, we have to feed the same amount of images for each class during the training epochs. After we all clear about the model and the dataset, it is time to use the Angular command-line interface to initialize the Angular web application. npm install -g @angular/cling new TFJS-CustomImageClassificationcd TFJS-CustomImageClassification Then I will use the ‘nmp’ package manager to install the tensorflow.js library. To polish the web app, I will use Angular Material classes. TFJS-CustomImageClassification npm install @tensorflow/tfjs --saveTFJS-CustomImageClassification ng add @angular/material First things first, let’s start coding with generating a function to modify the pre-trained model so that we can use this modified model for our specific task which is to classify the malaria-infected images. As I do not want to train the model starting from scratch, I will freeze all the layers except the ones I need to re-train to finetune the model. //-------------------------------------------------------------// modifies the pre-trained mobilenet to detect malaria infected// cells, freezes layers to train only the last couple of layers//-------------------------------------------------------------async getModifiedMobilenet(){ const trainableLayers= ['denseModified','conv_pw_13_bn','conv_pw_13','conv_dw_13_bn','conv _dw_13']; const mobilenet = await tf.loadLayersModel('https://storage.googleapis.com/tfjs- models/tfjs/mobilenet_v1_0.25_224/model.json');console.log('Mobilenet model is loaded') const x=mobilenet.getLayer('global_average_pooling2d_1'); const predictions= <tf.SymbolicTensor> tf.layers.dense({units: 2, activation: 'softmax',name: 'denseModified'}).apply(x.output); let mobilenetModified = tf.model({inputs: mobilenet.input, outputs: predictions, name: 'modelModified' }); console.log('Mobilenet model is modified')mobilenetModified = this.freezeModelLayers(trainableLayers,mobilenetModified) console.log('ModifiedMobilenet model layers are freezed')mobilenetModified.compile({loss: categoricalCrossentropy, optimizer: tf.train.adam(1e-3), metrics: ['accuracy','crossentropy']});mobilenet.dispose(); x.dispose(); return mobilenetModified}//-------------------------------------------------------------// freezes mobilenet layers to make them untrainable// just keeps final layers trainable with argument trainableLayers//-------------------------------------------------------------freezeModelLayers(trainableLayers,mobilenetModified){ for (const layer of mobilenetModified.layers) { layer.trainable = false; for (const tobeTrained of trainableLayers) { if (layer.name.indexOf(tobeTrained) === 0) { layer.trainable = true; break; } } } return mobilenetModified;} To train the model, we need uninfected and infected cell images in 224x224x3 shape tensor and another 1-dimensional tensor containing 1,0 values indicating the classes of the images. What I will do is to read from a CSV file containing the image src and the class info, then generating HTMLImageElement to see them in the browser. Capture() function then will get the image id to generate required image tensors from the images on the browser. Please note that we have to pre-process the image tensors as the mobilenet expects normalized inputs. To be honest, what I used here as a data-pipeline is not the proper way of doing it, as I am loading the whole chunk of image data into the memory at once. It would be much better to use tf.fitDataset and to use the memory iteratively just when it is needed. //-------------------------------------------------------------// this function generate input and target tensors for the training// input tensor is produced from 224x224x3 image in HTMLImageElement// target tensor shape2 is produced from the class definition//-------------------------------------------------------------generateData (trainData,batchSize){ const imageTensors = []; const targetTensors = [];let allTextLines = this.csvContent.split(/\r|\n|\r/); const csvSeparator = ','; const csvSeparator_2 = '.';for ( let i = 0; i < batchSize; i++) { // split content based on comma const cols: string[] = allTextLines[i].split(csvSeparator); console.log(cols[0].split(csvSeparator_2)[0])if (cols[0].split(csvSeparator_2)[1]=="png") { const imageTensor = this.capture(i); let targetTensor =tf.tensor1d([this.label_x1[i],this.label_x2[i]]); targetTensor.print(); imageTensors.push(imageTensor); targetTensors.push(targetTensor); } } const images = tf.stack(imageTensors); const targets = tf.stack(targetTensors); return {images, targets};}//-------------------------------------------------------------// converts images in HTMLImageElement into the tensors// takes Image Id in HTML as argument//-------------------------------------------------------------capture(imgId){ // Reads the image as a Tensor from the <image> element. this.picture = <HTMLImageElement> document.getElementById(imgId); const trainImage = tf.browser.fromPixels(this.picture); // Normalize the image between -1 and 1. The image comes in between 0-255, so we divide by 127 and subtract 1. const trainim = trainImage.toFloat().div(tf.scalar(127)).sub(tf.scalar(1)); return trainim;} As we prepared the data and the model, it is now time to fine-tune the model so that it can classify the malaria-infected cell images. To reduce the time for the training process, I will use 120 images in total, a training process of 5 epochs with data batches each containing 24 images. Loss function to be ‘categoricalCrossentropy’ and the ‘adam optimizer’ to be used in training with relatively small learning rate value. I used ‘onBatchEnd’ callback function which is provided by Keras to write the training metrics into the console for each epoch. We have to dispose of the tensors to free up the memory once the training is completed. As a final step, we will save the trained model into our local storage to use it later for inference. async fineTuneModifiedModel(model,images,targets){ function onBatchEnd(batch, logs) { console.log('Accuracy', logs.acc); console.log('CrossEntropy', logs.ce); console.log('All', logs); } console.log('Finetuning the model...'); await model.fit(images, targets, { epochs: 5, batchSize: 24, validationSplit: 0.2, callbacks: {onBatchEnd} }).then(info => { console.log console.log('Final accuracy', info.history.acc); console.log('Cross entropy', info.ce); console.log('All', info); console.log('All', info.history['acc'][0]); for ( let k = 0; k < 5; k++) { this.traningMetrics.push({acc: 0, ce: 0 , loss: 0}); this.traningMetrics[k].acc=info.history['acc'][k]; this.traningMetrics[k].ce=info.history['ce'][k]; this.traningMetrics[k].loss=info.history['loss'][k]; } images.dispose(); targets.dispose(); model.dispose(); });} Visit my GitHub repository for the full code of this project. You can find the images in the assets folder in this repository as well as the CSV file required to load the images into the browser. You should unzip the images and place them into the assets folder of the Angular project you are working on. Visit the live demo application to see the codes in action. The application runs in the Google Chrome browser without any issue.
[ { "code": null, "e": 632, "s": 172, "text": "There are several ways of fine-tuning a deep learning model but doing this on the web browser with WebGL acceleration is something that we experienced not such a long time ago, with the introduction of Tensorflow.js. I will use Tensorflow.js together with Angular to build a Web App that trains a convolutional neural network to detect malaria-infected cells with the help of Mobilenet and Kaggle dataset containing 27.558 infected and uninfected cell images." }, { "code": null, "e": 761, "s": 632, "text": "Visit the live demo application to see the codes in action. The application runs in the Google Chrome browser without any issue." }, { "code": null, "e": 1066, "s": 761, "text": "Visit my GitHub repository for the full code of this project. You can find the images in the assets folder in this repository as well as the CSV file required to load the images into the browser. You should unzip the images and place them into the assets folder of the Angular project you are working on." }, { "code": null, "e": 1328, "s": 1066, "text": "As I mentioned above, I will use the ‘mobilenet’ as a base model for our custom image classifier. The pre-trained ‘mobilenet’ model, which is tensorflow.js compatible, is relatively small (20MB) and can be directly downloaded from the Google API storage folder." }, { "code": null, "e": 1515, "s": 1328, "text": "Uninfected and parasitized cells, which are 2 classes I would like to classify with our custom model whereas the original ‘mobilenet’ model is trained to classify 1000 different objects." }, { "code": null, "e": 1732, "s": 1515, "text": "I will use all ‘mobilenet’ layers other than the last 5 layers and add a dense layer with 2 units and softmax activation on top of this truncated model to make the modified model suitable for our classification task." }, { "code": null, "e": 2032, "s": 1732, "text": "I will not train all layers, as this will require a lot of time and computational power. It is also not necessary for our case as we use a pre-trained model which has a lot of representations learned already. Instead, I will freeze the majority of the layers and keep only the last 2 ones trainable." }, { "code": null, "e": 2472, "s": 2032, "text": "Before start coding, we have to think about how we will feed the images to our custom model during the training. The mobilenet model requires specific image sizes (224x224x3) and image pre-processing operations and we have to apply the same pre-processes to our images before feeding them to our model. Besides, not to make our model biased to one class, we have to feed the same amount of images for each class during the training epochs." }, { "code": null, "e": 2620, "s": 2472, "text": "After we all clear about the model and the dataset, it is time to use the Angular command-line interface to initialize the Angular web application." }, { "code": null, "e": 2718, "s": 2620, "text": "npm install -g @angular/cling new TFJS-CustomImageClassificationcd TFJS-CustomImageClassification" }, { "code": null, "e": 2858, "s": 2718, "text": "Then I will use the ‘nmp’ package manager to install the tensorflow.js library. To polish the web app, I will use Angular Material classes." }, { "code": null, "e": 2980, "s": 2858, "text": "TFJS-CustomImageClassification npm install @tensorflow/tfjs --saveTFJS-CustomImageClassification ng add @angular/material" }, { "code": null, "e": 3335, "s": 2980, "text": "First things first, let’s start coding with generating a function to modify the pre-trained model so that we can use this modified model for our specific task which is to classify the malaria-infected images. As I do not want to train the model starting from scratch, I will freeze all the layers except the ones I need to re-train to finetune the model." }, { "code": null, "e": 5111, "s": 3335, "text": "//-------------------------------------------------------------// modifies the pre-trained mobilenet to detect malaria infected// cells, freezes layers to train only the last couple of layers//-------------------------------------------------------------async getModifiedMobilenet(){ const trainableLayers= ['denseModified','conv_pw_13_bn','conv_pw_13','conv_dw_13_bn','conv _dw_13']; const mobilenet = await tf.loadLayersModel('https://storage.googleapis.com/tfjs- models/tfjs/mobilenet_v1_0.25_224/model.json');console.log('Mobilenet model is loaded') const x=mobilenet.getLayer('global_average_pooling2d_1'); const predictions= <tf.SymbolicTensor> tf.layers.dense({units: 2, activation: 'softmax',name: 'denseModified'}).apply(x.output); let mobilenetModified = tf.model({inputs: mobilenet.input, outputs: predictions, name: 'modelModified' }); console.log('Mobilenet model is modified')mobilenetModified = this.freezeModelLayers(trainableLayers,mobilenetModified) console.log('ModifiedMobilenet model layers are freezed')mobilenetModified.compile({loss: categoricalCrossentropy, optimizer: tf.train.adam(1e-3), metrics: ['accuracy','crossentropy']});mobilenet.dispose(); x.dispose(); return mobilenetModified}//-------------------------------------------------------------// freezes mobilenet layers to make them untrainable// just keeps final layers trainable with argument trainableLayers//-------------------------------------------------------------freezeModelLayers(trainableLayers,mobilenetModified){ for (const layer of mobilenetModified.layers) { layer.trainable = false; for (const tobeTrained of trainableLayers) { if (layer.name.indexOf(tobeTrained) === 0) { layer.trainable = true; break; } } } return mobilenetModified;}" }, { "code": null, "e": 5916, "s": 5111, "text": "To train the model, we need uninfected and infected cell images in 224x224x3 shape tensor and another 1-dimensional tensor containing 1,0 values indicating the classes of the images. What I will do is to read from a CSV file containing the image src and the class info, then generating HTMLImageElement to see them in the browser. Capture() function then will get the image id to generate required image tensors from the images on the browser. Please note that we have to pre-process the image tensors as the mobilenet expects normalized inputs. To be honest, what I used here as a data-pipeline is not the proper way of doing it, as I am loading the whole chunk of image data into the memory at once. It would be much better to use tf.fitDataset and to use the memory iteratively just when it is needed." }, { "code": null, "e": 7633, "s": 5916, "text": "//-------------------------------------------------------------// this function generate input and target tensors for the training// input tensor is produced from 224x224x3 image in HTMLImageElement// target tensor shape2 is produced from the class definition//-------------------------------------------------------------generateData (trainData,batchSize){ const imageTensors = []; const targetTensors = [];let allTextLines = this.csvContent.split(/\\r|\\n|\\r/); const csvSeparator = ','; const csvSeparator_2 = '.';for ( let i = 0; i < batchSize; i++) { // split content based on comma const cols: string[] = allTextLines[i].split(csvSeparator); console.log(cols[0].split(csvSeparator_2)[0])if (cols[0].split(csvSeparator_2)[1]==\"png\") { const imageTensor = this.capture(i); let targetTensor =tf.tensor1d([this.label_x1[i],this.label_x2[i]]); targetTensor.print(); imageTensors.push(imageTensor); targetTensors.push(targetTensor); } } const images = tf.stack(imageTensors); const targets = tf.stack(targetTensors); return {images, targets};}//-------------------------------------------------------------// converts images in HTMLImageElement into the tensors// takes Image Id in HTML as argument//-------------------------------------------------------------capture(imgId){ // Reads the image as a Tensor from the <image> element. this.picture = <HTMLImageElement> document.getElementById(imgId); const trainImage = tf.browser.fromPixels(this.picture); // Normalize the image between -1 and 1. The image comes in between 0-255, so we divide by 127 and subtract 1. const trainim = trainImage.toFloat().div(tf.scalar(127)).sub(tf.scalar(1)); return trainim;}" }, { "code": null, "e": 8376, "s": 7633, "text": "As we prepared the data and the model, it is now time to fine-tune the model so that it can classify the malaria-infected cell images. To reduce the time for the training process, I will use 120 images in total, a training process of 5 epochs with data batches each containing 24 images. Loss function to be ‘categoricalCrossentropy’ and the ‘adam optimizer’ to be used in training with relatively small learning rate value. I used ‘onBatchEnd’ callback function which is provided by Keras to write the training metrics into the console for each epoch. We have to dispose of the tensors to free up the memory once the training is completed. As a final step, we will save the trained model into our local storage to use it later for inference." }, { "code": null, "e": 9285, "s": 8376, "text": "async fineTuneModifiedModel(model,images,targets){ function onBatchEnd(batch, logs) { console.log('Accuracy', logs.acc); console.log('CrossEntropy', logs.ce); console.log('All', logs); } console.log('Finetuning the model...'); await model.fit(images, targets, { epochs: 5, batchSize: 24, validationSplit: 0.2, callbacks: {onBatchEnd} }).then(info => { console.log console.log('Final accuracy', info.history.acc); console.log('Cross entropy', info.ce); console.log('All', info); console.log('All', info.history['acc'][0]); for ( let k = 0; k < 5; k++) { this.traningMetrics.push({acc: 0, ce: 0 , loss: 0}); this.traningMetrics[k].acc=info.history['acc'][k]; this.traningMetrics[k].ce=info.history['ce'][k]; this.traningMetrics[k].loss=info.history['loss'][k]; } images.dispose(); targets.dispose(); model.dispose(); });}" }, { "code": null, "e": 9590, "s": 9285, "text": "Visit my GitHub repository for the full code of this project. You can find the images in the assets folder in this repository as well as the CSV file required to load the images into the browser. You should unzip the images and place them into the assets folder of the Angular project you are working on." } ]
Build A Voice-Controlled Mouse In 5 minutes | by That Data Bloke | Towards Data Science
In this story, we will build an application using Python that will accept voice commands from the user and perform certain GUI based actions using the mouse and keyboard. You can think of it as you own voice-enabled digital assistant. It can play media, open applications, send emails, move around the mouse pointer and a lot more, all triggered by your voice commands. We will accomplish by using the following two python libraries — PyAutoGUI & Speech_Recognition. All you need is a laptop with Python installed and a microphone. Before getting into details of how the above-mentioned tools are used in this demo, let us see how they fit into the design of our application. The diagram below is pretty much self-explanatory. The user inputs the voice commands into the microphone (built-in or external), which is then converted into its equivalent text using the SpeechRecognition module. That converted text is then mapped to certain GUI actions (mouse/keyboard events) performed using the PyAutoGUI module. I have drawn the diagram below for ease. Let us look at these two libraries in a bit more detail! The Speech Recognition feature has various applications in the fields of home automation systems, language learning, digital assistants etc. Using this library, we can convert our speech into texts. It supports several APIs (both online & offline). In our example, we will be using the online google API. You might notice some lag at times during the speech to text conversion process, however, among the other API supported by this module, I have found the Google API to be most accurate in my case. It can be downloaded using the following pip commands. The pyaudio is required for using the microphone. pip install SpeechRecognitionpip install pyaudio In the below snippet, we are initializing the recognizer object, listening to the input voice from microphone and converting it to text using the “recognize_google” function. We are doing all of that in only the lines marked in Bold letters. The call to the function recognizer.adjust_for_ambient_noise() is optional. This function listens to the input sound and changes the energy_threshold value based on the amount of noise present in the room. It can be thought of as a measure of sensitivity of the recognizer. This value depends on the the ambient noise and higher values generally mean less sensitive. The range of this parameter might be anywhere from 50–4000. import speech_recognitionrecognizer = speech_recognition.Recognizer()with speech_recognition.Microphone() as src: try: audio = recognizer.adjust_for_ambient_noise(src) print("Threshold Value After calibration:" + str(recognizer.energy_threshold)) print("Please speak:") audio = recognizer.listen(src) speech_to_txt = recognizer.recognize_google(audio).lower() print(speech_to_txt) except Exception as ex: print("Sorry. Could not understand.") Say, instead of microphone, your input is an audio file (file.wav), the line number 3 can be replaced as below: with speech_recognition.WavFile("file.wav") as src: Python offers a library called PyAutoGUI for GUI Automation that simulates mouse clicks and keystrokes as if a human user was performing them. For instance, simulating the mouse movements, keystrokes, taking screenshots, maximizing & minimizing a window, there is a lot one can do. You can refer the official documentation link for the complete list. For the purposes of this demonstration, I am using functions like mouse movement, mouse clicks, keyboard presses & find image on screen. pip install PyAutoGUI Mouse Controls: To move the mouse cursor across the screen, we need the (x,y) coordinates. Think of the monitor as a 2-D plane (as shown here) with x,y coordinates, where the top left corner is the (0,0). To move to the right, the value of x increases and to go towards the bottom the value of y increases. The pyautogui.size() function returns the dimensions of the screen. You can check your screen dimension as shown below: >>> import pyautogui>>> pyautogui.size()Size(width=1920, height=1080) The below command moves the mouse pointer from its current position to (100,100) position and it takes 0.25 seconds to do so. The next command simulates double click with an interval of 0.25 seconds between the two clicks. pyautogui.moveRel(100, 100, duration=0.25)pyautogui.click(button='left', clicks=2, interval=0.25) Keyboard Controls: To simulate key presses, the following function is used. It presses the multimedia ‘mute’ button. The complete list of all the supported keys can be found here. pyautogui.typewrite(['volumemute']) Locate Function: There can be times when we do not already know the (x,y) coordinates of the point we want to click (say a button). But if we have a picture of the button stored as an image file, pyautogui.locateOnScreen() function can look for that image pixel by pixel and return the coordinates. One thing to note about the locateOnScreen() feature is that, even if a single pixel does not match, it will fail to detect the image and return a None object. We can then, simply move our mouse to the given location and perform a click. For eg:- I have the Chrome application pinned to my taskbar in my windows machine. I have taken a screenshot (Chrome.PNG) of the icon as below: Now, the locateOnScreen() function is used like below icon_location = pyautogui.locateOnScreen(r'screenshots\Chrome.PNG')print(icon_location)>>> Box(left=446, top=1023, width=74, height=52)#Using the left & top values as x & y to click at that locationpyautogui.click(x=446, y=1023, duration=0.25) That’s all we need to know. Now, the only thing remaining is to map the text to a GUI action. Here’s the mapping I have chosen. I have attached a demo video of the final application and the code is uploaded here for reference. In case you happen to read my previous article on Gesture Recognition using neural networks, I had intended to add PyAutoGUI functionality as a complementary part to take actions based on the predicted gestures based on the same principles discussed under the PyAutoGUI section here. In this demo, we have seen how speech can be converted to text using the Speech Recognition library and how to automate the GUI using PyAutoGUI. By combining these two functionalities, we built a basic version of a voice controlled mouse and keyboard. I hope you find this information useful and use it in your own way. towardsdatascience.com medium.com References: [1] PyAutoGUI CheatSheet, https://pyautogui.readthedocs.io/en/latest/quickstart.html [2] Speech Recognition Python, https://pypi.org/project/SpeechRecognition/
[ { "code": null, "e": 703, "s": 171, "text": "In this story, we will build an application using Python that will accept voice commands from the user and perform certain GUI based actions using the mouse and keyboard. You can think of it as you own voice-enabled digital assistant. It can play media, open applications, send emails, move around the mouse pointer and a lot more, all triggered by your voice commands. We will accomplish by using the following two python libraries — PyAutoGUI & Speech_Recognition. All you need is a laptop with Python installed and a microphone." }, { "code": null, "e": 847, "s": 703, "text": "Before getting into details of how the above-mentioned tools are used in this demo, let us see how they fit into the design of our application." }, { "code": null, "e": 1223, "s": 847, "text": "The diagram below is pretty much self-explanatory. The user inputs the voice commands into the microphone (built-in or external), which is then converted into its equivalent text using the SpeechRecognition module. That converted text is then mapped to certain GUI actions (mouse/keyboard events) performed using the PyAutoGUI module. I have drawn the diagram below for ease." }, { "code": null, "e": 1280, "s": 1223, "text": "Let us look at these two libraries in a bit more detail!" }, { "code": null, "e": 1886, "s": 1280, "text": "The Speech Recognition feature has various applications in the fields of home automation systems, language learning, digital assistants etc. Using this library, we can convert our speech into texts. It supports several APIs (both online & offline). In our example, we will be using the online google API. You might notice some lag at times during the speech to text conversion process, however, among the other API supported by this module, I have found the Google API to be most accurate in my case. It can be downloaded using the following pip commands. The pyaudio is required for using the microphone." }, { "code": null, "e": 1935, "s": 1886, "text": "pip install SpeechRecognitionpip install pyaudio" }, { "code": null, "e": 2604, "s": 1935, "text": "In the below snippet, we are initializing the recognizer object, listening to the input voice from microphone and converting it to text using the “recognize_google” function. We are doing all of that in only the lines marked in Bold letters. The call to the function recognizer.adjust_for_ambient_noise() is optional. This function listens to the input sound and changes the energy_threshold value based on the amount of noise present in the room. It can be thought of as a measure of sensitivity of the recognizer. This value depends on the the ambient noise and higher values generally mean less sensitive. The range of this parameter might be anywhere from 50–4000." }, { "code": null, "e": 3102, "s": 2604, "text": "import speech_recognitionrecognizer = speech_recognition.Recognizer()with speech_recognition.Microphone() as src: try: audio = recognizer.adjust_for_ambient_noise(src) print(\"Threshold Value After calibration:\" + str(recognizer.energy_threshold)) print(\"Please speak:\") audio = recognizer.listen(src) speech_to_txt = recognizer.recognize_google(audio).lower() print(speech_to_txt) except Exception as ex: print(\"Sorry. Could not understand.\")" }, { "code": null, "e": 3214, "s": 3102, "text": "Say, instead of microphone, your input is an audio file (file.wav), the line number 3 can be replaced as below:" }, { "code": null, "e": 3266, "s": 3214, "text": "with speech_recognition.WavFile(\"file.wav\") as src:" }, { "code": null, "e": 3754, "s": 3266, "text": "Python offers a library called PyAutoGUI for GUI Automation that simulates mouse clicks and keystrokes as if a human user was performing them. For instance, simulating the mouse movements, keystrokes, taking screenshots, maximizing & minimizing a window, there is a lot one can do. You can refer the official documentation link for the complete list. For the purposes of this demonstration, I am using functions like mouse movement, mouse clicks, keyboard presses & find image on screen." }, { "code": null, "e": 3776, "s": 3754, "text": "pip install PyAutoGUI" }, { "code": null, "e": 4151, "s": 3776, "text": "Mouse Controls: To move the mouse cursor across the screen, we need the (x,y) coordinates. Think of the monitor as a 2-D plane (as shown here) with x,y coordinates, where the top left corner is the (0,0). To move to the right, the value of x increases and to go towards the bottom the value of y increases. The pyautogui.size() function returns the dimensions of the screen." }, { "code": null, "e": 4203, "s": 4151, "text": "You can check your screen dimension as shown below:" }, { "code": null, "e": 4273, "s": 4203, "text": ">>> import pyautogui>>> pyautogui.size()Size(width=1920, height=1080)" }, { "code": null, "e": 4496, "s": 4273, "text": "The below command moves the mouse pointer from its current position to (100,100) position and it takes 0.25 seconds to do so. The next command simulates double click with an interval of 0.25 seconds between the two clicks." }, { "code": null, "e": 4594, "s": 4496, "text": "pyautogui.moveRel(100, 100, duration=0.25)pyautogui.click(button='left', clicks=2, interval=0.25)" }, { "code": null, "e": 4774, "s": 4594, "text": "Keyboard Controls: To simulate key presses, the following function is used. It presses the multimedia ‘mute’ button. The complete list of all the supported keys can be found here." }, { "code": null, "e": 4810, "s": 4774, "text": "pyautogui.typewrite(['volumemute'])" }, { "code": null, "e": 5491, "s": 4810, "text": "Locate Function: There can be times when we do not already know the (x,y) coordinates of the point we want to click (say a button). But if we have a picture of the button stored as an image file, pyautogui.locateOnScreen() function can look for that image pixel by pixel and return the coordinates. One thing to note about the locateOnScreen() feature is that, even if a single pixel does not match, it will fail to detect the image and return a None object. We can then, simply move our mouse to the given location and perform a click. For eg:- I have the Chrome application pinned to my taskbar in my windows machine. I have taken a screenshot (Chrome.PNG) of the icon as below:" }, { "code": null, "e": 5545, "s": 5491, "text": "Now, the locateOnScreen() function is used like below" }, { "code": null, "e": 5789, "s": 5545, "text": "icon_location = pyautogui.locateOnScreen(r'screenshots\\Chrome.PNG')print(icon_location)>>> Box(left=446, top=1023, width=74, height=52)#Using the left & top values as x & y to click at that locationpyautogui.click(x=446, y=1023, duration=0.25)" }, { "code": null, "e": 5917, "s": 5789, "text": "That’s all we need to know. Now, the only thing remaining is to map the text to a GUI action. Here’s the mapping I have chosen." }, { "code": null, "e": 6016, "s": 5917, "text": "I have attached a demo video of the final application and the code is uploaded here for reference." }, { "code": null, "e": 6300, "s": 6016, "text": "In case you happen to read my previous article on Gesture Recognition using neural networks, I had intended to add PyAutoGUI functionality as a complementary part to take actions based on the predicted gestures based on the same principles discussed under the PyAutoGUI section here." }, { "code": null, "e": 6620, "s": 6300, "text": "In this demo, we have seen how speech can be converted to text using the Speech Recognition library and how to automate the GUI using PyAutoGUI. By combining these two functionalities, we built a basic version of a voice controlled mouse and keyboard. I hope you find this information useful and use it in your own way." }, { "code": null, "e": 6643, "s": 6620, "text": "towardsdatascience.com" }, { "code": null, "e": 6654, "s": 6643, "text": "medium.com" }, { "code": null, "e": 6666, "s": 6654, "text": "References:" }, { "code": null, "e": 6751, "s": 6666, "text": "[1] PyAutoGUI CheatSheet, https://pyautogui.readthedocs.io/en/latest/quickstart.html" } ]
Python | Pandas Series.str.center() - GeeksforGeeks
27 Mar, 2019 Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.center() function is used for filling left and right side of strings in the Series/Index with an additional character. The function is equivalent to Python’s str.center(). Syntax: Series.str.center(width, fillchar=’ ‘) Parameter :width : Minimum width of resulting string; additional characters will be filled with fillcharfillchar : Additional character for filling, default is whitespace Returns : filled Example #1: Use Series.str.center() function to fill the left and right side of the string in the underlying data of the given series object by ‘*’ symbol. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr) Output : Now we will use Series.str.center() function to fill ‘*’ symbol in the left and right side of the string. # fill '*' in the left and right side of stringresult = sr.str.center(width = 13, fillchar = '*') # print the resultprint(result) Output : As we can see in the output, the Series.str.center() function has successfully filled ‘*’ symbol in the left and the right side of the string in the underlying data of the given series object. Example #2 : Use Series.str.center() function to fill the left and right side of the string in the underlying data of the given series object by ‘*’ symbol. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr) Output : Now we will use Series.str.center() function to fill ‘*’ symbol in the left and right side of the string. # fill '*' in the left and right side of string# width after filling should be 5result = sr.str.center(width = 5, fillchar = '*') # print the resultprint(result) Output : As we can see in the output, the Series.str.center() function has successfully filled ‘*’ symbol in the left and the right side of the string in the underlying data of the given series object. Note : If the value of width is smaller than the length of actual string then the whole string is printed without truncating it. Python-pandas Python-pandas-series-str Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 24214, "s": 24186, "text": "\n27 Mar, 2019" }, { "code": null, "e": 24506, "s": 24214, "text": "Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.center() function is used for filling left and right side of strings in the Series/Index with an additional character. The function is equivalent to Python’s str.center()." }, { "code": null, "e": 24553, "s": 24506, "text": "Syntax: Series.str.center(width, fillchar=’ ‘)" }, { "code": null, "e": 24724, "s": 24553, "text": "Parameter :width : Minimum width of resulting string; additional characters will be filled with fillcharfillchar : Additional character for filling, default is whitespace" }, { "code": null, "e": 24741, "s": 24724, "text": "Returns : filled" }, { "code": null, "e": 24897, "s": 24741, "text": "Example #1: Use Series.str.center() function to fill the left and right side of the string in the underlying data of the given series object by ‘*’ symbol." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = idx # Print the seriesprint(sr)", "e": 25168, "s": 24897, "text": null }, { "code": null, "e": 25177, "s": 25168, "text": "Output :" }, { "code": null, "e": 25283, "s": 25177, "text": "Now we will use Series.str.center() function to fill ‘*’ symbol in the left and right side of the string." }, { "code": "# fill '*' in the left and right side of stringresult = sr.str.center(width = 13, fillchar = '*') # print the resultprint(result)", "e": 25414, "s": 25283, "text": null }, { "code": null, "e": 25423, "s": 25414, "text": "Output :" }, { "code": null, "e": 25616, "s": 25423, "text": "As we can see in the output, the Series.str.center() function has successfully filled ‘*’ symbol in the left and the right side of the string in the underlying data of the given series object." }, { "code": null, "e": 25773, "s": 25616, "text": "Example #2 : Use Series.str.center() function to fill the left and right side of the string in the underlying data of the given series object by ‘*’ symbol." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the indexsr.index = idx # Print the seriesprint(sr)", "e": 26038, "s": 25773, "text": null }, { "code": null, "e": 26047, "s": 26038, "text": "Output :" }, { "code": null, "e": 26153, "s": 26047, "text": "Now we will use Series.str.center() function to fill ‘*’ symbol in the left and right side of the string." }, { "code": "# fill '*' in the left and right side of string# width after filling should be 5result = sr.str.center(width = 5, fillchar = '*') # print the resultprint(result)", "e": 26316, "s": 26153, "text": null }, { "code": null, "e": 26325, "s": 26316, "text": "Output :" }, { "code": null, "e": 26518, "s": 26325, "text": "As we can see in the output, the Series.str.center() function has successfully filled ‘*’ symbol in the left and the right side of the string in the underlying data of the given series object." }, { "code": null, "e": 26647, "s": 26518, "text": "Note : If the value of width is smaller than the length of actual string then the whole string is printed without truncating it." }, { "code": null, "e": 26661, "s": 26647, "text": "Python-pandas" }, { "code": null, "e": 26686, "s": 26661, "text": "Python-pandas-series-str" }, { "code": null, "e": 26693, "s": 26686, "text": "Python" }, { "code": null, "e": 26791, "s": 26693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26800, "s": 26791, "text": "Comments" }, { "code": null, "e": 26813, "s": 26800, "text": "Old Comments" }, { "code": null, "e": 26831, "s": 26813, "text": "Python Dictionary" }, { "code": null, "e": 26863, "s": 26831, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26898, "s": 26863, "text": "Read a file line by line in Python" }, { "code": null, "e": 26920, "s": 26898, "text": "Enumerate() in Python" }, { "code": null, "e": 26950, "s": 26920, "text": "Iterate over a list in Python" }, { "code": null, "e": 26992, "s": 26950, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27035, "s": 26992, "text": "Python program to convert a list to string" }, { "code": null, "e": 27072, "s": 27035, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27098, "s": 27072, "text": "Python String | replace()" } ]
Can we have an empty catch block in Java?
Yes, we can have an empty catch block. But this is a bad practice to implement in Java. Generally, the try block has the code which is capable of producing exceptions, if anything wrong in the try block, for instance, divide by zero, file not found, etc. It will generate an exception that is caught by the catch block. The catch block catches and handles the exception. If the catch block is empty then we will have no idea what went wrong within our code. public class EmptyCatchBlockTest { public static void main(String[] args) { try { int a = 4, b = 0; int c = a/b; } catch(ArithmeticException ae) { // An empty catch block } } } In the above code, the catch block catches the exception but doesn’t print anything in the console. This makes the user think that there is no exception in the code. So it's a good practice to print corresponding exception messages in the catch block. // An empty catch block
[ { "code": null, "e": 1150, "s": 1062, "text": "Yes, we can have an empty catch block. But this is a bad practice to implement in Java." }, { "code": null, "e": 1520, "s": 1150, "text": "Generally, the try block has the code which is capable of producing exceptions, if anything wrong in the try block, for instance, divide by zero, file not found, etc. It will generate an exception that is caught by the catch block. The catch block catches and handles the exception. If the catch block is empty then we will have no idea what went wrong within our code." }, { "code": null, "e": 1748, "s": 1520, "text": "public class EmptyCatchBlockTest {\n public static void main(String[] args) {\n try {\n int a = 4, b = 0;\n int c = a/b;\n } catch(ArithmeticException ae) {\n // An empty catch block\n }\n }\n}" }, { "code": null, "e": 2000, "s": 1748, "text": "In the above code, the catch block catches the exception but doesn’t print anything in the console. This makes the user think that there is no exception in the code. So it's a good practice to print corresponding exception messages in the catch block." }, { "code": null, "e": 2024, "s": 2000, "text": "// An empty catch block" } ]
Shortest path with exactly k edges in a directed and weighted graph | Set 2 - GeeksforGeeks
10 Nov, 2021 Given a directed weighted graph and two vertices S and D in it, the task is to find the shortest path from S to D with exactly K edges on the path. If no such path exists, print -1. Examples: Input: N = 3, K = 2, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 8 Explanation: The shortest path with two edges will be 1->2->3 Input: N = 3, K = 4, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: -1 Explanation: No path with edge length 4 exists from node 1 to 3 Input: N = 3, K = 5, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 20 Explanation: Shortest path will be 1->2->3->1->2->3. Approach: An O(V^3*K) approach for this problem has already been discussed in the previous article. In this article, an O(E*K) approach is discussed for solving this problem. The idea is to use dynamic-programming to solve this problem. Let dp[X][J] be the shortest path from node S to node X using exactly J edges in total. Using this, dp[X][J+1] can be calculated as: dp[X][J+1] = min(arr[Y][J]+weight[{Y, X}]) for all Y which has an edge from Y to X. The result for the problem can be computed by following below steps: Initialise an array, dis[] with initial value as ‘inf’ except dis[S] as 0.For i equals 1 – K, run a loop Initialise an array, dis1[] with initial value as ‘inf’.For each edge in the graph, dis1[edge.second] = min(dis1[edge.second], dis[edge.first]+weight(edge))If dist[d] in infinity, return -1, else return dist[d]. Initialise an array, dis[] with initial value as ‘inf’ except dis[S] as 0. For i equals 1 – K, run a loop Initialise an array, dis1[] with initial value as ‘inf’.For each edge in the graph, dis1[edge.second] = min(dis1[edge.second], dis[edge.first]+weight(edge)) Initialise an array, dis1[] with initial value as ‘inf’. For each edge in the graph, dis1[edge.second] = min(dis1[edge.second], dis[edge.first]+weight(edge)) If dist[d] in infinity, return -1, else return dist[d]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>#define inf 100000000using namespace std; // Function to find the smallest path// with exactly K edgesdouble smPath(int s, int d, vector<pair<pair<int, int>, int> > ed, int n, int k){ // Array to store dp int dis[n + 1]; // Initialising the array for (int i = 0; i <= n; i++) dis[i] = inf; dis[s] = 0; // Loop to solve DP for (int i = 0; i < k; i++) { // Initialising next state int dis1[n + 1]; for (int j = 0; j <= n; j++) dis1[j] = inf; // Recurrence relation for (auto it : ed) dis1[it.first.second] = min(dis1[it.first.second], dis[it.first.first] + it.second); for (int i = 0; i <= n; i++) dis[i] = dis1[i]; } // Returning final answer if (dis[d] == inf) return -1; else return dis[d];} // Driver codeint main(){ int n = 4; vector<pair<pair<int, int>, int> > ed; // Input edges ed = { { { 0, 1 }, 10 }, { { 0, 2 }, 3 }, { { 0, 3 }, 2 }, { { 1, 3 }, 7 }, { { 2, 3 }, 7 } }; // Source and Destination int s = 0, d = 3; // Number of edges in path int k = 2; // Calling the function cout << smPath(s, d, ed, n, k);} // Java implementation of the above approachimport java.util.ArrayList;import java.util.Arrays; class GFG{ static class Pair<K, V>{ K first; V second; public Pair(K first, V second) { this.first = first; this.second = second; }} static int inf = 100000000; // Function to find the smallest path// with exactly K edgesstatic int smPath(int s, int d, ArrayList<Pair<Pair<Integer, Integer>, Integer>> ed, int n, int k){ // Array to store dp int[] dis = new int[n + 1]; // Initialising the array Arrays.fill(dis, inf); dis[s] = 0; // Loop to solve DP for(int i = 0; i < k; i++) { // Initialising next state int[] dis1 = new int[n + 1]; Arrays.fill(dis1, inf); // Recurrence relation for(Pair<Pair<Integer, Integer>, Integer> it : ed) dis1[it.first.second] = Math.min(dis1[it.first.second], dis[it.first.first] + it.second); for(int j = 0; j <= n; j++) dis[j] = dis1[j]; } // Returning final answer if (dis[d] == inf) return -1; else return dis[d];} // Driver codepublic static void main(String[] args){ int n = 4; // Input edges ArrayList<Pair<Pair<Integer, Integer>, Integer>> ed = new ArrayList<>( Arrays.asList( new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(0, 1), 10), new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(0, 2), 3), new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(0, 3), 2), new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(1, 3), 7), new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(2, 3), 7) ) ); // Source and Destination int s = 0, d = 3; // Number of edges in path int k = 2; // Calling the function System.out.println(smPath(s, d, ed, n, k));}} // This code is contributed by sanjeev2552 # Python3 implementation of the above approachinf = 100000000 # Function to find the smallest path# with exactly K edgesdef smPath(s, d, ed, n, k): # Array to store dp dis = [inf] * (n + 1) dis[s] = 0 # Loop to solve DP for i in range(k): # Initialising next state dis1 = [inf] * (n + 1) # Recurrence relation for it in ed: dis1[it[1]] = min(dis1[it[1]], dis[it[0]]+ it[2]) for i in range(n + 1): dis[i] = dis1[i] # Returning final answer if (dis[d] == inf): return -1 else: return dis[d] # Driver codeif __name__ == '__main__': n = 4 # Input edges ed = [ [0, 1 ,10], [ 0, 2 ,3], [ 0, 3 ,2], [ 1, 3 ,7], [ 2, 3 ,7] ] # Source and Destination s = 0 d = 3 # Number of edges in path k = 2 # Calling the function print(smPath(s, d, ed, n, k)) # This code is contributed by mohit kumar 29 // C# implementation of the above approachusing System;using System.Linq;using System.Collections.Generic; public class GFG{ static int inf = 100000000; // Function to find the smallest path// with exactly K edgespublic static int smPath(int s, int d, List<KeyValuePair<KeyValuePair<int, int>, int>> ed, int n, int k){ // Array to store dp // Initialising the array int []dis = Enumerable.Repeat(inf, n+1).ToArray(); dis[s] = 0; // Loop to solve DP for(int i = 0; i < k; i++) { // Initialising next state int []dis1 = Enumerable.Repeat(inf, n+1).ToArray(); // Recurrence relation foreach(KeyValuePair<KeyValuePair<int, int>, int> it in ed) dis1[it.Key.Value] = Math.Min(dis1[it.Key.Value], dis[it.Key.Key] + it.Value); for(int j = 0; j <= n; j++) dis[j] = dis1[j]; } // Returning final answer if (dis[d] == inf) return -1; else return dis[d];} // Driver codepublic static void Main(string[] args){ int n = 4; // Input edges List<KeyValuePair<KeyValuePair<int, int>, int>> ed = new List<KeyValuePair<KeyValuePair<int, int>, int>>(){ new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(0, 1), 10), new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(0, 2), 3), new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(0, 3), 2), new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(1, 3), 7), new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(2, 3), 7) }; // Source and Destination int s = 0, d = 3; // Number of edges in path int k = 2; // Calling the function Console.Write(smPath(s, d, ed, n, k));}} // This code is contributed by rrrtnx. <script>// Javascript implementation of the above approach let inf = 100000000; // Function to find the smallest path// with exactly K edgesfunction smPath(s,d,ed,n,k){ // Array to store dp let dis = new Array(n + 1); // Initialising the array for(let i=0;i<(n+1);i++) { dis[i]=inf; } dis[s] = 0; // Loop to solve DP for(let i = 0; i < k; i++) { // Initialising next state let dis1 = new Array(n + 1); for(let i=0;i<(n+1);i++) { dis1[i]=inf; } // Recurrence relation for(let it=0;it< ed.length;it++) dis1[ed[it][1]] = Math.min(dis1[ed[it][1]], dis[ed[it][0]] + ed[it][2]); document.write() for(let j = 0; j <= n; j++) dis[j] = dis1[j]; } // Returning final answer if (dis[d] == inf) return -1; else return dis[d];} // Driver codelet n = 4; // Input edgeslet ed = [ [0, 1 ,10], [ 0, 2 ,3], [ 0, 3 ,2], [ 1, 3 ,7], [ 2, 3 ,7] ];// Source and Destinationlet s = 0, d = 3; // Number of edges in pathlet k = 2; // Calling the functiondocument.write(smPath(s, d, ed, n, k)); // This code is contributed by patel2127</script> 10 Time complexity: O(E*K) Space complexity: O(N) mohit kumar 29 sanjeev2552 patel2127 rrrtnx ACM-ICPC Algorithms Dynamic Programming Graph Dynamic Programming Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Understanding Time Complexity with Simple Examples Introduction to Algorithms How to write a Pseudo Code? 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 25082, "s": 25054, "text": "\n10 Nov, 2021" }, { "code": null, "e": 25264, "s": 25082, "text": "Given a directed weighted graph and two vertices S and D in it, the task is to find the shortest path from S to D with exactly K edges on the path. If no such path exists, print -1." }, { "code": null, "e": 25275, "s": 25264, "text": "Examples: " }, { "code": null, "e": 25427, "s": 25275, "text": "Input: N = 3, K = 2, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 8 Explanation: The shortest path with two edges will be 1->2->3" }, { "code": null, "e": 25582, "s": 25427, "text": "Input: N = 3, K = 4, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: -1 Explanation: No path with edge length 4 exists from node 1 to 3" }, { "code": null, "e": 25728, "s": 25582, "text": "Input: N = 3, K = 5, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 20 Explanation: Shortest path will be 1->2->3->1->2->3. " }, { "code": null, "e": 25904, "s": 25728, "text": "Approach: An O(V^3*K) approach for this problem has already been discussed in the previous article. In this article, an O(E*K) approach is discussed for solving this problem. " }, { "code": null, "e": 25966, "s": 25904, "text": "The idea is to use dynamic-programming to solve this problem." }, { "code": null, "e": 26100, "s": 25966, "text": "Let dp[X][J] be the shortest path from node S to node X using exactly J edges in total. Using this, dp[X][J+1] can be calculated as: " }, { "code": null, "e": 26184, "s": 26100, "text": "dp[X][J+1] = min(arr[Y][J]+weight[{Y, X}])\nfor all Y which has an edge from Y to X." }, { "code": null, "e": 26254, "s": 26184, "text": "The result for the problem can be computed by following below steps: " }, { "code": null, "e": 26571, "s": 26254, "text": "Initialise an array, dis[] with initial value as ‘inf’ except dis[S] as 0.For i equals 1 – K, run a loop Initialise an array, dis1[] with initial value as ‘inf’.For each edge in the graph, dis1[edge.second] = min(dis1[edge.second], dis[edge.first]+weight(edge))If dist[d] in infinity, return -1, else return dist[d]." }, { "code": null, "e": 26646, "s": 26571, "text": "Initialise an array, dis[] with initial value as ‘inf’ except dis[S] as 0." }, { "code": null, "e": 26834, "s": 26646, "text": "For i equals 1 – K, run a loop Initialise an array, dis1[] with initial value as ‘inf’.For each edge in the graph, dis1[edge.second] = min(dis1[edge.second], dis[edge.first]+weight(edge))" }, { "code": null, "e": 26891, "s": 26834, "text": "Initialise an array, dis1[] with initial value as ‘inf’." }, { "code": null, "e": 26992, "s": 26891, "text": "For each edge in the graph, dis1[edge.second] = min(dis1[edge.second], dis[edge.first]+weight(edge))" }, { "code": null, "e": 27048, "s": 26992, "text": "If dist[d] in infinity, return -1, else return dist[d]." }, { "code": null, "e": 27100, "s": 27048, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27104, "s": 27100, "text": "C++" }, { "code": null, "e": 27109, "s": 27104, "text": "Java" }, { "code": null, "e": 27117, "s": 27109, "text": "Python3" }, { "code": null, "e": 27120, "s": 27117, "text": "C#" }, { "code": null, "e": 27131, "s": 27120, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>#define inf 100000000using namespace std; // Function to find the smallest path// with exactly K edgesdouble smPath(int s, int d, vector<pair<pair<int, int>, int> > ed, int n, int k){ // Array to store dp int dis[n + 1]; // Initialising the array for (int i = 0; i <= n; i++) dis[i] = inf; dis[s] = 0; // Loop to solve DP for (int i = 0; i < k; i++) { // Initialising next state int dis1[n + 1]; for (int j = 0; j <= n; j++) dis1[j] = inf; // Recurrence relation for (auto it : ed) dis1[it.first.second] = min(dis1[it.first.second], dis[it.first.first] + it.second); for (int i = 0; i <= n; i++) dis[i] = dis1[i]; } // Returning final answer if (dis[d] == inf) return -1; else return dis[d];} // Driver codeint main(){ int n = 4; vector<pair<pair<int, int>, int> > ed; // Input edges ed = { { { 0, 1 }, 10 }, { { 0, 2 }, 3 }, { { 0, 3 }, 2 }, { { 1, 3 }, 7 }, { { 2, 3 }, 7 } }; // Source and Destination int s = 0, d = 3; // Number of edges in path int k = 2; // Calling the function cout << smPath(s, d, ed, n, k);}", "e": 28533, "s": 27131, "text": null }, { "code": "// Java implementation of the above approachimport java.util.ArrayList;import java.util.Arrays; class GFG{ static class Pair<K, V>{ K first; V second; public Pair(K first, V second) { this.first = first; this.second = second; }} static int inf = 100000000; // Function to find the smallest path// with exactly K edgesstatic int smPath(int s, int d, ArrayList<Pair<Pair<Integer, Integer>, Integer>> ed, int n, int k){ // Array to store dp int[] dis = new int[n + 1]; // Initialising the array Arrays.fill(dis, inf); dis[s] = 0; // Loop to solve DP for(int i = 0; i < k; i++) { // Initialising next state int[] dis1 = new int[n + 1]; Arrays.fill(dis1, inf); // Recurrence relation for(Pair<Pair<Integer, Integer>, Integer> it : ed) dis1[it.first.second] = Math.min(dis1[it.first.second], dis[it.first.first] + it.second); for(int j = 0; j <= n; j++) dis[j] = dis1[j]; } // Returning final answer if (dis[d] == inf) return -1; else return dis[d];} // Driver codepublic static void main(String[] args){ int n = 4; // Input edges ArrayList<Pair<Pair<Integer, Integer>, Integer>> ed = new ArrayList<>( Arrays.asList( new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(0, 1), 10), new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(0, 2), 3), new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(0, 3), 2), new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(1, 3), 7), new Pair<Pair<Integer, Integer>, Integer>( new Pair<Integer, Integer>(2, 3), 7) ) ); // Source and Destination int s = 0, d = 3; // Number of edges in path int k = 2; // Calling the function System.out.println(smPath(s, d, ed, n, k));}} // This code is contributed by sanjeev2552", "e": 30807, "s": 28533, "text": null }, { "code": "# Python3 implementation of the above approachinf = 100000000 # Function to find the smallest path# with exactly K edgesdef smPath(s, d, ed, n, k): # Array to store dp dis = [inf] * (n + 1) dis[s] = 0 # Loop to solve DP for i in range(k): # Initialising next state dis1 = [inf] * (n + 1) # Recurrence relation for it in ed: dis1[it[1]] = min(dis1[it[1]], dis[it[0]]+ it[2]) for i in range(n + 1): dis[i] = dis1[i] # Returning final answer if (dis[d] == inf): return -1 else: return dis[d] # Driver codeif __name__ == '__main__': n = 4 # Input edges ed = [ [0, 1 ,10], [ 0, 2 ,3], [ 0, 3 ,2], [ 1, 3 ,7], [ 2, 3 ,7] ] # Source and Destination s = 0 d = 3 # Number of edges in path k = 2 # Calling the function print(smPath(s, d, ed, n, k)) # This code is contributed by mohit kumar 29", "e": 31797, "s": 30807, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Linq;using System.Collections.Generic; public class GFG{ static int inf = 100000000; // Function to find the smallest path// with exactly K edgespublic static int smPath(int s, int d, List<KeyValuePair<KeyValuePair<int, int>, int>> ed, int n, int k){ // Array to store dp // Initialising the array int []dis = Enumerable.Repeat(inf, n+1).ToArray(); dis[s] = 0; // Loop to solve DP for(int i = 0; i < k; i++) { // Initialising next state int []dis1 = Enumerable.Repeat(inf, n+1).ToArray(); // Recurrence relation foreach(KeyValuePair<KeyValuePair<int, int>, int> it in ed) dis1[it.Key.Value] = Math.Min(dis1[it.Key.Value], dis[it.Key.Key] + it.Value); for(int j = 0; j <= n; j++) dis[j] = dis1[j]; } // Returning final answer if (dis[d] == inf) return -1; else return dis[d];} // Driver codepublic static void Main(string[] args){ int n = 4; // Input edges List<KeyValuePair<KeyValuePair<int, int>, int>> ed = new List<KeyValuePair<KeyValuePair<int, int>, int>>(){ new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(0, 1), 10), new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(0, 2), 3), new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(0, 3), 2), new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(1, 3), 7), new KeyValuePair<KeyValuePair<int, int>, int>( new KeyValuePair<int, int>(2, 3), 7) }; // Source and Destination int s = 0, d = 3; // Number of edges in path int k = 2; // Calling the function Console.Write(smPath(s, d, ed, n, k));}} // This code is contributed by rrrtnx.", "e": 33934, "s": 31797, "text": null }, { "code": "<script>// Javascript implementation of the above approach let inf = 100000000; // Function to find the smallest path// with exactly K edgesfunction smPath(s,d,ed,n,k){ // Array to store dp let dis = new Array(n + 1); // Initialising the array for(let i=0;i<(n+1);i++) { dis[i]=inf; } dis[s] = 0; // Loop to solve DP for(let i = 0; i < k; i++) { // Initialising next state let dis1 = new Array(n + 1); for(let i=0;i<(n+1);i++) { dis1[i]=inf; } // Recurrence relation for(let it=0;it< ed.length;it++) dis1[ed[it][1]] = Math.min(dis1[ed[it][1]], dis[ed[it][0]] + ed[it][2]); document.write() for(let j = 0; j <= n; j++) dis[j] = dis1[j]; } // Returning final answer if (dis[d] == inf) return -1; else return dis[d];} // Driver codelet n = 4; // Input edgeslet ed = [ [0, 1 ,10], [ 0, 2 ,3], [ 0, 3 ,2], [ 1, 3 ,7], [ 2, 3 ,7] ];// Source and Destinationlet s = 0, d = 3; // Number of edges in pathlet k = 2; // Calling the functiondocument.write(smPath(s, d, ed, n, k)); // This code is contributed by patel2127</script>", "e": 35282, "s": 33934, "text": null }, { "code": null, "e": 35285, "s": 35282, "text": "10" }, { "code": null, "e": 35335, "s": 35287, "text": "Time complexity: O(E*K) Space complexity: O(N) " }, { "code": null, "e": 35350, "s": 35335, "text": "mohit kumar 29" }, { "code": null, "e": 35362, "s": 35350, "text": "sanjeev2552" }, { "code": null, "e": 35372, "s": 35362, "text": "patel2127" }, { "code": null, "e": 35379, "s": 35372, "text": "rrrtnx" }, { "code": null, "e": 35388, "s": 35379, "text": "ACM-ICPC" }, { "code": null, "e": 35399, "s": 35388, "text": "Algorithms" }, { "code": null, "e": 35419, "s": 35399, "text": "Dynamic Programming" }, { "code": null, "e": 35425, "s": 35419, "text": "Graph" }, { "code": null, "e": 35445, "s": 35425, "text": "Dynamic Programming" }, { "code": null, "e": 35451, "s": 35445, "text": "Graph" }, { "code": null, "e": 35462, "s": 35451, "text": "Algorithms" }, { "code": null, "e": 35560, "s": 35462, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35609, "s": 35560, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 35634, "s": 35609, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 35685, "s": 35634, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 35712, "s": 35685, "text": "Introduction to Algorithms" }, { "code": null, "e": 35740, "s": 35712, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 35769, "s": 35740, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 35799, "s": 35769, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35831, "s": 35799, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 35865, "s": 35831, "text": "Longest Common Subsequence | DP-4" } ]
Amazon product availability checker using Python - GeeksforGeeks
02 Nov, 2021 As we know Python is a multi-purpose language and widely used for scripting. Its usage is not just limited to solve complex calculations but also to automate daily life task. Let’s say we want to track any Amazon product availability and grab the deal when the product availability changes and inform the user of availability through email. It will be a great fun to write a Python script for this.Note: Install the required libraries (as per the code) before running the script. Also, note if the product is not available currently then no email will be sent to user. Asin Id should be provided by the user for the product he wants to keep track of. Working of each module used: -> requests: Used to make HTTP get and post requests -> time: Used to find current time, wait, sleep -> schedule: Used to schedule a function to run again after intervals. It is similar to “setInterval” functionality in JavaScript. -> smptlib: Used to send email using Python. Below is the implementation of above project: Python3 # Python script for Amazon product availability checker# importing librariesfrom lxml import htmlimport requestsfrom time import sleepimport timeimport scheduleimport smtplib # Email id for who want to check availabilityreceiver_email_id = "EMAIL_ID_OF_USER" def check(url): headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'} # adding headers to show that you are # a browser who is sending GET request page = requests.get(url, headers = headers) for i in range(20): # because continuous checks in # milliseconds or few seconds # blocks your request sleep(3) # parsing the html content doc = html.fromstring(page.content) # checking availability XPATH_AVAILABILITY = '//div[@id ="availability"]//text()' RAw_AVAILABILITY = doc.xpath(XPATH_AVAILABILITY) AVAILABILITY = ''.join(RAw_AVAILABILITY).strip() if RAw_AVAILABILITY else None return AVAILABILITY def sendemail(ans, product): GMAIL_USERNAME = "YOUR_GMAIL_ID" GMAIL_PASSWORD = "YOUR_GMAIL_PASSWORD" recipient = receiver_email_id body_of_email = ans email_subject = product + ' product availability' # creates SMTP session s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security s.starttls() # Authentication s.login(GMAIL_USERNAME, GMAIL_PASSWORD) # message to be sent headers = "\r\n".join(["from: " + GMAIL_USERNAME, "subject: " + email_subject, "to: " + recipient, "mime-version: 1.0", "content-type: text/html"]) content = headers + "\r\n\r\n" + body_of_email s.sendmail(GMAIL_USERNAME, recipient, content) s.quit() def ReadAsin(): # Asin Id is the product Id which # needs to be provided by the user Asin = 'B077PWK5BT' url = "http://www.amazon.in/dp/" + Asin print ("Processing: "+url) ans = check(url) arr = [ 'Only 1 left in stock.', 'Only 2 left in stock.', 'In stock.'] print(ans) if ans in arr: # sending email to user if # in case product available sendemail(ans, Asin) # scheduling same code to run multiple# times after every 1 minutedef job(): print("Tracking....") ReadAsin() schedule.every(1).minutes.do(job) while True: # running all pending tasks/jobs schedule.run_pending() time.sleep(1) Output: Tracking.... Processing: http://www.amazon.in/dp/B077PWK5BT Only 1 left in stock. Tracking.... Processing: http://www.amazon.in/dp/B077PWK5BT Only 1 left in stock. Tracking.... Processing: http://www.amazon.in/dp/B077PWK5BT Only 1 left in stock. Note that the program might throw an error (Critical security alert/Sign-in attempt was blocked) while sending the mail to the user, which can be handled by modifying the security setting in the mail application you are using. abhishek0719kadiyan varshagumber28 python-utility Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation Twitter Sentiment Analysis using Python Java Swing | Simple User Registration Form Snake Game in C Program for Employee Management System Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24578, "s": 24550, "text": "\n02 Nov, 2021" }, { "code": null, "e": 25230, "s": 24578, "text": "As we know Python is a multi-purpose language and widely used for scripting. Its usage is not just limited to solve complex calculations but also to automate daily life task. Let’s say we want to track any Amazon product availability and grab the deal when the product availability changes and inform the user of availability through email. It will be a great fun to write a Python script for this.Note: Install the required libraries (as per the code) before running the script. Also, note if the product is not available currently then no email will be sent to user. Asin Id should be provided by the user for the product he wants to keep track of. " }, { "code": null, "e": 25536, "s": 25230, "text": "Working of each module used: -> requests: Used to make HTTP get and post requests -> time: Used to find current time, wait, sleep -> schedule: Used to schedule a function to run again after intervals. It is similar to “setInterval” functionality in JavaScript. -> smptlib: Used to send email using Python." }, { "code": null, "e": 25583, "s": 25536, "text": "Below is the implementation of above project: " }, { "code": null, "e": 25591, "s": 25583, "text": "Python3" }, { "code": "# Python script for Amazon product availability checker# importing librariesfrom lxml import htmlimport requestsfrom time import sleepimport timeimport scheduleimport smtplib # Email id for who want to check availabilityreceiver_email_id = \"EMAIL_ID_OF_USER\" def check(url): headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'} # adding headers to show that you are # a browser who is sending GET request page = requests.get(url, headers = headers) for i in range(20): # because continuous checks in # milliseconds or few seconds # blocks your request sleep(3) # parsing the html content doc = html.fromstring(page.content) # checking availability XPATH_AVAILABILITY = '//div[@id =\"availability\"]//text()' RAw_AVAILABILITY = doc.xpath(XPATH_AVAILABILITY) AVAILABILITY = ''.join(RAw_AVAILABILITY).strip() if RAw_AVAILABILITY else None return AVAILABILITY def sendemail(ans, product): GMAIL_USERNAME = \"YOUR_GMAIL_ID\" GMAIL_PASSWORD = \"YOUR_GMAIL_PASSWORD\" recipient = receiver_email_id body_of_email = ans email_subject = product + ' product availability' # creates SMTP session s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security s.starttls() # Authentication s.login(GMAIL_USERNAME, GMAIL_PASSWORD) # message to be sent headers = \"\\r\\n\".join([\"from: \" + GMAIL_USERNAME, \"subject: \" + email_subject, \"to: \" + recipient, \"mime-version: 1.0\", \"content-type: text/html\"]) content = headers + \"\\r\\n\\r\\n\" + body_of_email s.sendmail(GMAIL_USERNAME, recipient, content) s.quit() def ReadAsin(): # Asin Id is the product Id which # needs to be provided by the user Asin = 'B077PWK5BT' url = \"http://www.amazon.in/dp/\" + Asin print (\"Processing: \"+url) ans = check(url) arr = [ 'Only 1 left in stock.', 'Only 2 left in stock.', 'In stock.'] print(ans) if ans in arr: # sending email to user if # in case product available sendemail(ans, Asin) # scheduling same code to run multiple# times after every 1 minutedef job(): print(\"Tracking....\") ReadAsin() schedule.every(1).minutes.do(job) while True: # running all pending tasks/jobs schedule.run_pending() time.sleep(1)", "e": 28121, "s": 25591, "text": null }, { "code": null, "e": 28131, "s": 28121, "text": "Output: " }, { "code": null, "e": 28377, "s": 28131, "text": "Tracking....\nProcessing: http://www.amazon.in/dp/B077PWK5BT\nOnly 1 left in stock.\nTracking....\nProcessing: http://www.amazon.in/dp/B077PWK5BT\nOnly 1 left in stock.\nTracking....\nProcessing: http://www.amazon.in/dp/B077PWK5BT\nOnly 1 left in stock." }, { "code": null, "e": 28606, "s": 28377, "text": "Note that the program might throw an error (Critical security alert/Sign-in attempt was blocked) while sending the mail to the user, which can be handled by modifying the security setting in the mail application you are using. " }, { "code": null, "e": 28626, "s": 28606, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28641, "s": 28626, "text": "varshagumber28" }, { "code": null, "e": 28656, "s": 28641, "text": "python-utility" }, { "code": null, "e": 28664, "s": 28656, "text": "Project" }, { "code": null, "e": 28671, "s": 28664, "text": "Python" }, { "code": null, "e": 28769, "s": 28671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28818, "s": 28769, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 28858, "s": 28818, "text": "Twitter Sentiment Analysis using Python" }, { "code": null, "e": 28901, "s": 28858, "text": "Java Swing | Simple User Registration Form" }, { "code": null, "e": 28917, "s": 28901, "text": "Snake Game in C" }, { "code": null, "e": 28956, "s": 28917, "text": "Program for Employee Management System" }, { "code": null, "e": 28984, "s": 28956, "text": "Read JSON file using Python" }, { "code": null, "e": 29034, "s": 28984, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29056, "s": 29034, "text": "Python map() function" } ]
Build a Super Simple GAN in PyTorch | by Nicolas Bertagnolli | Towards Data Science
Generative Adversarial Networks (GANs) are a model framework where two models are trained together: one learns to generate synthetic data from the same distribution as the training set and the other learns to distinguish true data from generated data. When I was first learning about them, I remember being kind of overwhelmed with how to construct the joint training. I haven’t seen a tutorial yet that focuses on building a trivial GAN so I’m going to try and do that here. No image generation, no fancy deep fried conv nets. We are going to train a model capable of learning to generate even numbers in about 50 lines of Python code. All of the code for this project can be found in the github repository here. GANs are composed of two models trained in unison. The first model, the generator, takes in some random input and tries to output something that looks like our training data. The second model, the discriminator, takes in training data and generated data and tries to distinguish the fake generated data from the real training data. What makes this framework interesting is that these models are trained together. As the discriminator gets better at recognizing fake images this learning is passed to the generator and the generator gets better at generating fake images. To overuse an analogy the generator is to the discriminator as a counterfeiter is to FBI investigators. One tries to forge data, the other tries to distinguish forgeries from the real deal. This framework has produced a ton of super interesting results in the last few years from translating horses to zebras, to creating deep fakes, to imagining up wholly new images. In this tutorial we aren’t going to do anything as interesting as those but this should give you all of the background you need in order to successfully implement a GAN of your own from scratch : ). Let’s get started. Imagine that we have a data set of all even numbers between zero and 128. This is a subset of a much bigger distribution of data, the integers, with some specific properties, much like how human faces are a subset of all images of living things. Our generator is going to take in random noise as an integer in that same range and learn to produce only even numbers. Before getting into the actual model let’s build out our data set. We are going to represent each integer as it’s unsigned seven bit binary representation. So the number 56 is 0111000. We do this because: It is very natural to pass in a binary vector to a machine learning algorithm, in this case, a neural network.It is easy to see if the model is generating even numbers by looking at the lowest bit. If it’s a one the number is odd, if it’s a zero the number is even. It is very natural to pass in a binary vector to a machine learning algorithm, in this case, a neural network. It is easy to see if the model is generating even numbers by looking at the lowest bit. If it’s a one the number is odd, if it’s a zero the number is even. To start let’s write a function which converts any positive integer to its binary form as a list. With this we can make a function which will generate random training data for us on the fly. This function will produce two outputs the first is a list of ones representing that this data is even and comes from our true distribution. The second output is a random even number in binary list form. That’s all we need to start building and training our models! Building the Generator and Discriminator is a snap! Let’s start with the Generator. We need something capable of mapping random seven digit binary input to seven digit binary input that is even. The simplest possible thing here is a single seven neuron layer. If we were building a GAN to do something more complicated on say images we would probably train it using random noise generated from a normal distribution and gradually upsample and reshape it until it’s the same size as the data we are trying to copy. Since our example is so simple, a single linear layer with a logistic (sigmoid) activation should be enough to map ones and zeros in seven positions to other ones and zeros in seven positions. The Discriminator is no more complicated than the Generator. Here we need a model to take in a seven digit binary input and output whether or not it is from our real data distribution (is even) or not (is odd or not a number). To accomplish this we use a single neuron model (logistic regression) with a logistic activation (Sigmoid). That’s it, we’ve built the two models which we will train in unison. Now for the tricky part of GAN training, the training. We need to link these models up in a way that can propagate the gradients around correctly. Training GANs can seem a bit confusing at first because we need to update two models with every bit of input and we need to be careful about how we do that. So to break it down, we pass two batches of data to our model at every training step. One batch is random noise which will cause the generator to create some generated data, and the second batch is composed solely of data from our true distribution. Throughout the training description, I will reference line numbers in the final training code gist below, not the Github repository. Let’s start by training the generator. This consists of: Creating random noise. (Line 27)Generating new “fake” data by passing the noise to the generator (Line 28)Get the predictions from the discriminator on the “fake” data (Line 38)Calculate the loss from the discriminator’s output using labels as if the data were “real” instead of fake. (Line 39)Backpropagate the error through just the generator. (Lines 40–41) Creating random noise. (Line 27) Generating new “fake” data by passing the noise to the generator (Line 28) Get the predictions from the discriminator on the “fake” data (Line 38) Calculate the loss from the discriminator’s output using labels as if the data were “real” instead of fake. (Line 39) Backpropagate the error through just the generator. (Lines 40–41) Notice how in step four we use true labels instead of fake labels for calculating the loss. This is because we are training the generator. The generator should be trying to fool the discriminator so when the discriminator makes a mistake and says the generated output is real (predicts 1) then the gradients should be small, when the discriminator acts correctly and predicts that the output is generated (predicts 0) the gradients should be big. This is why we only propagate the gradients through the generator at this step, because we inverted the labels. If we trained the entire model like this either the generator would learn the wrong thing or the discriminator would. Now it’s time to update the weights in our discriminator. We do that in a few steps: Pass in a batch of only data from the true data set with a vector of all one labels. (Lines 44–46)Pass our generated data into the discriminator, with detached weights, and zero labels. (Lines 49–50)Average the loss from steps one and two. (Line 51)Backpropagate the gradients through just the discriminator. (Lines 52–53) Pass in a batch of only data from the true data set with a vector of all one labels. (Lines 44–46) Pass our generated data into the discriminator, with detached weights, and zero labels. (Lines 49–50) Average the loss from steps one and two. (Line 51) Backpropagate the gradients through just the discriminator. (Lines 52–53) The discriminator is trying to learn to distinguish real data from “fake” generated data. The labels while training the discriminator need to represent that, i.e. one when our data comes from the real data set and zero when it is generated by our generator. We pass in those two batches in steps (1) and (2) above and then average the loss from the two batches. It’s important to note that when passing in the generated data we want to detach the gradients. We do this because we are not training the generator we are just focused on the discriminator. Once all of that is done we backpropagate the gradients in only the discriminator and we are done. That’s it! We’ve built our entire GAN. Wrap that in a training loop with some gradient zeroing at each step and we’re ready to roll. If we look at the output of our generator at various training steps we can see it converging to only creating even numbers which is exactly what we wanted! 0 : [47, 3, 35, 1, 16, 56, 39, 16, 3, 1]50 : [2, 35, 34, 34, 38, 2, 34, 43, 3, 43]100 : [42, 43, 106, 38, 35, 42, 35, 42, 43, 106]200 : [108, 106, 106, 42, 106, 42, 106, 106, 42, 96] At step zero we have 7/10 odd numbers in our sample and at step 200 10/10 of our samples are even numbers! That’s a successful generator and it only took ~50 lines of real Python code! As you’ve probably guessed there are some other tricks for training a GAN which generates non trivial output. Some immediate things to try if you want to make this model work on real data like images are: The Generator will probably need to be a bit deeper and scale up the noise to the size of the real data. You can do this using transposed convolutions or upsampling layers.Change the noise input to the generator to be GaussianIncrease the depth of the discriminator so that its capacity for prediction is better.Train for much much longer and monitor the loss. The Generator will probably need to be a bit deeper and scale up the noise to the size of the real data. You can do this using transposed convolutions or upsampling layers. Change the noise input to the generator to be Gaussian Increase the depth of the discriminator so that its capacity for prediction is better. Train for much much longer and monitor the loss. As a good next step try and implement the DCGAN architecture. This code will get you 90% of the way there. Once you’ve done that and made some fun images like those in the introduction, try and improve them by playing around with training hyper parameters. A good list of things to try when training real GANs can be found here.
[ { "code": null, "e": 885, "s": 171, "text": "Generative Adversarial Networks (GANs) are a model framework where two models are trained together: one learns to generate synthetic data from the same distribution as the training set and the other learns to distinguish true data from generated data. When I was first learning about them, I remember being kind of overwhelmed with how to construct the joint training. I haven’t seen a tutorial yet that focuses on building a trivial GAN so I’m going to try and do that here. No image generation, no fancy deep fried conv nets. We are going to train a model capable of learning to generate even numbers in about 50 lines of Python code. All of the code for this project can be found in the github repository here." }, { "code": null, "e": 1646, "s": 885, "text": "GANs are composed of two models trained in unison. The first model, the generator, takes in some random input and tries to output something that looks like our training data. The second model, the discriminator, takes in training data and generated data and tries to distinguish the fake generated data from the real training data. What makes this framework interesting is that these models are trained together. As the discriminator gets better at recognizing fake images this learning is passed to the generator and the generator gets better at generating fake images. To overuse an analogy the generator is to the discriminator as a counterfeiter is to FBI investigators. One tries to forge data, the other tries to distinguish forgeries from the real deal." }, { "code": null, "e": 2043, "s": 1646, "text": "This framework has produced a ton of super interesting results in the last few years from translating horses to zebras, to creating deep fakes, to imagining up wholly new images. In this tutorial we aren’t going to do anything as interesting as those but this should give you all of the background you need in order to successfully implement a GAN of your own from scratch : ). Let’s get started." }, { "code": null, "e": 2409, "s": 2043, "text": "Imagine that we have a data set of all even numbers between zero and 128. This is a subset of a much bigger distribution of data, the integers, with some specific properties, much like how human faces are a subset of all images of living things. Our generator is going to take in random noise as an integer in that same range and learn to produce only even numbers." }, { "code": null, "e": 2614, "s": 2409, "text": "Before getting into the actual model let’s build out our data set. We are going to represent each integer as it’s unsigned seven bit binary representation. So the number 56 is 0111000. We do this because:" }, { "code": null, "e": 2880, "s": 2614, "text": "It is very natural to pass in a binary vector to a machine learning algorithm, in this case, a neural network.It is easy to see if the model is generating even numbers by looking at the lowest bit. If it’s a one the number is odd, if it’s a zero the number is even." }, { "code": null, "e": 2991, "s": 2880, "text": "It is very natural to pass in a binary vector to a machine learning algorithm, in this case, a neural network." }, { "code": null, "e": 3147, "s": 2991, "text": "It is easy to see if the model is generating even numbers by looking at the lowest bit. If it’s a one the number is odd, if it’s a zero the number is even." }, { "code": null, "e": 3245, "s": 3147, "text": "To start let’s write a function which converts any positive integer to its binary form as a list." }, { "code": null, "e": 3338, "s": 3245, "text": "With this we can make a function which will generate random training data for us on the fly." }, { "code": null, "e": 3604, "s": 3338, "text": "This function will produce two outputs the first is a list of ones representing that this data is even and comes from our true distribution. The second output is a random even number in binary list form. That’s all we need to start building and training our models!" }, { "code": null, "e": 3864, "s": 3604, "text": "Building the Generator and Discriminator is a snap! Let’s start with the Generator. We need something capable of mapping random seven digit binary input to seven digit binary input that is even. The simplest possible thing here is a single seven neuron layer." }, { "code": null, "e": 4311, "s": 3864, "text": "If we were building a GAN to do something more complicated on say images we would probably train it using random noise generated from a normal distribution and gradually upsample and reshape it until it’s the same size as the data we are trying to copy. Since our example is so simple, a single linear layer with a logistic (sigmoid) activation should be enough to map ones and zeros in seven positions to other ones and zeros in seven positions." }, { "code": null, "e": 4646, "s": 4311, "text": "The Discriminator is no more complicated than the Generator. Here we need a model to take in a seven digit binary input and output whether or not it is from our real data distribution (is even) or not (is odd or not a number). To accomplish this we use a single neuron model (logistic regression) with a logistic activation (Sigmoid)." }, { "code": null, "e": 4862, "s": 4646, "text": "That’s it, we’ve built the two models which we will train in unison. Now for the tricky part of GAN training, the training. We need to link these models up in a way that can propagate the gradients around correctly." }, { "code": null, "e": 5402, "s": 4862, "text": "Training GANs can seem a bit confusing at first because we need to update two models with every bit of input and we need to be careful about how we do that. So to break it down, we pass two batches of data to our model at every training step. One batch is random noise which will cause the generator to create some generated data, and the second batch is composed solely of data from our true distribution. Throughout the training description, I will reference line numbers in the final training code gist below, not the Github repository." }, { "code": null, "e": 5459, "s": 5402, "text": "Let’s start by training the generator. This consists of:" }, { "code": null, "e": 5819, "s": 5459, "text": "Creating random noise. (Line 27)Generating new “fake” data by passing the noise to the generator (Line 28)Get the predictions from the discriminator on the “fake” data (Line 38)Calculate the loss from the discriminator’s output using labels as if the data were “real” instead of fake. (Line 39)Backpropagate the error through just the generator. (Lines 40–41)" }, { "code": null, "e": 5852, "s": 5819, "text": "Creating random noise. (Line 27)" }, { "code": null, "e": 5927, "s": 5852, "text": "Generating new “fake” data by passing the noise to the generator (Line 28)" }, { "code": null, "e": 5999, "s": 5927, "text": "Get the predictions from the discriminator on the “fake” data (Line 38)" }, { "code": null, "e": 6117, "s": 5999, "text": "Calculate the loss from the discriminator’s output using labels as if the data were “real” instead of fake. (Line 39)" }, { "code": null, "e": 6183, "s": 6117, "text": "Backpropagate the error through just the generator. (Lines 40–41)" }, { "code": null, "e": 6860, "s": 6183, "text": "Notice how in step four we use true labels instead of fake labels for calculating the loss. This is because we are training the generator. The generator should be trying to fool the discriminator so when the discriminator makes a mistake and says the generated output is real (predicts 1) then the gradients should be small, when the discriminator acts correctly and predicts that the output is generated (predicts 0) the gradients should be big. This is why we only propagate the gradients through the generator at this step, because we inverted the labels. If we trained the entire model like this either the generator would learn the wrong thing or the discriminator would." }, { "code": null, "e": 6945, "s": 6860, "text": "Now it’s time to update the weights in our discriminator. We do that in a few steps:" }, { "code": null, "e": 7268, "s": 6945, "text": "Pass in a batch of only data from the true data set with a vector of all one labels. (Lines 44–46)Pass our generated data into the discriminator, with detached weights, and zero labels. (Lines 49–50)Average the loss from steps one and two. (Line 51)Backpropagate the gradients through just the discriminator. (Lines 52–53)" }, { "code": null, "e": 7367, "s": 7268, "text": "Pass in a batch of only data from the true data set with a vector of all one labels. (Lines 44–46)" }, { "code": null, "e": 7469, "s": 7367, "text": "Pass our generated data into the discriminator, with detached weights, and zero labels. (Lines 49–50)" }, { "code": null, "e": 7520, "s": 7469, "text": "Average the loss from steps one and two. (Line 51)" }, { "code": null, "e": 7594, "s": 7520, "text": "Backpropagate the gradients through just the discriminator. (Lines 52–53)" }, { "code": null, "e": 8246, "s": 7594, "text": "The discriminator is trying to learn to distinguish real data from “fake” generated data. The labels while training the discriminator need to represent that, i.e. one when our data comes from the real data set and zero when it is generated by our generator. We pass in those two batches in steps (1) and (2) above and then average the loss from the two batches. It’s important to note that when passing in the generated data we want to detach the gradients. We do this because we are not training the generator we are just focused on the discriminator. Once all of that is done we backpropagate the gradients in only the discriminator and we are done." }, { "code": null, "e": 8535, "s": 8246, "text": "That’s it! We’ve built our entire GAN. Wrap that in a training loop with some gradient zeroing at each step and we’re ready to roll. If we look at the output of our generator at various training steps we can see it converging to only creating even numbers which is exactly what we wanted!" }, { "code": null, "e": 8721, "s": 8535, "text": "0 : [47, 3, 35, 1, 16, 56, 39, 16, 3, 1]50 : [2, 35, 34, 34, 38, 2, 34, 43, 3, 43]100 : [42, 43, 106, 38, 35, 42, 35, 42, 43, 106]200 : [108, 106, 106, 42, 106, 42, 106, 106, 42, 96]" }, { "code": null, "e": 8906, "s": 8721, "text": "At step zero we have 7/10 odd numbers in our sample and at step 200 10/10 of our samples are even numbers! That’s a successful generator and it only took ~50 lines of real Python code!" }, { "code": null, "e": 9111, "s": 8906, "text": "As you’ve probably guessed there are some other tricks for training a GAN which generates non trivial output. Some immediate things to try if you want to make this model work on real data like images are:" }, { "code": null, "e": 9472, "s": 9111, "text": "The Generator will probably need to be a bit deeper and scale up the noise to the size of the real data. You can do this using transposed convolutions or upsampling layers.Change the noise input to the generator to be GaussianIncrease the depth of the discriminator so that its capacity for prediction is better.Train for much much longer and monitor the loss." }, { "code": null, "e": 9645, "s": 9472, "text": "The Generator will probably need to be a bit deeper and scale up the noise to the size of the real data. You can do this using transposed convolutions or upsampling layers." }, { "code": null, "e": 9700, "s": 9645, "text": "Change the noise input to the generator to be Gaussian" }, { "code": null, "e": 9787, "s": 9700, "text": "Increase the depth of the discriminator so that its capacity for prediction is better." }, { "code": null, "e": 9836, "s": 9787, "text": "Train for much much longer and monitor the loss." } ]
AngularJS - Modules
AngularJS supports modular approach. Modules are used to separate logic such as services, controllers, application etc. from the code and maintain the code clean. We define modules in separate js files and name them as per the module.js file. In the following example, we are going to create two modules − Application Module − used to initialize an application with controller(s). Application Module − used to initialize an application with controller(s). Controller Module − used to define the controller. Controller Module − used to define the controller. Here is a file named mainApp.js that contains the following code − var mainApp = angular.module("mainApp", []); Here, we declare an application mainApp module using angular.module function and pass an empty array to it. This array generally contains dependent modules. mainApp.controller("studentController", function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fees:500, subjects:[ {name:'Physics',marks:70}, {name:'Chemistry',marks:80}, {name:'Math',marks:65}, {name:'English',marks:75}, {name:'Hindi',marks:67} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); Here, we declare a controller studentController module using mainApp.controller function. <div ng-app = "mainApp" ng-controller = "studentController"> ... <script src = "mainApp.js"></script> <script src = "studentController.js"></script> </div> Here, we use application module using ng-app directive, and controller using ngcontroller directive. We import the mainApp.js and studentController.js in the main HTML page. The following example shows use of all the above mentioned modules. <html> <head> <title>Angular JS Modules</title> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script src = "/angularjs/src/module/mainApp.js"></script> <script src = "/angularjs/src/module/studentController.js"></script> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "studentController"> <table border = "0"> <tr> <td>Enter first name:</td> <td><input type = "text" ng-model = "student.firstName"></td> </tr> <tr> <td>Enter last name: </td> <td><input type = "text" ng-model = "student.lastName"></td> </tr> <tr> <td>Name: </td> <td>{{student.fullName()}}</td> </tr> <tr> <td>Subject:</td> <td> <table> <tr> <th>Name</th> <th>Marks</th> </tr> <tr ng-repeat = "subject in student.subjects"> <td>{{ subject.name }}</td> <td>{{ subject.marks }}</td> </tr> </table> </td> </tr> </table> </div> </body> </html> var mainApp = angular.module("mainApp", []); mainApp.controller("studentController", function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fees:500, subjects:[ {name:'Physics',marks:70}, {name:'Chemistry',marks:80}, {name:'Math',marks:65}, {name:'English',marks:75}, {name:'Hindi',marks:67} ], fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); Open the file textAngularJS.htm in a web browser. See the result. 16 Lectures 1.5 hours Anadi Sharma 40 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 3005, "s": 2699, "text": "AngularJS supports modular approach. Modules are used to separate logic such as services, controllers, application etc. from the code and maintain the code clean. We define modules in separate js files and name them as per the module.js file. In the following example, we are going to create two modules −" }, { "code": null, "e": 3080, "s": 3005, "text": "Application Module − used to initialize an application with controller(s)." }, { "code": null, "e": 3155, "s": 3080, "text": "Application Module − used to initialize an application with controller(s)." }, { "code": null, "e": 3206, "s": 3155, "text": "Controller Module − used to define the controller." }, { "code": null, "e": 3257, "s": 3206, "text": "Controller Module − used to define the controller." }, { "code": null, "e": 3324, "s": 3257, "text": "Here is a file named mainApp.js that contains the following code −" }, { "code": null, "e": 3370, "s": 3324, "text": "var mainApp = angular.module(\"mainApp\", []);\n" }, { "code": null, "e": 3527, "s": 3370, "text": "Here, we declare an application mainApp module using angular.module function and pass an empty array to it. This array generally contains dependent modules." }, { "code": null, "e": 4076, "s": 3527, "text": "mainApp.controller(\"studentController\", function($scope) {\n $scope.student = {\n firstName: \"Mahesh\",\n lastName: \"Parashar\",\n fees:500,\n \n subjects:[\n {name:'Physics',marks:70},\n {name:'Chemistry',marks:80},\n {name:'Math',marks:65},\n {name:'English',marks:75},\n {name:'Hindi',marks:67}\n ],\n fullName: function() {\n var studentObject;\n studentObject = $scope.student;\n return studentObject.firstName + \" \" + studentObject.lastName;\n }\n };\n});" }, { "code": null, "e": 4166, "s": 4076, "text": "Here, we declare a controller studentController module using mainApp.controller function." }, { "code": null, "e": 4334, "s": 4166, "text": "<div ng-app = \"mainApp\" ng-controller = \"studentController\">\n ...\n <script src = \"mainApp.js\"></script>\n <script src = \"studentController.js\"></script>\n\t\n</div>\n" }, { "code": null, "e": 4508, "s": 4334, "text": "Here, we use application module using ng-app directive, and controller using ngcontroller directive. We import the mainApp.js and studentController.js in the main HTML page." }, { "code": null, "e": 4576, "s": 4508, "text": "The following example shows use of all the above mentioned modules." }, { "code": null, "e": 6381, "s": 4576, "text": "<html>\n <head>\n <title>Angular JS Modules</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"></script>\n <script src = \"/angularjs/src/module/mainApp.js\"></script>\n <script src = \"/angularjs/src/module/studentController.js\"></script>\n \n <style>\n table, th , td {\n border: 1px solid grey;\n border-collapse: collapse;\n padding: 5px;\n }\n table tr:nth-child(odd) {\n background-color: #f2f2f2;\n }\n table tr:nth-child(even) {\n background-color: #ffffff;\n }\n </style>\n </head>\n \n <body>\n <h2>AngularJS Sample Application</h2>\n <div ng-app = \"mainApp\" ng-controller = \"studentController\">\n \n <table border = \"0\">\n <tr>\n <td>Enter first name:</td>\n <td><input type = \"text\" ng-model = \"student.firstName\"></td>\n </tr>\n <tr>\n <td>Enter last name: </td>\n <td><input type = \"text\" ng-model = \"student.lastName\"></td>\n </tr>\n <tr>\n <td>Name: </td>\n <td>{{student.fullName()}}</td>\n </tr>\n <tr>\n <td>Subject:</td>\n \n <td>\n <table>\n <tr>\n <th>Name</th>\n <th>Marks</th>\n </tr>\n <tr ng-repeat = \"subject in student.subjects\">\n <td>{{ subject.name }}</td>\n <td>{{ subject.marks }}</td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </div>\n \n </body>\n</html>" }, { "code": null, "e": 6426, "s": 6381, "text": "var mainApp = angular.module(\"mainApp\", []);" }, { "code": null, "e": 6975, "s": 6426, "text": "mainApp.controller(\"studentController\", function($scope) {\n $scope.student = {\n firstName: \"Mahesh\",\n lastName: \"Parashar\",\n fees:500,\n \n subjects:[\n {name:'Physics',marks:70},\n {name:'Chemistry',marks:80},\n {name:'Math',marks:65},\n {name:'English',marks:75},\n {name:'Hindi',marks:67}\n ],\n fullName: function() {\n var studentObject;\n studentObject = $scope.student;\n return studentObject.firstName + \" \" + studentObject.lastName;\n }\n };\n});" }, { "code": null, "e": 7041, "s": 6975, "text": "Open the file textAngularJS.htm in a web browser. See the result." }, { "code": null, "e": 7076, "s": 7041, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7090, "s": 7076, "text": " Anadi Sharma" }, { "code": null, "e": 7125, "s": 7090, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7145, "s": 7125, "text": " Skillbakerystudios" }, { "code": null, "e": 7152, "s": 7145, "text": " Print" }, { "code": null, "e": 7163, "s": 7152, "text": " Add Notes" } ]
Build a Basic React App that Display “Hello World!” - GeeksforGeeks
30 Sep, 2021 React is a Javascript Library that was created by Facebook for building better User Interface(UI) web applications and mobile applications. It is an open source library for creating interactive and dynamic applications. In this article, we will see how to build a basic react app that shows hello world. To create a react application, Node.js version of at least 10 or higher need to be installed on your system. If it is installed you can check by using the following command in your command line. node -v Make sure you have a code editor for working on your project files. To build a react application follow the below steps: Step 1: Create a react application using the following command npx create-react-app foldername It takes a couple of minutes to install the packages. Step 2: Once it is done change your directory to the newly created application using the following command cd foldername Project Structure: It is created as shown below. Project file structure Step 3: Now inside App.js and write down the following code as shown below: Javascript import React from 'react';import './App.css'; function App() { return ( <h1> Hello World! </h1> );} export default App; Step to run the application: Enter the following command to run the application. npm start Output: You will see the following output in your browser. Congratulations, you have created your first react app. You have learnt something new today. Don’t stop learning Go ahead. Learn React.js Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments React-Router Hooks How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? Axios in React: A Guide for Beginners Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24813, "s": 24785, "text": "\n30 Sep, 2021" }, { "code": null, "e": 25033, "s": 24813, "text": "React is a Javascript Library that was created by Facebook for building better User Interface(UI) web applications and mobile applications. It is an open source library for creating interactive and dynamic applications." }, { "code": null, "e": 25117, "s": 25033, "text": "In this article, we will see how to build a basic react app that shows hello world." }, { "code": null, "e": 25312, "s": 25117, "text": "To create a react application, Node.js version of at least 10 or higher need to be installed on your system. If it is installed you can check by using the following command in your command line." }, { "code": null, "e": 25321, "s": 25312, "text": "node -v " }, { "code": null, "e": 25389, "s": 25321, "text": "Make sure you have a code editor for working on your project files." }, { "code": null, "e": 25442, "s": 25389, "text": "To build a react application follow the below steps:" }, { "code": null, "e": 25507, "s": 25442, "text": "Step 1: Create a react application using the following command " }, { "code": null, "e": 25539, "s": 25507, "text": "npx create-react-app foldername" }, { "code": null, "e": 25593, "s": 25539, "text": "It takes a couple of minutes to install the packages." }, { "code": null, "e": 25702, "s": 25593, "text": "Step 2: Once it is done change your directory to the newly created application using the following command " }, { "code": null, "e": 25716, "s": 25702, "text": "cd foldername" }, { "code": null, "e": 25765, "s": 25716, "text": "Project Structure: It is created as shown below." }, { "code": null, "e": 25788, "s": 25765, "text": "Project file structure" }, { "code": null, "e": 25864, "s": 25788, "text": "Step 3: Now inside App.js and write down the following code as shown below:" }, { "code": null, "e": 25875, "s": 25864, "text": "Javascript" }, { "code": "import React from 'react';import './App.css'; function App() { return ( <h1> Hello World! </h1> );} export default App;", "e": 26009, "s": 25875, "text": null }, { "code": null, "e": 26090, "s": 26009, "text": "Step to run the application: Enter the following command to run the application." }, { "code": null, "e": 26100, "s": 26090, "text": "npm start" }, { "code": null, "e": 26159, "s": 26100, "text": "Output: You will see the following output in your browser." }, { "code": null, "e": 26298, "s": 26159, "text": "Congratulations, you have created your first react app. You have learnt something new today. Don’t stop learning Go ahead. Learn React.js" }, { "code": null, "e": 26305, "s": 26298, "text": "Picked" }, { "code": null, "e": 26321, "s": 26305, "text": "React-Questions" }, { "code": null, "e": 26329, "s": 26321, "text": "ReactJS" }, { "code": null, "e": 26346, "s": 26329, "text": "Web Technologies" }, { "code": null, "e": 26444, "s": 26346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26453, "s": 26444, "text": "Comments" }, { "code": null, "e": 26466, "s": 26453, "text": "Old Comments" }, { "code": null, "e": 26485, "s": 26466, "text": "React-Router Hooks" }, { "code": null, "e": 26527, "s": 26485, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 26562, "s": 26527, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 26620, "s": 26562, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 26658, "s": 26620, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 26700, "s": 26658, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26733, "s": 26700, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26795, "s": 26733, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26845, "s": 26795, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
MySQL query to fetch the latest date from a table with date records
Let us first create a table − mysql> create table DemoTable ( DueDate date ); Query OK, 0 rows affected (0.56 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('2018-10-01'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('2016-12-31'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('2019-07-02'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2015-01-12'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('2019-04-26'); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +------------+ | DueDate | +------------+ | 2018-10-01 | | 2016-12-31 | | 2019-07-02 | | 2015-01-12 | | 2019-04-26 | +------------+ 5 rows in set (0.00 sec) Let’s say the current date is 2019-08-15. Now we will fetch the latest date − mysql> select *from DemoTable order by DueDate DESC limit 1; This will produce the following output − +------------+ | DueDate | +------------+ | 2019-07-02 | +------------+ 1 row in set (0.03 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1180, "s": 1092, "text": "mysql> create table DemoTable\n(\n DueDate date\n);\nQuery OK, 0 rows affected (0.56 sec)" }, { "code": null, "e": 1236, "s": 1180, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1671, "s": 1236, "text": "mysql> insert into DemoTable values('2018-10-01');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('2016-12-31');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('2019-07-02');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values('2015-01-12');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values('2019-04-26');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 1731, "s": 1671, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1762, "s": 1731, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1803, "s": 1762, "text": "This will produce the following output −" }, { "code": null, "e": 1963, "s": 1803, "text": "+------------+\n| DueDate |\n+------------+\n| 2018-10-01 |\n| 2016-12-31 |\n| 2019-07-02 |\n| 2015-01-12 |\n| 2019-04-26 |\n+------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2041, "s": 1963, "text": "Let’s say the current date is 2019-08-15. Now we will fetch the latest date −" }, { "code": null, "e": 2102, "s": 2041, "text": "mysql> select *from DemoTable order by DueDate DESC limit 1;" }, { "code": null, "e": 2143, "s": 2102, "text": "This will produce the following output −" }, { "code": null, "e": 2242, "s": 2143, "text": "+------------+\n| DueDate |\n+------------+\n| 2019-07-02 |\n+------------+\n1 row in set (0.03 sec)" } ]
C++ Program to Convert Km/hr to miles/hr and vice versa
If input is in km/hr convert it to miles/hr else input will be in miles/hr convert it to km/hr. There are formulas that can be used for this conversion. Conversion Formulas − 1 kilo-metre = 0.621371 miles 1 miles = 1.60934 Kilo-meter Input-: kmph= 50.00 Mph = 10.00 Output-: speed in m/ph is 31.07 speed in km/ph is 16.0934 Start Step 1 -> Declare function to convert km/ph to m/ph double km_mph(double km) return 0.6214 * km step 2 -> Declare function to convert m/ph to km/ph double m_km(double m_ph) return m_ph * 1.60934 step 3 -> In main() declare variable as double kmph = 50 and double mph = 10 print km_mph(kmph) print m_km(mph) Stop #include <bits/stdc++.h> using namespace std; // convert km/ph to m/ph double km_mph(double km){ return 0.6214 * km; } //convert mph to kmph double m_km(double m_ph){ return m_ph * 1.60934; } int main(){ double kmph = 50.00; double mph = 10.00; cout << "speed in m/ph is " << km_mph(kmph) << endl; cout << "speed in km/ph is " << m_km(mph); return 0; } speed in m/ph is 31.07 speed in km/ph is 16.0934
[ { "code": null, "e": 1215, "s": 1062, "text": "If input is in km/hr convert it to miles/hr else input will be in miles/hr convert it to km/hr. There are formulas that can be used for this conversion." }, { "code": null, "e": 1237, "s": 1215, "text": "Conversion Formulas −" }, { "code": null, "e": 1296, "s": 1237, "text": "1 kilo-metre = 0.621371 miles\n1 miles = 1.60934 Kilo-meter" }, { "code": null, "e": 1392, "s": 1296, "text": "Input-: kmph= 50.00\n Mph = 10.00\nOutput-: speed in m/ph is 31.07\n speed in km/ph is 16.0934" }, { "code": null, "e": 1737, "s": 1392, "text": "Start\nStep 1 -> Declare function to convert km/ph to m/ph\n double km_mph(double km)\n return 0.6214 * km\nstep 2 -> Declare function to convert m/ph to km/ph\n double m_km(double m_ph)\n return m_ph * 1.60934\nstep 3 -> In main()\n declare variable as double kmph = 50 and double mph = 10\n print km_mph(kmph)\n print m_km(mph)\nStop" }, { "code": null, "e": 2111, "s": 1737, "text": "#include <bits/stdc++.h>\nusing namespace std;\n// convert km/ph to m/ph\ndouble km_mph(double km){\n return 0.6214 * km;\n}\n//convert mph to kmph\ndouble m_km(double m_ph){\n return m_ph * 1.60934;\n}\nint main(){\n double kmph = 50.00;\n double mph = 10.00;\n cout << \"speed in m/ph is \" << km_mph(kmph) << endl;\n cout << \"speed in km/ph is \" << m_km(mph);\n return 0;\n}" }, { "code": null, "e": 2160, "s": 2111, "text": "speed in m/ph is 31.07\nspeed in km/ph is 16.0934" } ]
NP complete problems - GeeksQuiz
06 May, 2017 1. The problem of determining whether there exists a cycle in an undirected graph is in P. 2. The problem of determining whether there exists a cycle in an undirected graph is in NP. 3. If a problem A is NP-Complete, there exists a non-deterministic polynomial time algorithm to solve A. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Program for Breadth First Search or BFS for a Graph Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies How to calculate MOVING AVERAGE in a Pandas DataFrame? What is "network ID" and "host ID" in IP Addresses? What is Transmission Control Protocol (TCP)? How to Calculate Number of Host in a Subnet? Bash Scripting - How to check If File Exists Python Raise Keyword Python OpenCV - Canny() Function
[ { "code": null, "e": 35737, "s": 35709, "text": "\n06 May, 2017" }, { "code": null, "e": 36036, "s": 35737, "text": "1. The problem of determining whether there exists\n a cycle in an undirected graph is in P.\n2. The problem of determining whether there exists\n a cycle in an undirected graph is in NP.\n3. If a problem A is NP-Complete, there exists a \n non-deterministic polynomial time algorithm to solve A. " }, { "code": null, "e": 36134, "s": 36036, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 36193, "s": 36134, "text": "Python Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 36225, "s": 36193, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 36278, "s": 36225, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 36333, "s": 36278, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 36385, "s": 36333, "text": "What is \"network ID\" and \"host ID\" in IP Addresses?" }, { "code": null, "e": 36430, "s": 36385, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 36475, "s": 36430, "text": "How to Calculate Number of Host in a Subnet?" }, { "code": null, "e": 36520, "s": 36475, "text": "Bash Scripting - How to check If File Exists" }, { "code": null, "e": 36541, "s": 36520, "text": "Python Raise Keyword" } ]
Python | Convert two lists into a dictionary - GeeksforGeeks
28 Nov, 2018 Interconversion between data types are usually necessary in real time applications as certain systems have certain modules which require the input in a particular data-type. Let’s discuss a simple yet useful utility of conversion of two lists into a key:value pair dictionary. Method #1 : Naive MethodThe basic method that can be applied to perform this task is the brute force method to achieve this. For this, simply declare a dictionary, and then run nested loop for both the lists and assign key and value pairs to from list values to dictionary. # Python3 code to demonstrate # conversion of lists to dictionary# using naive method # initializing liststest_keys = ["Rash", "Kil", "Varsha"]test_values = [1, 4, 5] # Printing original keys-value listsprint ("Original key list is : " + str(test_keys))print ("Original value list is : " + str(test_values)) # using naive method# to convert lists to dictionaryres = {}for key in test_keys: for value in test_values: res[key] = value test_values.remove(value) break # Printing resultant dictionary print ("Resultant dictionary is : " + str(res)) Original key list is : ['Rash', 'Kil', 'Varsha'] Original value list is : [1, 4, 5] Resultant dictionary is : {'Varsha': 5, 'Rash': 1, 'Kil': 4} Method #2 : Using dictionary comprehensionThe more concise way to achieve the above method, dictionary comprehension method offers the faster and time-saving approach by reducing the lines to type. # Python3 code to demonstrate # conversion of lists to dictionary# using dictionary comprehension # initializing liststest_keys = ["Rash", "Kil", "Varsha"]test_values = [1, 4, 5] # Printing original keys-value listsprint ("Original key list is : " + str(test_keys))print ("Original value list is : " + str(test_values)) # using dictionary comprehension# to convert lists to dictionaryres = {test_keys[i]: test_values[i] for i in range(len(test_keys))} # Printing resultant dictionary print ("Resultant dictionary is : " + str(res)) Original key list is : ['Rash', 'Kil', 'Varsha'] Original value list is : [1, 4, 5] Resultant dictionary is : {'Varsha': 5, 'Kil': 4, 'Rash': 1} Method #3 : Using zip()Most pythonic and generic method to perform this very task is by using zip(). This function pairs the list element with other list element at corresponding index in form of key-value pairs. # Python3 code to demonstrate # conversion of lists to dictionary# using zip() # initializing liststest_keys = ["Rash", "Kil", "Varsha"]test_values = [1, 4, 5] # Printing original keys-value listsprint ("Original key list is : " + str(test_keys))print ("Original value list is : " + str(test_values)) # using zip()# to convert lists to dictionaryres = dict(zip(test_keys, test_values)) # Printing resultant dictionary print ("Resultant dictionary is : " + str(res)) Original key list is : ['Rash', 'Kil', 'Varsha'] Original value list is : [1, 4, 5] Resultant dictionary is : {'Kil': 4, 'Rash': 1, 'Varsha': 5} Python dictionary-programs python-dict python-list Python python-dict python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists How To Convert Python Dictionary To JSON? Check if element exists in list in Python Convert integer to string in Python
[ { "code": null, "e": 25518, "s": 25490, "text": "\n28 Nov, 2018" }, { "code": null, "e": 25795, "s": 25518, "text": "Interconversion between data types are usually necessary in real time applications as certain systems have certain modules which require the input in a particular data-type. Let’s discuss a simple yet useful utility of conversion of two lists into a key:value pair dictionary." }, { "code": null, "e": 26069, "s": 25795, "text": "Method #1 : Naive MethodThe basic method that can be applied to perform this task is the brute force method to achieve this. For this, simply declare a dictionary, and then run nested loop for both the lists and assign key and value pairs to from list values to dictionary." }, { "code": "# Python3 code to demonstrate # conversion of lists to dictionary# using naive method # initializing liststest_keys = [\"Rash\", \"Kil\", \"Varsha\"]test_values = [1, 4, 5] # Printing original keys-value listsprint (\"Original key list is : \" + str(test_keys))print (\"Original value list is : \" + str(test_values)) # using naive method# to convert lists to dictionaryres = {}for key in test_keys: for value in test_values: res[key] = value test_values.remove(value) break # Printing resultant dictionary print (\"Resultant dictionary is : \" + str(res))", "e": 26645, "s": 26069, "text": null }, { "code": null, "e": 26791, "s": 26645, "text": "Original key list is : ['Rash', 'Kil', 'Varsha']\nOriginal value list is : [1, 4, 5]\nResultant dictionary is : {'Varsha': 5, 'Rash': 1, 'Kil': 4}\n" }, { "code": null, "e": 26990, "s": 26791, "text": " Method #2 : Using dictionary comprehensionThe more concise way to achieve the above method, dictionary comprehension method offers the faster and time-saving approach by reducing the lines to type." }, { "code": "# Python3 code to demonstrate # conversion of lists to dictionary# using dictionary comprehension # initializing liststest_keys = [\"Rash\", \"Kil\", \"Varsha\"]test_values = [1, 4, 5] # Printing original keys-value listsprint (\"Original key list is : \" + str(test_keys))print (\"Original value list is : \" + str(test_values)) # using dictionary comprehension# to convert lists to dictionaryres = {test_keys[i]: test_values[i] for i in range(len(test_keys))} # Printing resultant dictionary print (\"Resultant dictionary is : \" + str(res))", "e": 27527, "s": 26990, "text": null }, { "code": null, "e": 27673, "s": 27527, "text": "Original key list is : ['Rash', 'Kil', 'Varsha']\nOriginal value list is : [1, 4, 5]\nResultant dictionary is : {'Varsha': 5, 'Kil': 4, 'Rash': 1}\n" }, { "code": null, "e": 27887, "s": 27673, "text": " Method #3 : Using zip()Most pythonic and generic method to perform this very task is by using zip(). This function pairs the list element with other list element at corresponding index in form of key-value pairs." }, { "code": "# Python3 code to demonstrate # conversion of lists to dictionary# using zip() # initializing liststest_keys = [\"Rash\", \"Kil\", \"Varsha\"]test_values = [1, 4, 5] # Printing original keys-value listsprint (\"Original key list is : \" + str(test_keys))print (\"Original value list is : \" + str(test_values)) # using zip()# to convert lists to dictionaryres = dict(zip(test_keys, test_values)) # Printing resultant dictionary print (\"Resultant dictionary is : \" + str(res))", "e": 28358, "s": 27887, "text": null }, { "code": null, "e": 28504, "s": 28358, "text": "Original key list is : ['Rash', 'Kil', 'Varsha']\nOriginal value list is : [1, 4, 5]\nResultant dictionary is : {'Kil': 4, 'Rash': 1, 'Varsha': 5}\n" }, { "code": null, "e": 28531, "s": 28504, "text": "Python dictionary-programs" }, { "code": null, "e": 28543, "s": 28531, "text": "python-dict" }, { "code": null, "e": 28555, "s": 28543, "text": "python-list" }, { "code": null, "e": 28562, "s": 28555, "text": "Python" }, { "code": null, "e": 28574, "s": 28562, "text": "python-dict" }, { "code": null, "e": 28586, "s": 28574, "text": "python-list" }, { "code": null, "e": 28684, "s": 28586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28716, "s": 28684, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28738, "s": 28716, "text": "Enumerate() in Python" }, { "code": null, "e": 28780, "s": 28738, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28806, "s": 28780, "text": "Python String | replace()" }, { "code": null, "e": 28835, "s": 28806, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28879, "s": 28835, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28916, "s": 28879, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28958, "s": 28916, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29000, "s": 28958, "text": "Check if element exists in list in Python" } ]
list insert() in C++ STL - GeeksforGeeks
24 Oct, 2018 The list::insert() is used to insert the elements at any position of list. This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1. Syntax: insert(pos_iter, ele_num, ele) Parameters: This function takes in three parameters: pos_iter: Position in the container where the new elements are inserted. ele_num: Number of elements to insert. Each element is initialized to a copy of val. ele: Value to be copied (or moved) to the inserted elements. Return Value: This function returns an iterator that points to the first of the newly inserted elements. // C++ code to demonstrate the working of// insert() function #include <iostream>#include <list> // for list operationsusing namespace std; int main(){ // declaring list list<int> list1; // using assign() to insert multiple numbers // creates 3 occurrences of "2" list1.assign(3, 2); // initializing list iterator to beginning list<int>::iterator it = list1.begin(); // iterator to point to 3rd position advance(it, 2); // using insert to insert 1 element at the 3rd position // inserts 5 at 3rd position list1.insert(it, 5); // Printing the new list cout << "The list after inserting" << " 1 element using insert() is : "; for (list<int>::iterator i = list1.begin(); i != list1.end(); i++) cout << *i << " "; cout << endl; // using insert to insert // 2 element at the 4th position // inserts 2 occurrences // of 7 at 4th position list1.insert(it, 2, 7); // Printing the new list cout << "The list after inserting" << " multiple elements " << "using insert() is : "; for (list<int>::iterator i = list1.begin(); i != list1.end(); i++) cout << *i << " "; cout << endl;} The list after inserting 1 element using insert() is : 2 2 5 2 The list after inserting multiple elements using insert() is : 2 2 5 7 7 2 CPP-Functions cpp-list Picked C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Virtual Function in C++ Templates in C++ with Examples Constructors in C++ Operator Overloading in C++ Socket Programming in C/C++ Object Oriented Programming in C++ Copy Constructor in C++ Polymorphism in C++
[ { "code": null, "e": 25697, "s": 25669, "text": "\n24 Oct, 2018" }, { "code": null, "e": 25922, "s": 25697, "text": "The list::insert() is used to insert the elements at any position of list. This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1." }, { "code": null, "e": 25930, "s": 25922, "text": "Syntax:" }, { "code": null, "e": 25962, "s": 25930, "text": "insert(pos_iter, ele_num, ele)\n" }, { "code": null, "e": 26015, "s": 25962, "text": "Parameters: This function takes in three parameters:" }, { "code": null, "e": 26088, "s": 26015, "text": "pos_iter: Position in the container where the new elements are inserted." }, { "code": null, "e": 26173, "s": 26088, "text": "ele_num: Number of elements to insert. Each element is initialized to a copy of val." }, { "code": null, "e": 26234, "s": 26173, "text": "ele: Value to be copied (or moved) to the inserted elements." }, { "code": null, "e": 26339, "s": 26234, "text": "Return Value: This function returns an iterator that points to the first of the newly inserted elements." }, { "code": "// C++ code to demonstrate the working of// insert() function #include <iostream>#include <list> // for list operationsusing namespace std; int main(){ // declaring list list<int> list1; // using assign() to insert multiple numbers // creates 3 occurrences of \"2\" list1.assign(3, 2); // initializing list iterator to beginning list<int>::iterator it = list1.begin(); // iterator to point to 3rd position advance(it, 2); // using insert to insert 1 element at the 3rd position // inserts 5 at 3rd position list1.insert(it, 5); // Printing the new list cout << \"The list after inserting\" << \" 1 element using insert() is : \"; for (list<int>::iterator i = list1.begin(); i != list1.end(); i++) cout << *i << \" \"; cout << endl; // using insert to insert // 2 element at the 4th position // inserts 2 occurrences // of 7 at 4th position list1.insert(it, 2, 7); // Printing the new list cout << \"The list after inserting\" << \" multiple elements \" << \"using insert() is : \"; for (list<int>::iterator i = list1.begin(); i != list1.end(); i++) cout << *i << \" \"; cout << endl;}", "e": 27575, "s": 26339, "text": null }, { "code": null, "e": 27715, "s": 27575, "text": "The list after inserting 1 element using insert() is : 2 2 5 2 \nThe list after inserting multiple elements using insert() is : 2 2 5 7 7 2\n" }, { "code": null, "e": 27729, "s": 27715, "text": "CPP-Functions" }, { "code": null, "e": 27738, "s": 27729, "text": "cpp-list" }, { "code": null, "e": 27745, "s": 27738, "text": "Picked" }, { "code": null, "e": 27749, "s": 27745, "text": "C++" }, { "code": null, "e": 27753, "s": 27749, "text": "CPP" }, { "code": null, "e": 27851, "s": 27753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27870, "s": 27851, "text": "Inheritance in C++" }, { "code": null, "e": 27894, "s": 27870, "text": "C++ Classes and Objects" }, { "code": null, "e": 27918, "s": 27894, "text": "Virtual Function in C++" }, { "code": null, "e": 27949, "s": 27918, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27969, "s": 27949, "text": "Constructors in C++" }, { "code": null, "e": 27997, "s": 27969, "text": "Operator Overloading in C++" }, { "code": null, "e": 28025, "s": 27997, "text": "Socket Programming in C/C++" }, { "code": null, "e": 28060, "s": 28025, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 28084, "s": 28060, "text": "Copy Constructor in C++" } ]
Python | Check if list contains consecutive numbers - GeeksforGeeks
19 Mar, 2019 Given a list of numbers, write a Python program to check if the list contains consecutive integers. Examples: Input : [2, 3, 1, 4, 5] Output : True Input : [1, 2, 3, 5, 6] Output : False Let’s discuss the few ways we can do this task. Approach #1 : using sorted() This approach uses sorted() function of Python. We compare the sorted list with list of range of minimum and maximum integer of the list and return it. # Python3 Program to Create list # with integers within given range def checkConsecutive(l): return sorted(l) == list(range(min(l), max(l)+1)) # Driver Codelst = [2, 3, 1, 4, 5]print(checkConsecutive(lst)) True Approach #2 : Using numpy.diff() Numpy module provides a function diff() that calculate the n-th discrete difference along the given axis. We find the iterative difference of the sorted list and check if it is equal to 1. # Python3 Program to Create list # with integers within given range import numpy as np def checkConsecutive(l): n = len(l) - 1 return (sum(np.diff(sorted(l)) == 1) >= n) # Driver Codelst = [2, 3, 1, 4, 5]print(checkConsecutive(lst)) True 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 Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26111, "s": 26083, "text": "\n19 Mar, 2019" }, { "code": null, "e": 26211, "s": 26111, "text": "Given a list of numbers, write a Python program to check if the list contains consecutive integers." }, { "code": null, "e": 26221, "s": 26211, "text": "Examples:" }, { "code": null, "e": 26300, "s": 26221, "text": "Input : [2, 3, 1, 4, 5]\nOutput : True\n\nInput : [1, 2, 3, 5, 6]\nOutput : False\n" }, { "code": null, "e": 26377, "s": 26300, "text": "Let’s discuss the few ways we can do this task. Approach #1 : using sorted()" }, { "code": null, "e": 26529, "s": 26377, "text": "This approach uses sorted() function of Python. We compare the sorted list with list of range of minimum and maximum integer of the list and return it." }, { "code": "# Python3 Program to Create list # with integers within given range def checkConsecutive(l): return sorted(l) == list(range(min(l), max(l)+1)) # Driver Codelst = [2, 3, 1, 4, 5]print(checkConsecutive(lst))", "e": 26745, "s": 26529, "text": null }, { "code": null, "e": 26751, "s": 26745, "text": "True\n" }, { "code": null, "e": 26785, "s": 26751, "text": " Approach #2 : Using numpy.diff()" }, { "code": null, "e": 26974, "s": 26785, "text": "Numpy module provides a function diff() that calculate the n-th discrete difference along the given axis. We find the iterative difference of the sorted list and check if it is equal to 1." }, { "code": "# Python3 Program to Create list # with integers within given range import numpy as np def checkConsecutive(l): n = len(l) - 1 return (sum(np.diff(sorted(l)) == 1) >= n) # Driver Codelst = [2, 3, 1, 4, 5]print(checkConsecutive(lst))", "e": 27220, "s": 26974, "text": null }, { "code": null, "e": 27226, "s": 27220, "text": "True\n" }, { "code": null, "e": 27247, "s": 27226, "text": "Python list-programs" }, { "code": null, "e": 27259, "s": 27247, "text": "python-list" }, { "code": null, "e": 27266, "s": 27259, "text": "Python" }, { "code": null, "e": 27282, "s": 27266, "text": "Python Programs" }, { "code": null, "e": 27294, "s": 27282, "text": "python-list" }, { "code": null, "e": 27392, "s": 27294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27410, "s": 27392, "text": "Python Dictionary" }, { "code": null, "e": 27445, "s": 27410, "text": "Read a file line by line in Python" }, { "code": null, "e": 27477, "s": 27445, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27499, "s": 27477, "text": "Enumerate() in Python" }, { "code": null, "e": 27541, "s": 27499, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27584, "s": 27541, "text": "Python program to convert a list to string" }, { "code": null, "e": 27606, "s": 27584, "text": "Defaultdict in Python" }, { "code": null, "e": 27645, "s": 27606, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27691, "s": 27645, "text": "Python | Split string into list of characters" } ]
Generate all binary numbers in range [L, R] with same length - GeeksforGeeks
23 Dec, 2021 Given two positive integer numbers L and R. The task is to convert all the numbers from L to R to binary number. The length of all binary numbers should be same. Examples: Input: L = 2, R = 4Output:010011100Explanation: The binary representation of the numbers: 2 = 10, 3 = 11 and 4 = 100.For the numbers to have same length one preceding 0 is added to the binary representation of both 3 and 4. Input: L = 2, R = 8Output:0010001101000101011001111000 Approach: Follow the approach mentioned below to solve the problem. To determine the length of resultant binary numbers, take log of R+1 to the base 2. Then traverse from L to R and convert every number to binary of determined length. Store each number and print it at the end. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ code to implement the approach#include <bits/stdc++.h>using namespace std; // Function to convert a number to binaryvector<int> convertToBinary(int num, int length){ vector<int> bits(length, 0); if (num == 0) { return bits; } int i = length - 1; while (num != 0) { bits[i--] = (num % 2); // Integer division // gives quotient num = num / 2; } return bits;} // Function to convert all numbers// in range [L, R] to binary of// same lengthvector<vector<int> > getAllBinary(int l, int r){ // Length of the binary numbers int n = (int) ceil(log(r+1) / log (2)); vector<vector<int> > binary_nos; for (int i = l; i <= r; i++) { vector<int> bits = convertToBinary(i, n); binary_nos.push_back(bits); } return binary_nos;} // Driver codeint main(){ int L = 2, R = 8; vector<vector<int> > binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.size(); i++) { for (int j = 0; j < binary_nos[i].size(); j++) cout << binary_nos[i][j]; cout << endl; } return 0;} // Java code to implement the approachimport java.util.*;public class GFG{ // Function to convert a number to binary static ArrayList<Integer> convertToBinary(int num, int length) { ArrayList<Integer> bits= new ArrayList<Integer>(); for(int i = 0; i < length; i++) { bits.add(0); } if (num == 0) { return bits; } int i = length - 1; while (num != 0) { bits.set(i, (num % 2)); i = i - 1; // Integer division // gives quotient num = num / 2; } return bits; } // Function to convert all numbers // in range [L, R] to binary of // same length static ArrayList<ArrayList<Integer> > getAllBinary(int l, int r) { // Length of the binary numbers double x = Math.log(r+1); double y = Math.log (2); int n = (int) Math.ceil(x / y); ArrayList<ArrayList<Integer> > binary_nos = new ArrayList<ArrayList<Integer> >(); for (int i = l; i <= r; i++) { ArrayList<Integer> bits = convertToBinary(i, n); binary_nos.add(bits); } return binary_nos; } // Driver code public static void main(String args[]) { int L = 2, R = 8; ArrayList<ArrayList<Integer> > binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.size(); i++) { for (int j = 0; j < binary_nos.get(i).size(); j++) { System.out.print(binary_nos.get(i).get(j)); } System.out.println(); } }} // This code is contributed by Samim Hossain Mondal. # Python 3 code to implement the approachimport math # Function to convert a number to binarydef convertToBinary(num, length): bits = [0]*(length) if (num == 0): return bits i = length - 1 while (num != 0): bits[i] = (num % 2) i -= 1 # Integer division # gives quotient num = num // 2 return bits # Function to convert all numbers# in range [L, R] to binary of# same lengthdef getAllBinary(l, r): # Length of the binary numbers n = int(math.ceil(math.log(r+1)/ math.log(2))) binary_nos = [] for i in range(l, r + 1): bits = convertToBinary(i, n) binary_nos.append(bits) return binary_nos # Driver codeif __name__ == "__main__": L = 2 R = 8 binary_nos = getAllBinary(L, R) for i in range(len(binary_nos)): for j in range(len(binary_nos[i])): print(binary_nos[i][j], end="") print() # This code is contributed by ukasp. // C# code to implement the approachusing System;using System.Collections.Generic;public class GFG{ // Function to convert a number to binary static List<int> convertToBinary(int num, int length) { List<int> bits = new List<int>(); int i; for (i = 0; i < length; i++) { bits.Add(0); } if (num == 0) { return bits; } i = length - 1; while (num != 0) { bits[i] = (num % 2); i = i - 1; // Integer division // gives quotient num = num / 2; } return bits; } // Function to convert all numbers // in range [L, R] to binary of // same length static List<List<int>> getAllBinary(int l, int r) { // Length of the binary numbers double x = Math.Log(r + 1); double y = Math.Log(2); int n = (int)Math.Ceiling(x / y); List<List<int>> binary_nos = new List<List<int>>(); for (int i = l; i <= r; i++) { List<int> bits = convertToBinary(i, n); binary_nos.Add(bits); } return binary_nos; } // Driver code public static void Main() { int L = 2, R = 8; List<List<int>> binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.Count; i++) { for (int j = 0; j < binary_nos[i].Count; j++) { Console.Write(binary_nos[i][j]); } Console.WriteLine(""); } }} // This code is contributed by Saurabh Jaiswal <script> // JavaScript code to implement the approach // Function to convert a number to binary const convertToBinary = (num, length) => { let bits = new Array(length).fill(0); if (num == 0) { return bits; } let i = length - 1; while (num != 0) { bits[i--] = (num % 2); // Integer division // gives quotient num = parseInt(num / 2); } return bits; } // Function to convert all numbers // in range [L, R] to binary of // same length const getAllBinary = (l, r) => { // Length of the binary numbers let n = Math.ceil(Math.log(r + 1) / Math.log(2)); let binary_nos = []; for (let i = l; i <= r; i++) { let bits = convertToBinary(i, n); binary_nos.push(bits); } return binary_nos; } // Driver code let L = 2, R = 8; let binary_nos = getAllBinary(L, R); for (let i = 0; i < binary_nos.length; i++) { for (let j = 0; j < binary_nos[i].length; j++) document.write(binary_nos[i][j]); document.write("<br/>"); } // This code is contributed by rakeshsahni </script> 0010 0011 0100 0101 0110 0111 1000 Time Complexity: O(N * logR) where N = (R – L + 1)Auxiliary Space: O(N * logR) rakeshsahni ukasp samim2000 gfgking binary-representation Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to turn off a particular bit in a number? Set, Clear and Toggle a given bit of a number in C Reverse actual bits of the given number Convert decimal fraction to binary number Count inversions in an array | Set 3 (Using BIT) 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) Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26253, "s": 26225, "text": "\n23 Dec, 2021" }, { "code": null, "e": 26415, "s": 26253, "text": "Given two positive integer numbers L and R. The task is to convert all the numbers from L to R to binary number. The length of all binary numbers should be same." }, { "code": null, "e": 26425, "s": 26415, "text": "Examples:" }, { "code": null, "e": 26649, "s": 26425, "text": "Input: L = 2, R = 4Output:010011100Explanation: The binary representation of the numbers: 2 = 10, 3 = 11 and 4 = 100.For the numbers to have same length one preceding 0 is added to the binary representation of both 3 and 4." }, { "code": null, "e": 26704, "s": 26649, "text": "Input: L = 2, R = 8Output:0010001101000101011001111000" }, { "code": null, "e": 26772, "s": 26704, "text": "Approach: Follow the approach mentioned below to solve the problem." }, { "code": null, "e": 26856, "s": 26772, "text": "To determine the length of resultant binary numbers, take log of R+1 to the base 2." }, { "code": null, "e": 26939, "s": 26856, "text": "Then traverse from L to R and convert every number to binary of determined length." }, { "code": null, "e": 26982, "s": 26939, "text": "Store each number and print it at the end." }, { "code": null, "e": 27032, "s": 26982, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 27036, "s": 27032, "text": "C++" }, { "code": null, "e": 27041, "s": 27036, "text": "Java" }, { "code": null, "e": 27049, "s": 27041, "text": "Python3" }, { "code": null, "e": 27052, "s": 27049, "text": "C#" }, { "code": null, "e": 27063, "s": 27052, "text": "Javascript" }, { "code": "// C++ code to implement the approach#include <bits/stdc++.h>using namespace std; // Function to convert a number to binaryvector<int> convertToBinary(int num, int length){ vector<int> bits(length, 0); if (num == 0) { return bits; } int i = length - 1; while (num != 0) { bits[i--] = (num % 2); // Integer division // gives quotient num = num / 2; } return bits;} // Function to convert all numbers// in range [L, R] to binary of// same lengthvector<vector<int> > getAllBinary(int l, int r){ // Length of the binary numbers int n = (int) ceil(log(r+1) / log (2)); vector<vector<int> > binary_nos; for (int i = l; i <= r; i++) { vector<int> bits = convertToBinary(i, n); binary_nos.push_back(bits); } return binary_nos;} // Driver codeint main(){ int L = 2, R = 8; vector<vector<int> > binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.size(); i++) { for (int j = 0; j < binary_nos[i].size(); j++) cout << binary_nos[i][j]; cout << endl; } return 0;}", "e": 28257, "s": 27063, "text": null }, { "code": "// Java code to implement the approachimport java.util.*;public class GFG{ // Function to convert a number to binary static ArrayList<Integer> convertToBinary(int num, int length) { ArrayList<Integer> bits= new ArrayList<Integer>(); for(int i = 0; i < length; i++) { bits.add(0); } if (num == 0) { return bits; } int i = length - 1; while (num != 0) { bits.set(i, (num % 2)); i = i - 1; // Integer division // gives quotient num = num / 2; } return bits; } // Function to convert all numbers // in range [L, R] to binary of // same length static ArrayList<ArrayList<Integer> > getAllBinary(int l, int r) { // Length of the binary numbers double x = Math.log(r+1); double y = Math.log (2); int n = (int) Math.ceil(x / y); ArrayList<ArrayList<Integer> > binary_nos = new ArrayList<ArrayList<Integer> >(); for (int i = l; i <= r; i++) { ArrayList<Integer> bits = convertToBinary(i, n); binary_nos.add(bits); } return binary_nos; } // Driver code public static void main(String args[]) { int L = 2, R = 8; ArrayList<ArrayList<Integer> > binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.size(); i++) { for (int j = 0; j < binary_nos.get(i).size(); j++) { System.out.print(binary_nos.get(i).get(j)); } System.out.println(); } }} // This code is contributed by Samim Hossain Mondal.", "e": 29814, "s": 28257, "text": null }, { "code": "# Python 3 code to implement the approachimport math # Function to convert a number to binarydef convertToBinary(num, length): bits = [0]*(length) if (num == 0): return bits i = length - 1 while (num != 0): bits[i] = (num % 2) i -= 1 # Integer division # gives quotient num = num // 2 return bits # Function to convert all numbers# in range [L, R] to binary of# same lengthdef getAllBinary(l, r): # Length of the binary numbers n = int(math.ceil(math.log(r+1)/ math.log(2))) binary_nos = [] for i in range(l, r + 1): bits = convertToBinary(i, n) binary_nos.append(bits) return binary_nos # Driver codeif __name__ == \"__main__\": L = 2 R = 8 binary_nos = getAllBinary(L, R) for i in range(len(binary_nos)): for j in range(len(binary_nos[i])): print(binary_nos[i][j], end=\"\") print() # This code is contributed by ukasp.", "e": 30772, "s": 29814, "text": null }, { "code": "// C# code to implement the approachusing System;using System.Collections.Generic;public class GFG{ // Function to convert a number to binary static List<int> convertToBinary(int num, int length) { List<int> bits = new List<int>(); int i; for (i = 0; i < length; i++) { bits.Add(0); } if (num == 0) { return bits; } i = length - 1; while (num != 0) { bits[i] = (num % 2); i = i - 1; // Integer division // gives quotient num = num / 2; } return bits; } // Function to convert all numbers // in range [L, R] to binary of // same length static List<List<int>> getAllBinary(int l, int r) { // Length of the binary numbers double x = Math.Log(r + 1); double y = Math.Log(2); int n = (int)Math.Ceiling(x / y); List<List<int>> binary_nos = new List<List<int>>(); for (int i = l; i <= r; i++) { List<int> bits = convertToBinary(i, n); binary_nos.Add(bits); } return binary_nos; } // Driver code public static void Main() { int L = 2, R = 8; List<List<int>> binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.Count; i++) { for (int j = 0; j < binary_nos[i].Count; j++) { Console.Write(binary_nos[i][j]); } Console.WriteLine(\"\"); } }} // This code is contributed by Saurabh Jaiswal", "e": 32135, "s": 30772, "text": null }, { "code": "<script> // JavaScript code to implement the approach // Function to convert a number to binary const convertToBinary = (num, length) => { let bits = new Array(length).fill(0); if (num == 0) { return bits; } let i = length - 1; while (num != 0) { bits[i--] = (num % 2); // Integer division // gives quotient num = parseInt(num / 2); } return bits; } // Function to convert all numbers // in range [L, R] to binary of // same length const getAllBinary = (l, r) => { // Length of the binary numbers let n = Math.ceil(Math.log(r + 1) / Math.log(2)); let binary_nos = []; for (let i = l; i <= r; i++) { let bits = convertToBinary(i, n); binary_nos.push(bits); } return binary_nos; } // Driver code let L = 2, R = 8; let binary_nos = getAllBinary(L, R); for (let i = 0; i < binary_nos.length; i++) { for (let j = 0; j < binary_nos[i].length; j++) document.write(binary_nos[i][j]); document.write(\"<br/>\"); } // This code is contributed by rakeshsahni </script>", "e": 33362, "s": 32135, "text": null }, { "code": null, "e": 33400, "s": 33365, "text": "0010\n0011\n0100\n0101\n0110\n0111\n1000" }, { "code": null, "e": 33481, "s": 33402, "text": "Time Complexity: O(N * logR) where N = (R – L + 1)Auxiliary Space: O(N * logR)" }, { "code": null, "e": 33495, "s": 33483, "text": "rakeshsahni" }, { "code": null, "e": 33501, "s": 33495, "text": "ukasp" }, { "code": null, "e": 33511, "s": 33501, "text": "samim2000" }, { "code": null, "e": 33519, "s": 33511, "text": "gfgking" }, { "code": null, "e": 33541, "s": 33519, "text": "binary-representation" }, { "code": null, "e": 33551, "s": 33541, "text": "Bit Magic" }, { "code": null, "e": 33564, "s": 33551, "text": "Mathematical" }, { "code": null, "e": 33577, "s": 33564, "text": "Mathematical" }, { "code": null, "e": 33587, "s": 33577, "text": "Bit Magic" }, { "code": null, "e": 33685, "s": 33587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33731, "s": 33685, "text": "How to turn off a particular bit in a number?" }, { "code": null, "e": 33782, "s": 33731, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 33822, "s": 33782, "text": "Reverse actual bits of the given number" }, { "code": null, "e": 33864, "s": 33822, "text": "Convert decimal fraction to binary number" }, { "code": null, "e": 33913, "s": 33864, "text": "Count inversions in an array | Set 3 (Using BIT)" }, { "code": null, "e": 33943, "s": 33913, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34003, "s": 33943, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34018, "s": 34003, "text": "C++ Data Types" }, { "code": null, "e": 34061, "s": 34018, "text": "Set in C++ Standard Template Library (STL)" } ]
How to block comments in YAML ? - GeeksforGeeks
11 Jun, 2020 YAML is a human-friendly data serialization standard for all programming languages. It is commonly used for configuration files and in applications where data is being stored or transmitted. The Normal Way for commenting in YAML is Inline commenting with the “#” symbol, however, if you want to comment blocks then we have a list of ways in which it can be done. Step 1: Select the blockStep 2: Press cmd plus / on Mac or press ctrl plus / on Linux & Windows. Note: This method works on the following editors – Sublime Text Editor Atom Editor Eclipse (with YEdit plugin) JetBrains IDEs: RubyMine and Gogland Visual Studio Code At any level of the code, you may add a new block text named like “Description” or “Comment” or “Notes” or whatever that you wish Example: Instead of # This comment # is too long use Description: > This comment is too long or Comment: > This comment is also too long and newlines survive from parsing! Advantages: If the comments become too large and too complex and have a lot of repeating pattern, you may want to promote them from plain text blocks to objects. Your app may need to read/update the comments in the future. This method is very handy especially if anyone wants these comments to appear in JSON or XML if one is to transform from YAML to these two. Picked Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript How to create footer to stay at the bottom of a Web page? Remove elements from a JavaScript Array How to apply style to parent if it has child with CSS? How to Open URL in New Tab using JavaScript ? How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 25447, "s": 25419, "text": "\n11 Jun, 2020" }, { "code": null, "e": 25638, "s": 25447, "text": "YAML is a human-friendly data serialization standard for all programming languages. It is commonly used for configuration files and in applications where data is being stored or transmitted." }, { "code": null, "e": 25810, "s": 25638, "text": "The Normal Way for commenting in YAML is Inline commenting with the “#” symbol, however, if you want to comment blocks then we have a list of ways in which it can be done." }, { "code": null, "e": 25907, "s": 25810, "text": "Step 1: Select the blockStep 2: Press cmd plus / on Mac or press ctrl plus / on Linux & Windows." }, { "code": null, "e": 25958, "s": 25907, "text": "Note: This method works on the following editors –" }, { "code": null, "e": 25978, "s": 25958, "text": "Sublime Text Editor" }, { "code": null, "e": 25990, "s": 25978, "text": "Atom Editor" }, { "code": null, "e": 26018, "s": 25990, "text": "Eclipse (with YEdit plugin)" }, { "code": null, "e": 26055, "s": 26018, "text": "JetBrains IDEs: RubyMine and Gogland" }, { "code": null, "e": 26074, "s": 26055, "text": "Visual Studio Code" }, { "code": null, "e": 26204, "s": 26074, "text": "At any level of the code, you may add a new block text named like “Description” or “Comment” or “Notes” or whatever that you wish" }, { "code": null, "e": 26213, "s": 26204, "text": "Example:" }, { "code": null, "e": 26378, "s": 26213, "text": "Instead of\n# This comment\n# is too long\n\nuse\nDescription: >\nThis comment\nis too long\n\nor\nComment: >\nThis comment is also too long\nand newlines survive from parsing!" }, { "code": null, "e": 26390, "s": 26378, "text": "Advantages:" }, { "code": null, "e": 26540, "s": 26390, "text": "If the comments become too large and too complex and have a lot of repeating pattern, you may want to promote them from plain text blocks to objects." }, { "code": null, "e": 26601, "s": 26540, "text": "Your app may need to read/update the comments in the future." }, { "code": null, "e": 26741, "s": 26601, "text": "This method is very handy especially if anyone wants these comments to appear in JSON or XML if one is to transform from YAML to these two." }, { "code": null, "e": 26748, "s": 26741, "text": "Picked" }, { "code": null, "e": 26765, "s": 26748, "text": "Web Technologies" }, { "code": null, "e": 26792, "s": 26765, "text": "Web technologies Questions" }, { "code": null, "e": 26890, "s": 26792, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26930, "s": 26890, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26975, "s": 26930, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27018, "s": 26975, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27079, "s": 27018, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27137, "s": 27079, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27177, "s": 27137, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27232, "s": 27177, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 27278, "s": 27232, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27323, "s": 27278, "text": "How to execute PHP code using command line ?" } ]
Python MongoDB - find_one_and_update Query - GeeksforGeeks
26 May, 2020 The function find_one_and_update() actually finds and updates a MongoDB document. Though default-wise this function returns the document in original form and to return the updated document return_document have to be implemented in the code. Syntax: coll.find_one_and_update(filter, update, options) Parameters: col- collection in MongoDB filter- criteria to find the document which needs to be updated update- The operations which need to be implemented for updating the document options- projection or upsert can be used here projection- a mapping which informs about which fields are included and excluded, it is 1/TRUE for including a field and 0/FALSE for excluding upsert- for inserting a new document if no file is found with the mentioned criteria upsert is TRUE Example 1: Sample Database: from pymongo import MongoClientfrom pymongo import ReturnDocument # Create a pymongo clientclient = MongoClient('localhost', 27017) # Get the database instancedb = client['GFG'] # Create a collectiondoc = db['Student'] print(doc.find_one_and_update({'name':"Raju"}, { '$set': { "Branch" : 'ECE'} }, return_document = ReturnDocument.AFTER)) Output: {‘_id’: 5, ‘name’: ‘Raju’, ‘Roll No’: ‘1005’, ‘Branch’: ‘ECE’} Example 2: from pymongo import MongoClientfrom pymongo import ReturnDocument # Create a pymongo clientclient = MongoClient('localhost', 27017) # Get the database instancedb = client['GFG'] # Create a collectiondoc = db['Student'] print(# Increasing marks of Ravi by 10 doc.find_one_and_update({'name': "Raju"}, { '$set': { "Branch" : 'CSE'} }, projection = { "name" : 1, "Branch" : 1 }, return_document = ReturnDocument.AFTER)) Output: {'_id': 5, 'name': 'Raju', 'Branch': 'CSE'} Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 May, 2020" }, { "code": null, "e": 25778, "s": 25537, "text": "The function find_one_and_update() actually finds and updates a MongoDB document. Though default-wise this function returns the document in original form and to return the updated document return_document have to be implemented in the code." }, { "code": null, "e": 25836, "s": 25778, "text": "Syntax: coll.find_one_and_update(filter, update, options)" }, { "code": null, "e": 25848, "s": 25836, "text": "Parameters:" }, { "code": null, "e": 25875, "s": 25848, "text": "col- collection in MongoDB" }, { "code": null, "e": 25939, "s": 25875, "text": "filter- criteria to find the document which needs to be updated" }, { "code": null, "e": 26017, "s": 25939, "text": "update- The operations which need to be implemented for updating the document" }, { "code": null, "e": 26064, "s": 26017, "text": "options- projection or upsert can be used here" }, { "code": null, "e": 26207, "s": 26064, "text": "projection- a mapping which informs about which fields are included and excluded, it is 1/TRUE for including a field and 0/FALSE for excluding" }, { "code": null, "e": 26307, "s": 26207, "text": "upsert- for inserting a new document if no file is found with the mentioned criteria upsert is TRUE" }, { "code": null, "e": 26318, "s": 26307, "text": "Example 1:" }, { "code": null, "e": 26335, "s": 26318, "text": "Sample Database:" }, { "code": "from pymongo import MongoClientfrom pymongo import ReturnDocument # Create a pymongo clientclient = MongoClient('localhost', 27017) # Get the database instancedb = client['GFG'] # Create a collectiondoc = db['Student'] print(doc.find_one_and_update({'name':\"Raju\"}, { '$set': { \"Branch\" : 'ECE'} }, return_document = ReturnDocument.AFTER))", "e": 26728, "s": 26335, "text": null }, { "code": null, "e": 26736, "s": 26728, "text": "Output:" }, { "code": null, "e": 26799, "s": 26736, "text": "{‘_id’: 5, ‘name’: ‘Raju’, ‘Roll No’: ‘1005’, ‘Branch’: ‘ECE’}" }, { "code": null, "e": 26810, "s": 26799, "text": "Example 2:" }, { "code": "from pymongo import MongoClientfrom pymongo import ReturnDocument # Create a pymongo clientclient = MongoClient('localhost', 27017) # Get the database instancedb = client['GFG'] # Create a collectiondoc = db['Student'] print(# Increasing marks of Ravi by 10 doc.find_one_and_update({'name': \"Raju\"}, { '$set': { \"Branch\" : 'CSE'} }, projection = { \"name\" : 1, \"Branch\" : 1 }, return_document = ReturnDocument.AFTER))", "e": 27305, "s": 26810, "text": null }, { "code": null, "e": 27313, "s": 27305, "text": "Output:" }, { "code": null, "e": 27358, "s": 27313, "text": "{'_id': 5, 'name': 'Raju', 'Branch': 'CSE'}\n" }, { "code": null, "e": 27373, "s": 27358, "text": "Python-mongoDB" }, { "code": null, "e": 27380, "s": 27373, "text": "Python" }, { "code": null, "e": 27478, "s": 27380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27510, "s": 27478, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27552, "s": 27510, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27594, "s": 27552, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27621, "s": 27594, "text": "Python Classes and Objects" }, { "code": null, "e": 27677, "s": 27621, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27699, "s": 27677, "text": "Defaultdict in Python" }, { "code": null, "e": 27738, "s": 27699, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27769, "s": 27738, "text": "Python | os.path.join() method" }, { "code": null, "e": 27798, "s": 27769, "text": "Create a directory in Python" } ]
Cumulative Frequency and Probability Table in R - GeeksforGeeks
30 May, 2021 In this article, we are going to see how to calculate the cumulative frequency and probability table in R programming language. Table(): Tables in R are used for better organizing and summarizing the categorical variables. The table() method takes the cross-classifying factors belonging in a vector to build a contingency or frequency table of the counts at each combination of values. A contingency table is basically a tabulation of the counts and/or percentages for multiple variables. It excludes the counting of any missing values from the factor variable supplied to the method. The output returned is in the form of a table, where the first column contains the distinct values followed by their respective counts. This method can be used for cross-tabulation and statistical analysis. frequency_table <- table (vec) Cumsum(): The cumulative frequency can be computed by the summation of each frequency value from a frequency distribution table to include the sum of its predecessors. The last value of this table will be equivalent to the total for all observations. The cumulative frequency table can be calculated by the frequency table, using the cumsum() method. This method returns a vector whose corresponding elements are the cumulative sums. cumsum ( frequency_table) Example 1: Here we are going to create a frequency table. R set.seed(1)vec <- sample(c("Geeks", "CSE", "R", "Python"), 50 , replace = TRUE) # generating frequency tabledata <- table(vec) # frequency table print ("Frequency Table")print (data) print ("Cumulative Frequency Table")cumfreq_data <- cumsum(data)print (cumfreq_data) Output: [1] "Frequency Table" vec CSE Geeks Python R 16 16 7 11 [1] "Cumulative Frequency Table" CSE Geeks Python R 16 32 39 50 Example 2: Creating a probability table. The probability table is the fraction of total samples that belong to a particular class. Therefore, it is obtained by the division of frequency table values by the total number of observations, that is the length of the vector. The output is in form of a table, where the first column contains the distinct values followed by their respective probabilities of occurrence. prob_table <- freq_table/number of observations Code: R set.seed(1)vec <- sample(c("Geeks","CSE","R","Python") ,50 , replace = TRUE) # generating frequency tabledata <- table(vec) # frequency table print ("Frequency Table")print (data) print ("Probability Table")prob_data <- data/50print (prob_data) Output: [1] "Frequency Table" vec CSE Geeks Python R 16 16 7 11 [1] "Probability Table" vec CSE Geeks Python R 0.32 0.32 0.14 0.22 Example 3: Creating Cumulative Frequency & Probability Table, All the columns obtained can be merged together to form a data frame where the respective components form columns of the data frame. The data frame column names can also be assigned using the colnames(df) method. R set.seed(1)vec <- sample(c("Geeks","CSE","R","Python") ,50 , replace = TRUE) # generating frequency tabledata <- table(vec) # probabilitynum_obsrv <- 50prob_data <- data/num_obsrv # cumulative frequencycumfreq_data <- cumsum(data)data_frame <- data.frame(data, cumfreq_data,prob_data) colnames(data_frame) <- c("data","frequency", "cumulative_frequency", "data","probability")print (data_frame) Output: data frequency cumulative_frequency data probability CSE CSE 16 16 CSE 0.32 Geeks Geeks 16 32 Geeks 0.32 Python Python 7 39 Python 0.14 R R 11 50 R 0.22 Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming Creating a Data Frame from Vectors in R Programming Replace Specific Characters in String in R
[ { "code": null, "e": 25893, "s": 25865, "text": "\n30 May, 2021" }, { "code": null, "e": 26021, "s": 25893, "text": "In this article, we are going to see how to calculate the cumulative frequency and probability table in R programming language." }, { "code": null, "e": 26686, "s": 26021, "text": "Table(): Tables in R are used for better organizing and summarizing the categorical variables. The table() method takes the cross-classifying factors belonging in a vector to build a contingency or frequency table of the counts at each combination of values. A contingency table is basically a tabulation of the counts and/or percentages for multiple variables. It excludes the counting of any missing values from the factor variable supplied to the method. The output returned is in the form of a table, where the first column contains the distinct values followed by their respective counts. This method can be used for cross-tabulation and statistical analysis." }, { "code": null, "e": 26717, "s": 26686, "text": "frequency_table <- table (vec)" }, { "code": null, "e": 27152, "s": 26717, "text": "Cumsum(): The cumulative frequency can be computed by the summation of each frequency value from a frequency distribution table to include the sum of its predecessors. The last value of this table will be equivalent to the total for all observations. The cumulative frequency table can be calculated by the frequency table, using the cumsum() method. This method returns a vector whose corresponding elements are the cumulative sums. " }, { "code": null, "e": 27178, "s": 27152, "text": "cumsum ( frequency_table)" }, { "code": null, "e": 27236, "s": 27178, "text": "Example 1: Here we are going to create a frequency table." }, { "code": null, "e": 27238, "s": 27236, "text": "R" }, { "code": "set.seed(1)vec <- sample(c(\"Geeks\", \"CSE\", \"R\", \"Python\"), 50 , replace = TRUE) # generating frequency tabledata <- table(vec) # frequency table print (\"Frequency Table\")print (data) print (\"Cumulative Frequency Table\")cumfreq_data <- cumsum(data)print (cumfreq_data)", "e": 27522, "s": 27238, "text": null }, { "code": null, "e": 27530, "s": 27522, "text": "Output:" }, { "code": null, "e": 27698, "s": 27530, "text": "[1] \"Frequency Table\"\nvec\n CSE Geeks Python R\n 16 16 7 11\n[1] \"Cumulative Frequency Table\"\n CSE Geeks Python R\n 16 32 39 50 " }, { "code": null, "e": 27739, "s": 27698, "text": "Example 2: Creating a probability table." }, { "code": null, "e": 28113, "s": 27739, "text": "The probability table is the fraction of total samples that belong to a particular class. Therefore, it is obtained by the division of frequency table values by the total number of observations, that is the length of the vector. The output is in form of a table, where the first column contains the distinct values followed by their respective probabilities of occurrence. " }, { "code": null, "e": 28161, "s": 28113, "text": "prob_table <- freq_table/number of observations" }, { "code": null, "e": 28167, "s": 28161, "text": "Code:" }, { "code": null, "e": 28169, "s": 28167, "text": "R" }, { "code": "set.seed(1)vec <- sample(c(\"Geeks\",\"CSE\",\"R\",\"Python\") ,50 , replace = TRUE) # generating frequency tabledata <- table(vec) # frequency table print (\"Frequency Table\")print (data) print (\"Probability Table\")prob_data <- data/50print (prob_data)", "e": 28430, "s": 28169, "text": null }, { "code": null, "e": 28438, "s": 28430, "text": "Output:" }, { "code": null, "e": 28601, "s": 28438, "text": "[1] \"Frequency Table\"\nvec\n CSE Geeks Python R\n 16 16 7 11\n[1] \"Probability Table\"\nvec\n CSE Geeks Python R\n 0.32 0.32 0.14 0.22 " }, { "code": null, "e": 28663, "s": 28601, "text": "Example 3: Creating Cumulative Frequency & Probability Table," }, { "code": null, "e": 28877, "s": 28663, "text": "All the columns obtained can be merged together to form a data frame where the respective components form columns of the data frame. The data frame column names can also be assigned using the colnames(df) method. " }, { "code": null, "e": 28879, "s": 28877, "text": "R" }, { "code": "set.seed(1)vec <- sample(c(\"Geeks\",\"CSE\",\"R\",\"Python\") ,50 , replace = TRUE) # generating frequency tabledata <- table(vec) # probabilitynum_obsrv <- 50prob_data <- data/num_obsrv # cumulative frequencycumfreq_data <- cumsum(data)data_frame <- data.frame(data, cumfreq_data,prob_data) colnames(data_frame) <- c(\"data\",\"frequency\", \"cumulative_frequency\", \"data\",\"probability\")print (data_frame)", "e": 29341, "s": 28879, "text": null }, { "code": null, "e": 29349, "s": 29341, "text": "Output:" }, { "code": null, "e": 29669, "s": 29349, "text": " data frequency cumulative_frequency data probability\nCSE CSE 16 16 CSE 0.32\nGeeks Geeks 16 32 Geeks 0.32\nPython Python 7 39 Python 0.14\nR R 11 50 R 0.22" }, { "code": null, "e": 29676, "s": 29669, "text": "Picked" }, { "code": null, "e": 29687, "s": 29676, "text": "R Language" }, { "code": null, "e": 29785, "s": 29687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29837, "s": 29785, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 29869, "s": 29837, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 29921, "s": 29869, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29965, "s": 29921, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 30000, "s": 29965, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30038, "s": 30000, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30096, "s": 30038, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30132, "s": 30096, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 30184, "s": 30132, "text": "Creating a Data Frame from Vectors in R Programming" } ]
Microsoft Azure - Working with PowerShell in Cosmos DB - GeeksforGeeks
26 Jan, 2021 Azure Cosmos DB is a fully managed NoSQL database for build applications designed by Microsoft. It is highly responsive, scalable, and fully automated. Azure Cloud Shell is an in-browser terminal used to manage cloud instances in Azure. The PowerShell is an application used for the same purpose but is installed locally. In this article, we will look into Azure Cosmos DB with PowerShell where we will create a new Cosmos DB account, a database, and a container with PowerShell. Here we’ll use the Azure Cloud Shell, and you can also use a local installation of PowerShell.Some of the operations that you can perform using PowerShell in Cosmos DB are listed below: Create a Cosmos DB database Update Cosmos DB database Delete Cosmos DB database To create a Cosmos DB database with Powershell/ Cloud Shell follow the below steps: Step 1: Before we can start, we need to install the Cosmos DB PowerShell module like with the below command: Install-Module -Name Az.CosmosDB At the end of the installation you need to verify again if to install the same as shown below: Step 2: First, to see if it works, we will run the below command to list all Cosmos DB accounts in this resource group: Get-AzCosmosDBAccount -ResourceGroupName "RESOURCE NAME" This will list the accounts as shown below: And we can see that there is one in this resource group. Step 3: Now, let’s create a new Azure Cosmos DB account. This will contain a database that will contain containers with documents in it. This will be an account that uses the SQL API to work with data. This can take a while. At this stage, the Cosmos DB account is created. Step 4: Now we need a database for the account. To do so use the below command: New-AzCosmosDBSqlDatabase It would result in something like below after completion: This creates a database, and it is done. Step 5: Now, we can add a container to the database with the below command: New-AzCosmosDBSqlContainer This will result in the following: You can create multiple containers in a database, and this one would use the Autoscale feature as shown in the above image: $ autoscaleMaxThroughput = 4000 #minimum = 4000 Now let’s go to the Azure portal to look at the result. We are in the Azure Cosmos DB account in the Data Explorer. Here is the database, and under that is the container. It also has autoscale enabled. We’ve used PowerShell to list Azure Cosmos DB accounts and create a new one with a database and autoscale container. Microsoft Advanced Computer Subject Microsoft Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Markov Decision Process Fuzzy Logic | Introduction Q-Learning in Python Principal Component Analysis with Python ML | What is Machine Learning ? OpenCV - Overview Basics of API Testing Using Postman Getting Started with System Design ML | Introduction to Data in Machine Learning
[ { "code": null, "e": 25493, "s": 25465, "text": "\n26 Jan, 2021" }, { "code": null, "e": 25815, "s": 25493, "text": "Azure Cosmos DB is a fully managed NoSQL database for build applications designed by Microsoft. It is highly responsive, scalable, and fully automated. Azure Cloud Shell is an in-browser terminal used to manage cloud instances in Azure. The PowerShell is an application used for the same purpose but is installed locally." }, { "code": null, "e": 26159, "s": 25815, "text": "In this article, we will look into Azure Cosmos DB with PowerShell where we will create a new Cosmos DB account, a database, and a container with PowerShell. Here we’ll use the Azure Cloud Shell, and you can also use a local installation of PowerShell.Some of the operations that you can perform using PowerShell in Cosmos DB are listed below:" }, { "code": null, "e": 26187, "s": 26159, "text": "Create a Cosmos DB database" }, { "code": null, "e": 26213, "s": 26187, "text": "Update Cosmos DB database" }, { "code": null, "e": 26239, "s": 26213, "text": "Delete Cosmos DB database" }, { "code": null, "e": 26323, "s": 26239, "text": "To create a Cosmos DB database with Powershell/ Cloud Shell follow the below steps:" }, { "code": null, "e": 26432, "s": 26323, "text": "Step 1: Before we can start, we need to install the Cosmos DB PowerShell module like with the below command:" }, { "code": null, "e": 26465, "s": 26432, "text": "Install-Module -Name Az.CosmosDB" }, { "code": null, "e": 26560, "s": 26465, "text": "At the end of the installation you need to verify again if to install the same as shown below:" }, { "code": null, "e": 26680, "s": 26560, "text": "Step 2: First, to see if it works, we will run the below command to list all Cosmos DB accounts in this resource group:" }, { "code": null, "e": 26737, "s": 26680, "text": "Get-AzCosmosDBAccount -ResourceGroupName \"RESOURCE NAME\"" }, { "code": null, "e": 26781, "s": 26737, "text": "This will list the accounts as shown below:" }, { "code": null, "e": 26838, "s": 26781, "text": "And we can see that there is one in this resource group." }, { "code": null, "e": 27112, "s": 26838, "text": "Step 3: Now, let’s create a new Azure Cosmos DB account. This will contain a database that will contain containers with documents in it. This will be an account that uses the SQL API to work with data. This can take a while. At this stage, the Cosmos DB account is created." }, { "code": null, "e": 27192, "s": 27112, "text": "Step 4: Now we need a database for the account. To do so use the below command:" }, { "code": null, "e": 27218, "s": 27192, "text": "New-AzCosmosDBSqlDatabase" }, { "code": null, "e": 27276, "s": 27218, "text": "It would result in something like below after completion:" }, { "code": null, "e": 27318, "s": 27276, "text": "This creates a database, and it is done. " }, { "code": null, "e": 27394, "s": 27318, "text": "Step 5: Now, we can add a container to the database with the below command:" }, { "code": null, "e": 27421, "s": 27394, "text": "New-AzCosmosDBSqlContainer" }, { "code": null, "e": 27456, "s": 27421, "text": "This will result in the following:" }, { "code": null, "e": 27581, "s": 27456, "text": " You can create multiple containers in a database, and this one would use the Autoscale feature as shown in the above image:" }, { "code": null, "e": 27629, "s": 27581, "text": "$ autoscaleMaxThroughput = 4000 #minimum = 4000" }, { "code": null, "e": 27800, "s": 27629, "text": "Now let’s go to the Azure portal to look at the result. We are in the Azure Cosmos DB account in the Data Explorer. Here is the database, and under that is the container." }, { "code": null, "e": 27832, "s": 27800, "text": "It also has autoscale enabled. " }, { "code": null, "e": 27949, "s": 27832, "text": "We’ve used PowerShell to list Azure Cosmos DB accounts and create a new one with a database and autoscale container." }, { "code": null, "e": 27959, "s": 27949, "text": "Microsoft" }, { "code": null, "e": 27985, "s": 27959, "text": "Advanced Computer Subject" }, { "code": null, "e": 27995, "s": 27985, "text": "Microsoft" }, { "code": null, "e": 28093, "s": 27995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28137, "s": 28093, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 28161, "s": 28137, "text": "Markov Decision Process" }, { "code": null, "e": 28188, "s": 28161, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 28209, "s": 28188, "text": "Q-Learning in Python" }, { "code": null, "e": 28250, "s": 28209, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 28282, "s": 28250, "text": "ML | What is Machine Learning ?" }, { "code": null, "e": 28300, "s": 28282, "text": "OpenCV - Overview" }, { "code": null, "e": 28336, "s": 28300, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 28371, "s": 28336, "text": "Getting Started with System Design" } ]
Printing brackets in Matrix Chain Multiplication Problem - GeeksforGeeks
23 Dec, 2021 Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication)Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have: (ABC)D = (AB)(CD) = A(BCD) = .... However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then, (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations. Clearly the first parenthesization requires less number of operations.Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain. Input: p[] = {40, 20, 30, 10, 30} Output: Optimal parenthesization is ((A(BC))D) Optimal cost of parenthesization is 26000 There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30. Let the input 4 matrices be A, B, C and D. The minimum number of multiplications are obtained by putting parenthesis in following way (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30 Input: p[] = {10, 20, 30, 40, 30} Output: Optimal parenthesization is (((AB)C)D) Optimal cost of parenthesization is 30000 There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. Let the input 4 matrices be A, B, C and D. The minimum number of multiplications are obtained by putting parenthesis in following way ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30 Input: p[] = {10, 20, 30} Output: Optimal parenthesization is (AB) Optimal cost of parenthesization is 6000 There are only two matrices of dimensions 10x20 and 20x30. So there is only one way to multiply the matrices, cost of which is 10*20*30 This problem is mainly an extension of previous post. In the previous post, we have discussed algorithm for finding optimal cost only. Here we need print parenthesization also. The idea is to store optimal break point for every subexpression (i, j) in a 2D array bracket[n][n]. Once we have bracket array us constructed, we can print parenthesization using below code. // Prints parenthesization in subexpression (i, j) printParenthesis(i, j, bracket[n][n], name) { // If only one matrix left in current segment if (i == j) { print name; name++; return; } print "("; // Recursively put brackets around subexpression // from i to bracket[i][j]. printParenthesis(i, bracket[i][j], bracket, name); // Recursively put brackets around subexpression // from bracket[i][j] + 1 to j. printParenthesis(bracket[i][j]+1, j, bracket, name); print ")"; } Below is the implementation of the above steps. C++ Java C# Javascript // C++ program to print optimal parenthesization// in matrix chain multiplication.#include <bits/stdc++.h>using namespace std; // Function for printing the optimal// parenthesization of a matrix chain productvoid printParenthesis(int i, int j, int n, int* bracket, char& name){ // If only one matrix left in current segment if (i == j) { cout << name++; return; } cout << "("; // Recursively put brackets around subexpression // from i to bracket[i][j]. // Note that "*((bracket+i*n)+j)" is similar to // bracket[i][j] printParenthesis(i, *((bracket + i * n) + j), n, bracket, name); // Recursively put brackets around subexpression // from bracket[i][j] + 1 to j. printParenthesis(*((bracket + i * n) + j) + 1, j, n, bracket, name); cout << ")";} // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n// Please refer below article for details of this// function// https://goo.gl/k6EYKjvoid matrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; // bracket[i][j] stores optimal break point in // subexpression from i to j. int bracket[n][n]; /* m[i,j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (int i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (int L = 2; L < n; L++) { for (int i = 1; i < n - L + 1; i++) { int j = i + L - 1; m[i][j] = INT_MAX; for (int k = i; k <= j - 1; k++) { // q = cost/scalar multiplications int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) { m[i][j] = q; // Each entry bracket[i,j]=k shows // where to split the product arr // i,i+1....j for the minimum cost. bracket[i][j] = k; } } } } // The first matrix is printed as 'A', next as 'B', // and so on char name = 'A'; cout << "Optimal Parenthesization is : "; printParenthesis(1, n - 1, n, (int*)bracket, name); cout << "nOptimal Cost is : " << m[1][n - 1];} // Driver codeint main(){ int arr[] = { 40, 20, 30, 10, 30 }; int n = sizeof(arr) / sizeof(arr[0]); matrixChainOrder(arr, n); return 0;} // Java program to print optimal parenthesization// in matrix chain multiplication.class GFG{ static char name; // Function for printing the optimal // parenthesization of a matrix chain product static void printParenthesis(int i, int j, int n, int[][] bracket) { // If only one matrix left in current segment if (i == j) { System.out.print(name++); return; } System.out.print("("); // Recursively put brackets around subexpression // from i to bracket[i][j]. // Note that "*((bracket+i*n)+j)" is similar to // bracket[i][j] printParenthesis(i, bracket[i][j], n, bracket); // Recursively put brackets around subexpression // from bracket[i][j] + 1 to j. printParenthesis(bracket[i][j] + 1, j, n, bracket); System.out.print(")"); } // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n // Please refer below article for details of this // function // https://goo.gl/k6EYKj static void matrixChainOrder(int p[], int n) { /* * For simplicity of the program, one extra row and one extra column are * allocated in m[][]. 0th row and 0th column of m[][] are not used */ int[][] m = new int[n][n]; // bracket[i][j] stores optimal break point in // subexpression from i to j. int[][] bracket = new int[n][n]; /* * m[i,j] = Minimum number of scalar multiplications needed to compute the * matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (int i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (int L = 2; L < n; L++) { for (int i = 1; i < n - L + 1; i++) { int j = i + L - 1; m[i][j] = Integer.MAX_VALUE; for (int k = i; k <= j - 1; k++) { // q = cost/scalar multiplications int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) { m[i][j] = q; // Each entry bracket[i,j]=k shows // where to split the product arr // i,i+1....j for the minimum cost. bracket[i][j] = k; } } } } // The first matrix is printed as 'A', next as 'B', // and so on name = 'A'; System.out.print("Optimal Parenthesization is : "); printParenthesis(1, n - 1, n, bracket); System.out.print("\nOptimal Cost is : " + m[1][n - 1]); } // Driver code public static void main(String[] args) { int arr[] = { 40, 20, 30, 10, 30 }; int n = arr.length; matrixChainOrder(arr, n); }} // This code is contributed by sanjeev2552 // C# program to print optimal parenthesization// in matrix chain multiplication.using System; class GFG{ static char name; // Function for printing the optimal// parenthesization of a matrix chain productstatic void printParenthesis(int i, int j, int n, int[,] bracket){ // If only one matrix left in current segment if (i == j) { Console.Write(name++); return; } Console.Write("("); // Recursively put brackets around subexpression // from i to bracket[i,j]. // Note that "*((bracket+i*n)+j)" is similar to // bracket[i,j] printParenthesis(i, bracket[i, j], n, bracket); // Recursively put brackets around subexpression // from bracket[i,j] + 1 to j. printParenthesis(bracket[i, j] + 1, j, n, bracket); Console.Write(")");} // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n// Please refer below article for details of this// function// https://goo.gl/k6EYKjstatic void matrixChainOrder(int []p, int n){ /* * For simplicity of the program, one extra row and one extra column are * allocated in m[,]. 0th row and 0th column of m[,] are not used */ int[,] m = new int[n, n]; // bracket[i,j] stores optimal break point in // subexpression from i to j. int[,] bracket = new int[n, n]; /* * m[i,j] = Minimum number of scalar multiplications needed to compute the * matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for(int i = 1; i < n; i++) m[i, i] = 0; // L is chain length. for(int L = 2; L < n; L++) { for(int i = 1; i < n - L + 1; i++) { int j = i + L - 1; m[i, j] = int.MaxValue; for (int k = i; k <= j - 1; k++) { // q = cost/scalar multiplications int q = m[i, k] + m[k + 1, j] + p[i - 1] * p[k] * p[j]; if (q < m[i, j]) { m[i, j] = q; // Each entry bracket[i,j]=k shows // where to split the product arr // i,i+1....j for the minimum cost. bracket[i, j] = k; } } } } // The first matrix is printed as 'A', next as 'B', // and so on name = 'A'; Console.Write("Optimal Parenthesization is : "); printParenthesis(1, n - 1, n, bracket); Console.Write("\nOptimal Cost is : " + m[1, n - 1]);} // Driver codepublic static void Main(String[] args){ int []arr = { 40, 20, 30, 10, 30 }; int n = arr.Length; matrixChainOrder(arr, n);}} // This code is contributed by 29AjayKumar <script>// javascript program to print optimal parenthesization// in matrix chain multiplication. var name=0; // Function for printing the optimal // parenthesization of a matrix chain product function printParenthesis(i , j, n, bracket) { // If only one matrix left in current segment if (i == j) { document.write(name++); return; } document.write("("); // Recursively put brackets around subexpression // from i to bracket[i][j]. // Note that "*((bracket+i*n)+j)" is similar to // bracket[i][j] printParenthesis(i, bracket[i][j], n, bracket); // Recursively put brackets around subexpression // from bracket[i][j] + 1 to j. printParenthesis(bracket[i][j] + 1, j, n, bracket); document.write(")"); } // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n // Please refer below article for details of this // function // https://goo.gl/k6EYKj function matrixChainOrder( p , n) { /* * For simplicity of the program, one extra row and one extra column are * allocated in m. 0th row and 0th column of m are not used */ var m = Array(n).fill(0).map(x => Array(n).fill(0)); // bracket[i][j] stores optimal break point in // subexpression from i to j. var bracket = Array(n).fill(0).map(x => Array(n).fill(0)); /* * m[i,j] = Minimum number of scalar multiplications needed to compute the * matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (var i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (var L = 2; L < n; L++) { for (var i = 1; i < n - L + 1; i++) { var j = i + L - 1; m[i][j] = Number.MAX_VALUE; for (var k = i; k <= j - 1; k++) { // q = cost/scalar multiplications var q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) { m[i][j] = q; // Each entry bracket[i,j]=k shows // where to split the product arr // i,i+1....j for the minimum cost. bracket[i][j] = k; } } } } // The first matrix is printed as 'A', next as 'B', // and so on name = 'A'; document.write("Optimal Parenthesization is : "); printParenthesis(1, n - 1, n, bracket); document.write("\nOptimal Cost is : " + m[1][n - 1]); } // Driver code var arr = [ 40, 20, 30, 10, 30 ]; var n = arr.length; matrixChainOrder(arr, n); // This code is contributed by 29AjayKumar</script> Optimal Parenthesization is : ((A(BC))D)nOptimal Cost is : 26000 Time Complexity: O(n3) Auxiliary Space: O(n2) Another Approach: —————————————— This solution try to solve the problem using Recursion using permutations. Let's take example: {40, 20, 30, 10, 30} n = 5 Let’s divide that into a Matrix [ [40, 20], [20, 30], [30, 10], [10, 30] ] [ A , B , C , D ] it contains 4 matrices i.e. (n - 1) We have 3 combinations to multiply i.e. (n-2) AB or BC or CD 1) Given array of matrices with length M, Loop through M – 1 times 2) Merge consecutive matrices in each loop for (int i = 0; i < M - 1; i++) { int cost = (matrices[i][0] * matrices[i][1] * matrices[i+1][1]); // STEP - 3 // STEP - 4 } 3) Merge the current two matrices into one, and remove merged matrices list from list. If A, B merged, then A, B must be removed from the List and NEW matrix list will be like newMatrices = [ AB, C , D ] We have now 3 matrices, in any loop Loop#1: [ AB, C, D ] Loop#2: [ A, BC, D ] Loop#3 [ A, B, CD ] 4) Repeat: Go to STEP – 1 with newMatrices as input M — recursion 5) Stop recursion, when we get 2 matrices in the list. Matrices are reduced in following way, and cost’s must be retained and summed-up during recursion with previous values of each parent step. [ A, B , C, D ] [(AB), C, D ] [ ((AB)C), D ]--> [ (((AB)C)D) ] - return & sum-up total cost of this step. [ (AB), (CD)] --> [ ((AB)(CD)) ] - return .. ditto.. [ A, (BC), D ] [ (A(BC)), D ]--> [ ((A(BC))D) ] - return [ A, ((BC)D) ]--> [ (A((BC)D)) ] - return [ A, B, (CD) ] [ A, (B(CD)) ]--> [ (A(B(CD))) ] - return [ (AB), (CD) ]--> [ ((AB)(CD)) ] - return .. ditto.. on return i.e. at final step of each recursion, check if this value smaller than of any other. Below is JAVA implementation of above steps. Java import java.util.Arrays; public class MatrixMultiplyCost { static class FinalCost { public String label = ""; public int cost = Integer.MAX_VALUE; } private void optimalCost(int[][] matrices, String[] labels, int prevCost, FinalCost finalCost) { int len = matrices.length; if (len < 2) { finalCost.cost = 0; return; } else if (len == 2) { int cost = prevCost + (matrices[0][0] * matrices[0][1] * matrices[1][1]); // This is where minimal cost has been caught // for whole program if (cost < finalCost.cost) { finalCost.cost = cost; finalCost.label = "(" + labels[0] + labels[1] + ")"; } return; } // recursive Reduce for (int i = 0; i < len - 1; i++) { int j; int[][] newMatrix = new int[len - 1][2]; String[] newLabels = new String[len - 1]; int subIndex = 0; // STEP-1: // - Merge two matrices's into one - in each // loop, you move merge position // - if i = 0 THEN (AB) C D ... // - if i = 1 THEN A (BC) D ... // - if i = 2 THEN A B (CD) ... // - and find the cost of this two matrices // multiplication int cost = (matrices[i][0] * matrices[i][1] * matrices[i + 1][1]); // STEP - 2: // - Build new matrices after merge // - Keep track of the merged labels too for (j = 0; j < i; j++) { newMatrix[subIndex] = matrices[j]; newLabels[subIndex++] = labels[j]; } newMatrix[subIndex][0] = matrices[i][0]; newMatrix[subIndex][1] = matrices[i + 1][1]; newLabels[subIndex++] = "(" + labels[i] + labels[i + 1] + ")"; for (j = i + 2; j < len; j++) { newMatrix[subIndex] = matrices[j]; newLabels[subIndex++] = labels[j]; } optimalCost(newMatrix, newLabels, prevCost + cost, finalCost); } } public FinalCost findOptionalCost(int[] arr) { // STEP -1 : Prepare and convert inout as Matrix int[][] matrices = new int[arr.length - 1][2]; String[] labels = new String[arr.length - 1]; for (int i = 0; i < arr.length - 1; i++) { matrices[i][0] = arr[i]; matrices[i][1] = arr[i + 1]; labels[i] = Character.toString((char)(65 + i)); } printMatrix(matrices); FinalCost finalCost = new FinalCost(); optimalCost(matrices, labels, 0, finalCost); return finalCost; } /** * Driver Code */ public static void main(String[] args) { MatrixMultiplyCost calc = new MatrixMultiplyCost(); // ======= *** TEST CASES **** ============ int[] arr = { 40, 20, 30, 10, 30 }; FinalCost cost = calc.findOptionalCost(arr); System.out.println("Final labels: \n" + cost.label); System.out.println("Final Cost:\n" + cost.cost + "\n"); } /** * Ignore this method * - THIS IS for DISPLAY purpose only */ private static void printMatrix(int[][] matrices) { System.out.print("matrices = \n["); for (int[] row : matrices) { System.out.print(Arrays.toString(row) + " "); } System.out.println("]"); }} // This code is contributed by suvera matrices = [[40, 20] [20, 30] [30, 10] [10, 30] ] Final labels: ((A(BC))D) Final Cost: 26000 This article is contributed by Yasin Zafar. 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. Rishi_Lazy suvera sanjeev2552 29AjayKumar simranarora5sos Amazon matrix-chain-multiplication Dynamic Programming Matrix Amazon Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Overlapping Subproblems Property in Dynamic Programming | DP-1 Tabulation vs Memoization Longest Common Substring | DP-29 Cutting a Rod | DP-13 Optimal Substructure Property in Dynamic Programming | DP-2 Program to find largest element in an array Print a given matrix in spiral form Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 26041, "s": 26013, "text": "\n23 Dec, 2021" }, { "code": null, "e": 26591, "s": 26041, "text": "Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication)Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have: " }, { "code": null, "e": 26625, "s": 26591, "text": "(ABC)D = (AB)(CD) = A(BCD) = ...." }, { "code": null, "e": 26882, "s": 26625, "text": "However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then, " }, { "code": null, "e": 27010, "s": 26882, "text": "(AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations\nA(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations." }, { "code": null, "e": 27332, "s": 27010, "text": "Clearly the first parenthesization requires less number of operations.Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain. " }, { "code": null, "e": 28354, "s": 27332, "text": "Input: p[] = {40, 20, 30, 10, 30} \nOutput: Optimal parenthesization is ((A(BC))D)\n Optimal cost of parenthesization is 26000\nThere are 4 matrices of dimensions 40x20, 20x30, \n30x10 and 10x30. Let the input 4 matrices be A, B, \nC and D. The minimum number of multiplications are \nobtained by putting parenthesis in following way\n(A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30\n\nInput: p[] = {10, 20, 30, 40, 30} \nOutput: Optimal parenthesization is (((AB)C)D)\n Optimal cost of parenthesization is 30000\nThere are 4 matrices of dimensions 10x20, 20x30, \n30x40 and 40x30. Let the input 4 matrices be A, B, \nC and D. The minimum number of multiplications are \nobtained by putting parenthesis in following way\n((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30\n\nInput: p[] = {10, 20, 30} \nOutput: Optimal parenthesization is (AB)\n Optimal cost of parenthesization is 6000\nThere are only two matrices of dimensions 10x20 \nand 20x30. So there is only one way to multiply \nthe matrices, cost of which is 10*20*30" }, { "code": null, "e": 28531, "s": 28354, "text": "This problem is mainly an extension of previous post. In the previous post, we have discussed algorithm for finding optimal cost only. Here we need print parenthesization also." }, { "code": null, "e": 28724, "s": 28531, "text": "The idea is to store optimal break point for every subexpression (i, j) in a 2D array bracket[n][n]. Once we have bracket array us constructed, we can print parenthesization using below code. " }, { "code": null, "e": 29273, "s": 28724, "text": "// Prints parenthesization in subexpression (i, j)\nprintParenthesis(i, j, bracket[n][n], name)\n{\n // If only one matrix left in current segment\n if (i == j)\n {\n print name;\n name++;\n return;\n }\n\n print \"(\";\n\n // Recursively put brackets around subexpression\n // from i to bracket[i][j].\n printParenthesis(i, bracket[i][j], bracket, name);\n\n // Recursively put brackets around subexpression\n // from bracket[i][j] + 1 to j.\n printParenthesis(bracket[i][j]+1, j, bracket, name);\n\n print \")\";\n}" }, { "code": null, "e": 29321, "s": 29273, "text": "Below is the implementation of the above steps." }, { "code": null, "e": 29325, "s": 29321, "text": "C++" }, { "code": null, "e": 29330, "s": 29325, "text": "Java" }, { "code": null, "e": 29333, "s": 29330, "text": "C#" }, { "code": null, "e": 29344, "s": 29333, "text": "Javascript" }, { "code": "// C++ program to print optimal parenthesization// in matrix chain multiplication.#include <bits/stdc++.h>using namespace std; // Function for printing the optimal// parenthesization of a matrix chain productvoid printParenthesis(int i, int j, int n, int* bracket, char& name){ // If only one matrix left in current segment if (i == j) { cout << name++; return; } cout << \"(\"; // Recursively put brackets around subexpression // from i to bracket[i][j]. // Note that \"*((bracket+i*n)+j)\" is similar to // bracket[i][j] printParenthesis(i, *((bracket + i * n) + j), n, bracket, name); // Recursively put brackets around subexpression // from bracket[i][j] + 1 to j. printParenthesis(*((bracket + i * n) + j) + 1, j, n, bracket, name); cout << \")\";} // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n// Please refer below article for details of this// function// https://goo.gl/k6EYKjvoid matrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; // bracket[i][j] stores optimal break point in // subexpression from i to j. int bracket[n][n]; /* m[i,j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (int i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (int L = 2; L < n; L++) { for (int i = 1; i < n - L + 1; i++) { int j = i + L - 1; m[i][j] = INT_MAX; for (int k = i; k <= j - 1; k++) { // q = cost/scalar multiplications int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) { m[i][j] = q; // Each entry bracket[i,j]=k shows // where to split the product arr // i,i+1....j for the minimum cost. bracket[i][j] = k; } } } } // The first matrix is printed as 'A', next as 'B', // and so on char name = 'A'; cout << \"Optimal Parenthesization is : \"; printParenthesis(1, n - 1, n, (int*)bracket, name); cout << \"nOptimal Cost is : \" << m[1][n - 1];} // Driver codeint main(){ int arr[] = { 40, 20, 30, 10, 30 }; int n = sizeof(arr) / sizeof(arr[0]); matrixChainOrder(arr, n); return 0;}", "e": 32028, "s": 29344, "text": null }, { "code": "// Java program to print optimal parenthesization// in matrix chain multiplication.class GFG{ static char name; // Function for printing the optimal // parenthesization of a matrix chain product static void printParenthesis(int i, int j, int n, int[][] bracket) { // If only one matrix left in current segment if (i == j) { System.out.print(name++); return; } System.out.print(\"(\"); // Recursively put brackets around subexpression // from i to bracket[i][j]. // Note that \"*((bracket+i*n)+j)\" is similar to // bracket[i][j] printParenthesis(i, bracket[i][j], n, bracket); // Recursively put brackets around subexpression // from bracket[i][j] + 1 to j. printParenthesis(bracket[i][j] + 1, j, n, bracket); System.out.print(\")\"); } // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n // Please refer below article for details of this // function // https://goo.gl/k6EYKj static void matrixChainOrder(int p[], int n) { /* * For simplicity of the program, one extra row and one extra column are * allocated in m[][]. 0th row and 0th column of m[][] are not used */ int[][] m = new int[n][n]; // bracket[i][j] stores optimal break point in // subexpression from i to j. int[][] bracket = new int[n][n]; /* * m[i,j] = Minimum number of scalar multiplications needed to compute the * matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (int i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (int L = 2; L < n; L++) { for (int i = 1; i < n - L + 1; i++) { int j = i + L - 1; m[i][j] = Integer.MAX_VALUE; for (int k = i; k <= j - 1; k++) { // q = cost/scalar multiplications int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) { m[i][j] = q; // Each entry bracket[i,j]=k shows // where to split the product arr // i,i+1....j for the minimum cost. bracket[i][j] = k; } } } } // The first matrix is printed as 'A', next as 'B', // and so on name = 'A'; System.out.print(\"Optimal Parenthesization is : \"); printParenthesis(1, n - 1, n, bracket); System.out.print(\"\\nOptimal Cost is : \" + m[1][n - 1]); } // Driver code public static void main(String[] args) { int arr[] = { 40, 20, 30, 10, 30 }; int n = arr.length; matrixChainOrder(arr, n); }} // This code is contributed by sanjeev2552", "e": 34722, "s": 32028, "text": null }, { "code": "// C# program to print optimal parenthesization// in matrix chain multiplication.using System; class GFG{ static char name; // Function for printing the optimal// parenthesization of a matrix chain productstatic void printParenthesis(int i, int j, int n, int[,] bracket){ // If only one matrix left in current segment if (i == j) { Console.Write(name++); return; } Console.Write(\"(\"); // Recursively put brackets around subexpression // from i to bracket[i,j]. // Note that \"*((bracket+i*n)+j)\" is similar to // bracket[i,j] printParenthesis(i, bracket[i, j], n, bracket); // Recursively put brackets around subexpression // from bracket[i,j] + 1 to j. printParenthesis(bracket[i, j] + 1, j, n, bracket); Console.Write(\")\");} // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n// Please refer below article for details of this// function// https://goo.gl/k6EYKjstatic void matrixChainOrder(int []p, int n){ /* * For simplicity of the program, one extra row and one extra column are * allocated in m[,]. 0th row and 0th column of m[,] are not used */ int[,] m = new int[n, n]; // bracket[i,j] stores optimal break point in // subexpression from i to j. int[,] bracket = new int[n, n]; /* * m[i,j] = Minimum number of scalar multiplications needed to compute the * matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for(int i = 1; i < n; i++) m[i, i] = 0; // L is chain length. for(int L = 2; L < n; L++) { for(int i = 1; i < n - L + 1; i++) { int j = i + L - 1; m[i, j] = int.MaxValue; for (int k = i; k <= j - 1; k++) { // q = cost/scalar multiplications int q = m[i, k] + m[k + 1, j] + p[i - 1] * p[k] * p[j]; if (q < m[i, j]) { m[i, j] = q; // Each entry bracket[i,j]=k shows // where to split the product arr // i,i+1....j for the minimum cost. bracket[i, j] = k; } } } } // The first matrix is printed as 'A', next as 'B', // and so on name = 'A'; Console.Write(\"Optimal Parenthesization is : \"); printParenthesis(1, n - 1, n, bracket); Console.Write(\"\\nOptimal Cost is : \" + m[1, n - 1]);} // Driver codepublic static void Main(String[] args){ int []arr = { 40, 20, 30, 10, 30 }; int n = arr.Length; matrixChainOrder(arr, n);}} // This code is contributed by 29AjayKumar", "e": 37537, "s": 34722, "text": null }, { "code": "<script>// javascript program to print optimal parenthesization// in matrix chain multiplication. var name=0; // Function for printing the optimal // parenthesization of a matrix chain product function printParenthesis(i , j, n, bracket) { // If only one matrix left in current segment if (i == j) { document.write(name++); return; } document.write(\"(\"); // Recursively put brackets around subexpression // from i to bracket[i][j]. // Note that \"*((bracket+i*n)+j)\" is similar to // bracket[i][j] printParenthesis(i, bracket[i][j], n, bracket); // Recursively put brackets around subexpression // from bracket[i][j] + 1 to j. printParenthesis(bracket[i][j] + 1, j, n, bracket); document.write(\")\"); } // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n // Please refer below article for details of this // function // https://goo.gl/k6EYKj function matrixChainOrder( p , n) { /* * For simplicity of the program, one extra row and one extra column are * allocated in m. 0th row and 0th column of m are not used */ var m = Array(n).fill(0).map(x => Array(n).fill(0)); // bracket[i][j] stores optimal break point in // subexpression from i to j. var bracket = Array(n).fill(0).map(x => Array(n).fill(0)); /* * m[i,j] = Minimum number of scalar multiplications needed to compute the * matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (var i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (var L = 2; L < n; L++) { for (var i = 1; i < n - L + 1; i++) { var j = i + L - 1; m[i][j] = Number.MAX_VALUE; for (var k = i; k <= j - 1; k++) { // q = cost/scalar multiplications var q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) { m[i][j] = q; // Each entry bracket[i,j]=k shows // where to split the product arr // i,i+1....j for the minimum cost. bracket[i][j] = k; } } } } // The first matrix is printed as 'A', next as 'B', // and so on name = 'A'; document.write(\"Optimal Parenthesization is : \"); printParenthesis(1, n - 1, n, bracket); document.write(\"\\nOptimal Cost is : \" + m[1][n - 1]); } // Driver code var arr = [ 40, 20, 30, 10, 30 ]; var n = arr.length; matrixChainOrder(arr, n); // This code is contributed by 29AjayKumar</script>", "e": 40158, "s": 37537, "text": null }, { "code": null, "e": 40223, "s": 40158, "text": "Optimal Parenthesization is : ((A(BC))D)nOptimal Cost is : 26000" }, { "code": null, "e": 40269, "s": 40223, "text": "Time Complexity: O(n3) Auxiliary Space: O(n2)" }, { "code": null, "e": 40287, "s": 40269, "text": "Another Approach:" }, { "code": null, "e": 40302, "s": 40287, "text": "——————————————" }, { "code": null, "e": 40377, "s": 40302, "text": "This solution try to solve the problem using Recursion using permutations." }, { "code": null, "e": 40425, "s": 40377, "text": "Let's take example: {40, 20, 30, 10, 30}\nn = 5" }, { "code": null, "e": 40457, "s": 40425, "text": "Let’s divide that into a Matrix" }, { "code": null, "e": 40556, "s": 40457, "text": "[ [40, 20], [20, 30], [30, 10], [10, 30] ]\n\n[ A , B , C , D ]\n\nit contains 4 matrices i.e. (n - 1)" }, { "code": null, "e": 40604, "s": 40556, "text": "We have 3 combinations to multiply i.e. (n-2)" }, { "code": null, "e": 40632, "s": 40604, "text": "AB or BC or CD" }, { "code": null, "e": 40700, "s": 40632, "text": "1) Given array of matrices with length M, Loop through M – 1 times" }, { "code": null, "e": 40743, "s": 40700, "text": "2) Merge consecutive matrices in each loop" }, { "code": null, "e": 40900, "s": 40743, "text": "for (int i = 0; i < M - 1; i++) {\n int cost = (matrices[i][0] * \n matrices[i][1] * matrices[i+1][1]);\n \n // STEP - 3\n // STEP - 4\n}" }, { "code": null, "e": 40987, "s": 40900, "text": "3) Merge the current two matrices into one, and remove merged matrices list from list." }, { "code": null, "e": 41222, "s": 40987, "text": "If A, B merged, then A, B must be removed from the List\n\nand NEW matrix list will be like\nnewMatrices = [ AB, C , D ]\n\nWe have now 3 matrices, in any loop\nLoop#1: [ AB, C, D ]\nLoop#2: [ A, BC, D ]\nLoop#3 [ A, B, CD ]" }, { "code": null, "e": 41290, "s": 41222, "text": "4) Repeat: Go to STEP – 1 with newMatrices as input M — recursion" }, { "code": null, "e": 41345, "s": 41290, "text": "5) Stop recursion, when we get 2 matrices in the list." }, { "code": null, "e": 41385, "s": 41345, "text": "Matrices are reduced in following way, " }, { "code": null, "e": 41486, "s": 41385, "text": "and cost’s must be retained and summed-up during recursion with previous values of each parent step." }, { "code": null, "e": 41886, "s": 41486, "text": "[ A, B , C, D ]\n\n[(AB), C, D ]\n [ ((AB)C), D ]--> [ (((AB)C)D) ] \n - return & sum-up total cost of this step.\n [ (AB), (CD)] --> [ ((AB)(CD)) ] \n - return .. ditto..\n\n [ A, (BC), D ]\n [ (A(BC)), D ]--> [ ((A(BC))D) ] \n - return\n [ A, ((BC)D) ]--> [ (A((BC)D)) ] \n - return\n \n [ A, B, (CD) ]\n [ A, (B(CD)) ]--> [ (A(B(CD))) ] \n - return\n [ (AB), (CD) ]--> [ ((AB)(CD)) ] \n - return .. ditto.." }, { "code": null, "e": 41982, "s": 41886, "text": "on return i.e. at final step of each recursion, check if this value smaller than of any other." }, { "code": null, "e": 42027, "s": 41982, "text": "Below is JAVA implementation of above steps." }, { "code": null, "e": 42032, "s": 42027, "text": "Java" }, { "code": "import java.util.Arrays; public class MatrixMultiplyCost { static class FinalCost { public String label = \"\"; public int cost = Integer.MAX_VALUE; } private void optimalCost(int[][] matrices, String[] labels, int prevCost, FinalCost finalCost) { int len = matrices.length; if (len < 2) { finalCost.cost = 0; return; } else if (len == 2) { int cost = prevCost + (matrices[0][0] * matrices[0][1] * matrices[1][1]); // This is where minimal cost has been caught // for whole program if (cost < finalCost.cost) { finalCost.cost = cost; finalCost.label = \"(\" + labels[0] + labels[1] + \")\"; } return; } // recursive Reduce for (int i = 0; i < len - 1; i++) { int j; int[][] newMatrix = new int[len - 1][2]; String[] newLabels = new String[len - 1]; int subIndex = 0; // STEP-1: // - Merge two matrices's into one - in each // loop, you move merge position // - if i = 0 THEN (AB) C D ... // - if i = 1 THEN A (BC) D ... // - if i = 2 THEN A B (CD) ... // - and find the cost of this two matrices // multiplication int cost = (matrices[i][0] * matrices[i][1] * matrices[i + 1][1]); // STEP - 2: // - Build new matrices after merge // - Keep track of the merged labels too for (j = 0; j < i; j++) { newMatrix[subIndex] = matrices[j]; newLabels[subIndex++] = labels[j]; } newMatrix[subIndex][0] = matrices[i][0]; newMatrix[subIndex][1] = matrices[i + 1][1]; newLabels[subIndex++] = \"(\" + labels[i] + labels[i + 1] + \")\"; for (j = i + 2; j < len; j++) { newMatrix[subIndex] = matrices[j]; newLabels[subIndex++] = labels[j]; } optimalCost(newMatrix, newLabels, prevCost + cost, finalCost); } } public FinalCost findOptionalCost(int[] arr) { // STEP -1 : Prepare and convert inout as Matrix int[][] matrices = new int[arr.length - 1][2]; String[] labels = new String[arr.length - 1]; for (int i = 0; i < arr.length - 1; i++) { matrices[i][0] = arr[i]; matrices[i][1] = arr[i + 1]; labels[i] = Character.toString((char)(65 + i)); } printMatrix(matrices); FinalCost finalCost = new FinalCost(); optimalCost(matrices, labels, 0, finalCost); return finalCost; } /** * Driver Code */ public static void main(String[] args) { MatrixMultiplyCost calc = new MatrixMultiplyCost(); // ======= *** TEST CASES **** ============ int[] arr = { 40, 20, 30, 10, 30 }; FinalCost cost = calc.findOptionalCost(arr); System.out.println(\"Final labels: \\n\" + cost.label); System.out.println(\"Final Cost:\\n\" + cost.cost + \"\\n\"); } /** * Ignore this method * - THIS IS for DISPLAY purpose only */ private static void printMatrix(int[][] matrices) { System.out.print(\"matrices = \\n[\"); for (int[] row : matrices) { System.out.print(Arrays.toString(row) + \" \"); } System.out.println(\"]\"); }} // This code is contributed by suvera", "e": 45825, "s": 42032, "text": null }, { "code": null, "e": 45920, "s": 45825, "text": "matrices = \n[[40, 20] [20, 30] [30, 10] [10, 30] ]\nFinal labels: \n((A(BC))D)\nFinal Cost:\n26000" }, { "code": null, "e": 46339, "s": 45920, "text": "This article is contributed by Yasin Zafar. 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": 46350, "s": 46339, "text": "Rishi_Lazy" }, { "code": null, "e": 46357, "s": 46350, "text": "suvera" }, { "code": null, "e": 46369, "s": 46357, "text": "sanjeev2552" }, { "code": null, "e": 46381, "s": 46369, "text": "29AjayKumar" }, { "code": null, "e": 46397, "s": 46381, "text": "simranarora5sos" }, { "code": null, "e": 46404, "s": 46397, "text": "Amazon" }, { "code": null, "e": 46432, "s": 46404, "text": "matrix-chain-multiplication" }, { "code": null, "e": 46452, "s": 46432, "text": "Dynamic Programming" }, { "code": null, "e": 46459, "s": 46452, "text": "Matrix" }, { "code": null, "e": 46466, "s": 46459, "text": "Amazon" }, { "code": null, "e": 46486, "s": 46466, "text": "Dynamic Programming" }, { "code": null, "e": 46493, "s": 46486, "text": "Matrix" }, { "code": null, "e": 46591, "s": 46493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46654, "s": 46591, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" }, { "code": null, "e": 46680, "s": 46654, "text": "Tabulation vs Memoization" }, { "code": null, "e": 46713, "s": 46680, "text": "Longest Common Substring | DP-29" }, { "code": null, "e": 46735, "s": 46713, "text": "Cutting a Rod | DP-13" }, { "code": null, "e": 46795, "s": 46735, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 46839, "s": 46795, "text": "Program to find largest element in an array" }, { "code": null, "e": 46875, "s": 46839, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 46906, "s": 46875, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 46930, "s": 46906, "text": "Sudoku | Backtracking-7" } ]
COBOL - Basic Verbs
COBOL Tutorial COBOL - Home COBOL - Overview COBOL - Environment Setup COBOL - Program Structure COBOL - Basic Syntax COBOL - Data Types COBOL - Basic Verbs COBOL - Data Layout COBOL - Conditional Statements COBOL - Loop Statements COBOL - String Handling COBOL - Table Processing COBOL - File Handling COBOL - File Organization COBOL - File Access Mode COBOL - File Handling Verbs COBOL - Subroutines COBOL - Internal Sort COBOL - Database Interface COBOL Useful Resources COBOL - Questions and Answers COBOL - Quick Guide COBOL - Useful Resources COBOL - Discussion COBOL verbs are used in the procedure division for data processing. A statement always start with a COBOL verb. There are several COBOL verbs with different types of actions. Input/Output verbs are used to get data from the user and display the output of COBOL programs. The following two verbs are used for this process − Accept verb is used to get data such as date, time, and day from the operating system or directly from the user. If a program is accepting data from the user, then it needs to be passed through JCL. While getting data from the operating system, FROM option is included as shown in the following example − ACCEPT WS-STUDENT-NAME. ACCEPT WS-DATE FROM SYSTEM-DATE. Display verb is used to display the output of a COBOL program. DISPLAY WS-STUDENT-NAME. DISPLAY "System date is : " WS-DATE. COBOL PROGRAM IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-STUDENT-NAME PIC X(25). 01 WS-DATE PIC X(10). PROCEDURE DIVISION. ACCEPT WS-STUDENT-NAME. ACCEPT WS-DATE FROM DATE. DISPLAY "Name : " WS-STUDENT-NAME. DISPLAY "Date : " WS-DATE. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO //INPUT DD DSN=PROGRAM.DIRECTORY,DISP=SHR //SYSIN DD * TutorialsPoint /* When you compile and execute the above program, it produces the following result − Name : TutorialsPoint Date : 200623 Initialize verb is used to initialize a group item or an elementary item. Data names with RENAME clause cannot be initialized. Numeric data items are replaced by ZEROES. Alphanumeric or alphabetic data items are replaced by SPACES. If we include REPLACING term, then data items can be initialized to the given replacing value as shown in the following example − IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NAME PIC A(30) VALUE 'ABCDEF'. 01 WS-ID PIC 9(5). 01 WS-ADDRESS. 05 WS-HOUSE-NUMBER PIC 9(3). 05 WS-COUNTRY PIC X(15). 05 WS-PINCODE PIC 9(6) VALUE 123456. PROCEDURE DIVISION. A000-FIRST-PARA. INITIALIZE WS-NAME, WS-ADDRESS. INITIALIZE WS-ID REPLACING NUMERIC DATA BY 12345. DISPLAY "My name is : "WS-NAME. DISPLAY "My ID is : "WS-ID. DISPLAY "Address : "WS-ADDRESS. DISPLAY "House Number : "WS-HOUSE-NUMBER. DISPLAY "Country : "WS-COUNTRY. DISPLAY "Pincode : "WS-PINCODE. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − My name is : My ID is : 12345 Address : 000 000000 House Number : 000 Country : Pincode : 000000 Move verb is used to copy data from source data to destination data. It can be used on both elementary and group data items. For group data items, MOVE CORRESPONDING/CORR is used. In try it option, MOVE CORR is not working; but on a mainframe server, it will work. For moving data from a string, MOVE(x:l) is used where x is the starting position and l is the length. Data will be truncated if the destination data item PIC clause is less than the source data item PIC clause. If the destination data item PIC clause is more than the source data item PIC clause, then ZEROS or SPACES will be added in the extra bytes. The following example makes it clear. IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC 9(9). 01 WS-NUM2 PIC 9(9). 01 WS-NUM3 PIC 9(5). 01 WS-NUM4 PIC 9(6). 01 WS-ADDRESS. 05 WS-HOUSE-NUMBER PIC 9(3). 05 WS-COUNTRY PIC X(5). 05 WS-PINCODE PIC 9(6). 01 WS-ADDRESS1. 05 WS-HOUSE-NUMBER1 PIC 9(3). 05 WS-COUNTRY1 PIC X(5). 05 WS-PINCODE1 PIC 9(6). PROCEDURE DIVISION. A000-FIRST-PARA. MOVE 123456789 TO WS-NUM1. MOVE WS-NUM1 TO WS-NUM2 WS-NUM3. MOVE WS-NUM1(3:6) TO WS-NUM4. MOVE 123 TO WS-HOUSE-NUMBER. MOVE 'INDIA' TO WS-COUNTRY. MOVE 112233 TO WS-PINCODE. MOVE WS-ADDRESS TO WS-ADDRESS1. DISPLAY "WS-NUM1 : " WS-NUM1 DISPLAY "WS-NUM2 : " WS-NUM2 DISPLAY "WS-NUM3 : " WS-NUM3 DISPLAY "WS-NUM4 : " WS-NUM4 DISPLAY "WS-ADDRESS : " WS-ADDRESS DISPLAY "WS-ADDRESS1 : " WS-ADDRESS1 STOP RUN. JCL to execute the above COBOL program. //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : 123456789 WS-NUM2 : 123456789 WS-NUM3 : 56789 WS-NUM4 : 345678 WS-ADDRESS : 123INDIA112233 WS-ADDRESS1 : 123INDIA112233 The following table gives information about the legal moves − Add verb is used to add two or more numbers and store the result in the destination operand. Given below is the syntax to Add two or more numbers − ADD A B TO C D ADD A B C TO D GIVING E ADD CORR WS-GROUP1 TO WS-GROUP2 In syntax-1, A, B, C are added and the result is stored in C (C=A+B+C). A, B, D are added and the result is stored in D (D = A + B + D). In syntax-2, A, B, C, D are added and the result is stored in E (E=A+B+C+D). In syntax-3, sub-group items within WS-GROUP1 and WS-GROUP2 are added and the result is stored in WS-GROUP2. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC 9(9) VALUE 10 . 01 WS-NUM2 PIC 9(9) VALUE 10. 01 WS-NUM3 PIC 9(9) VALUE 10. 01 WS-NUM4 PIC 9(9) VALUE 10. 01 WS-NUMA PIC 9(9) VALUE 10. 01 WS-NUMB PIC 9(9) VALUE 10. 01 WS-NUMC PIC 9(9) VALUE 10. 01 WS-NUMD PIC 9(9) VALUE 10. 01 WS-NUME PIC 9(9) VALUE 10. PROCEDURE DIVISION. ADD WS-NUM1 WS-NUM2 TO WS-NUM3 WS-NUM4. ADD WS-NUMA WS-NUMB WS-NUMC TO WS-NUMD GIVING WS-NUME. DISPLAY "WS-NUM1 : " WS-NUM1 DISPLAY "WS-NUM2 : " WS-NUM2 DISPLAY "WS-NUM3 : " WS-NUM3 DISPLAY "WS-NUM4 : " WS-NUM4 DISPLAY "WS-NUMA : " WS-NUMA DISPLAY "WS-NUMB : " WS-NUMB DISPLAY "WS-NUMC : " WS-NUMC DISPLAY "WS-NUMD : " WS-NUMD DISPLAY "WS-NUME : " WS-NUME STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : 000000010 WS-NUM2 : 000000010 WS-NUM3 : 000000030 WS-NUM4 : 000000030 WS-NUMA : 000000010 WS-NUMB : 000000010 WS-NUMC : 000000010 WS-NUMD : 000000010 WS-NUME : 000000040 Subtract verb is used for subtraction operations. Given below is the syntax for Subtract operations − SUBTRACT A B FROM C D SUBTRACT A B C FROM D GIVING E SUBTRACT CORR WS-GROUP1 TO WS-GROUP2 In syntax-1, A and B are added and subtracted from C. The result is stored in C (C = C-(A+B)). A and B are added and subtracted from D. The result is stored in D (D = D-(A+B)). In syntax-2, A, B, C are added and subtracted from D. The result is stored in E (E = D-(A+B+C)) In syntax-3, sub-group items within WS-GROUP1 and WS-GROUP2 are subtracted and the result is stored in WS-GROUP2. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC 9(9) VALUE 10 . 01 WS-NUM2 PIC 9(9) VALUE 10. 01 WS-NUM3 PIC 9(9) VALUE 100. 01 WS-NUM4 PIC 9(9) VALUE 100. 01 WS-NUMA PIC 9(9) VALUE 10. 01 WS-NUMB PIC 9(9) VALUE 10. 01 WS-NUMC PIC 9(9) VALUE 10. 01 WS-NUMD PIC 9(9) VALUE 100. 01 WS-NUME PIC 9(9) VALUE 10. PROCEDURE DIVISION. SUBTRACT WS-NUM1 WS-NUM2 FROM WS-NUM3 WS-NUM4. SUBTRACT WS-NUMA WS-NUMB WS-NUMC FROM WS-NUMD GIVING WS-NUME. DISPLAY "WS-NUM1 : " WS-NUM1 DISPLAY "WS-NUM2 : " WS-NUM2 DISPLAY "WS-NUM3 : " WS-NUM3 DISPLAY "WS-NUM4 : " WS-NUM4 DISPLAY "WS-NUMA : " WS-NUMA DISPLAY "WS-NUMB : " WS-NUMB DISPLAY "WS-NUMC : " WS-NUMC DISPLAY "WS-NUMD : " WS-NUMD DISPLAY "WS-NUME : " WS-NUME STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : 000000010 WS-NUM2 : 000000010 WS-NUM3 : 000000080 WS-NUM4 : 000000080 WS-NUMA : 000000010 WS-NUMB : 000000010 WS-NUMC : 000000010 WS-NUMD : 000000100 WS-NUME : 000000070 Multiply verb is used for multiplication operations. Given below is the syntax to multiply two or more numbers − MULTIPLY A BY B C MULTIPLY A BY B GIVING E In syntax-1, A and B are multipled and the result is stored in B (B=A*B). A and C are multipled and the result is stored in C (C = A * C). In syntax-2, A and B are multipled and the result is stored in E (E=A*B). Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC 9(9) VALUE 10 . 01 WS-NUM2 PIC 9(9) VALUE 10. 01 WS-NUM3 PIC 9(9) VALUE 10. 01 WS-NUMA PIC 9(9) VALUE 10. 01 WS-NUMB PIC 9(9) VALUE 10. 01 WS-NUMC PIC 9(9) VALUE 10. PROCEDURE DIVISION. MULTIPLY WS-NUM1 BY WS-NUM2 WS-NUM3. MULTIPLY WS-NUMA BY WS-NUMB GIVING WS-NUMC. DISPLAY "WS-NUM1 : " WS-NUM1 DISPLAY "WS-NUM2 : " WS-NUM2 DISPLAY "WS-NUM3 : " WS-NUM3 DISPLAY "WS-NUMA : " WS-NUMA DISPLAY "WS-NUMB : " WS-NUMB DISPLAY "WS-NUMC : " WS-NUMC STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : 000000010 WS-NUM2 : 000000100 WS-NUM3 : 000000100 WS-NUMA : 000000010 WS-NUMB : 000000010 WS-NUMC : 000000100 Divide verb is used for division operations. Given below is the syntax for division operations − DIVIDE A INTO B DIVIDE A BY B GIVING C REMAINDER R In syntax-1, B is divided by A and the result is stored in B (B=B/A). In syntax-2, A is divided by B and the result is stored in C (C=A/B) and the remainder is stored in R. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC 9(9) VALUE 5. 01 WS-NUM2 PIC 9(9) VALUE 250. 01 WS-NUMA PIC 9(9) VALUE 100. 01 WS-NUMB PIC 9(9) VALUE 15. 01 WS-NUMC PIC 9(9). 01 WS-REM PIC 9(9). PROCEDURE DIVISION. DIVIDE WS-NUM1 INTO WS-NUM2. DIVIDE WS-NUMA BY WS-NUMB GIVING WS-NUMC REMAINDER WS-REM. DISPLAY "WS-NUM1 : " WS-NUM1 DISPLAY "WS-NUM2 : " WS-NUM2 DISPLAY "WS-NUMA : " WS-NUMA DISPLAY "WS-NUMB : " WS-NUMB DISPLAY "WS-NUMC : " WS-NUMC DISPLAY "WS-REM : " WS-REM STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : 000000005 WS-NUM2 : 000000050 WS-NUMA : 000000100 WS-NUMB : 000000015 WS-NUMC : 000000006 WS-REM : 000000010 Compute statement is used to write arithmetic expressions in COBOL. This is a replacement for Add, Subtract, Multiply, and Divide. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC 9(9) VALUE 10 . 01 WS-NUM2 PIC 9(9) VALUE 10. 01 WS-NUM3 PIC 9(9) VALUE 10. 01 WS-NUMA PIC 9(9) VALUE 50. 01 WS-NUMB PIC 9(9) VALUE 10. 01 WS-NUMC PIC 9(9). PROCEDURE DIVISION. COMPUTE WS-NUMC= (WS-NUM1 * WS-NUM2) - (WS-NUMA / WS-NUMB) + WS-NUM3. DISPLAY "WS-NUM1 : " WS-NUM1 DISPLAY "WS-NUM2 : " WS-NUM2 DISPLAY "WS-NUM3 : " WS-NUM3 DISPLAY "WS-NUMA : " WS-NUMA DISPLAY "WS-NUMB : " WS-NUMB DISPLAY "WS-NUMC : " WS-NUMC STOP RUN. JCL to execute the above COBOL program. //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : 000000010 WS-NUM2 : 000000010 WS-NUM3 : 000000010 WS-NUMA : 000000050 WS-NUMB : 000000010 WS-NUMC : 000000105 12 Lectures 2.5 hours Nishant Malik 33 Lectures 3.5 hours Craig Kenneth Kaercher Print Add Notes Bookmark this page
[ { "code": null, "e": 2037, "s": 2022, "text": "COBOL Tutorial" }, { "code": null, "e": 2050, "s": 2037, "text": "COBOL - Home" }, { "code": null, "e": 2067, "s": 2050, "text": "COBOL - Overview" }, { "code": null, "e": 2093, "s": 2067, "text": "COBOL - Environment Setup" }, { "code": null, "e": 2119, "s": 2093, "text": "COBOL - Program Structure" }, { "code": null, "e": 2140, "s": 2119, "text": "COBOL - Basic Syntax" }, { "code": null, "e": 2159, "s": 2140, "text": "COBOL - Data Types" }, { "code": null, "e": 2179, "s": 2159, "text": "COBOL - Basic Verbs" }, { "code": null, "e": 2199, "s": 2179, "text": "COBOL - Data Layout" }, { "code": null, "e": 2230, "s": 2199, "text": "COBOL - Conditional Statements" }, { "code": null, "e": 2254, "s": 2230, "text": "COBOL - Loop Statements" }, { "code": null, "e": 2278, "s": 2254, "text": "COBOL - String Handling" }, { "code": null, "e": 2303, "s": 2278, "text": "COBOL - Table Processing" }, { "code": null, "e": 2325, "s": 2303, "text": "COBOL - File Handling" }, { "code": null, "e": 2351, "s": 2325, "text": "COBOL - File Organization" }, { "code": null, "e": 2376, "s": 2351, "text": "COBOL - File Access Mode" }, { "code": null, "e": 2404, "s": 2376, "text": "COBOL - File Handling Verbs" }, { "code": null, "e": 2424, "s": 2404, "text": "COBOL - Subroutines" }, { "code": null, "e": 2446, "s": 2424, "text": "COBOL - Internal Sort" }, { "code": null, "e": 2473, "s": 2446, "text": "COBOL - Database Interface" }, { "code": null, "e": 2496, "s": 2473, "text": "COBOL Useful Resources" }, { "code": null, "e": 2526, "s": 2496, "text": "COBOL - Questions and Answers" }, { "code": null, "e": 2546, "s": 2526, "text": "COBOL - Quick Guide" }, { "code": null, "e": 2571, "s": 2546, "text": "COBOL - Useful Resources" }, { "code": null, "e": 2590, "s": 2571, "text": "COBOL - Discussion" }, { "code": null, "e": 2765, "s": 2590, "text": "COBOL verbs are used in the procedure division for data processing. A statement always start with a COBOL verb. There are several COBOL verbs with different types of actions." }, { "code": null, "e": 2913, "s": 2765, "text": "Input/Output verbs are used to get data from the user and display the output of COBOL programs. The following two verbs are used for this process −" }, { "code": null, "e": 3218, "s": 2913, "text": "Accept verb is used to get data such as date, time, and day from the operating system or directly from the user. If a program is accepting data from the user, then it needs to be passed through JCL. While getting data from the operating system, FROM option is included as shown in the following example −" }, { "code": null, "e": 3276, "s": 3218, "text": "ACCEPT WS-STUDENT-NAME.\nACCEPT WS-DATE FROM SYSTEM-DATE.\n" }, { "code": null, "e": 3339, "s": 3276, "text": "Display verb is used to display the output of a COBOL program." }, { "code": null, "e": 3402, "s": 3339, "text": "DISPLAY WS-STUDENT-NAME.\nDISPLAY \"System date is : \" WS-DATE.\n" }, { "code": null, "e": 3416, "s": 3402, "text": "COBOL PROGRAM" }, { "code": null, "e": 3719, "s": 3416, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-STUDENT-NAME PIC X(25).\n 01 WS-DATE PIC X(10).\n\nPROCEDURE DIVISION.\n ACCEPT WS-STUDENT-NAME.\n ACCEPT WS-DATE FROM DATE.\n DISPLAY \"Name : \" WS-STUDENT-NAME.\n DISPLAY \"Date : \" WS-DATE.\n\nSTOP RUN." }, { "code": null, "e": 3760, "s": 3719, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 3910, "s": 3760, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO\n//INPUT DD DSN=PROGRAM.DIRECTORY,DISP=SHR\n//SYSIN DD *\nTutorialsPoint\n/*" }, { "code": null, "e": 3993, "s": 3910, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 4030, "s": 3993, "text": "Name : TutorialsPoint\nDate : 200623\n" }, { "code": null, "e": 4392, "s": 4030, "text": "Initialize verb is used to initialize a group item or an elementary item. Data names with RENAME clause cannot be initialized. Numeric data items are replaced by ZEROES. Alphanumeric or alphabetic data items are replaced by SPACES. If we include REPLACING term, then data items can be initialized to the given replacing value as shown in the following example −" }, { "code": null, "e": 5038, "s": 4392, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NAME PIC A(30) VALUE 'ABCDEF'.\n 01 WS-ID PIC 9(5).\n 01 WS-ADDRESS. \n 05 WS-HOUSE-NUMBER PIC 9(3).\n 05 WS-COUNTRY PIC X(15).\n 05 WS-PINCODE PIC 9(6) VALUE 123456.\n\nPROCEDURE DIVISION.\n A000-FIRST-PARA.\n INITIALIZE WS-NAME, WS-ADDRESS.\n INITIALIZE WS-ID REPLACING NUMERIC DATA BY 12345.\n DISPLAY \"My name is : \"WS-NAME.\n DISPLAY \"My ID is : \"WS-ID.\n DISPLAY \"Address : \"WS-ADDRESS.\n DISPLAY \"House Number : \"WS-HOUSE-NUMBER.\n DISPLAY \"Country : \"WS-COUNTRY.\n DISPLAY \"Pincode : \"WS-PINCODE.\n\nSTOP RUN." }, { "code": null, "e": 5079, "s": 5038, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 5156, "s": 5079, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 5239, "s": 5156, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 5419, "s": 5239, "text": "My name is : \nMy ID is : 12345\nAddress : 000 000000\nHouse Number : 000\nCountry : \nPincode : 000000\n" }, { "code": null, "e": 5684, "s": 5419, "text": "Move verb is used to copy data from source data to destination data. It can be used on both elementary and group data items. For group data items, MOVE CORRESPONDING/CORR is used. In try it option, MOVE CORR is not working; but on a mainframe server, it will work." }, { "code": null, "e": 6075, "s": 5684, "text": "For moving data from a string, MOVE(x:l) is used where x is the starting position and l is the length. Data will be truncated if the destination data item PIC clause is less than the source data item PIC clause. If the destination data item PIC clause is more than the source data item PIC clause, then ZEROS or SPACES will be added in the extra bytes. The following example makes it clear." }, { "code": null, "e": 6976, "s": 6075, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NUM1 PIC 9(9).\n 01 WS-NUM2 PIC 9(9).\n 01 WS-NUM3 PIC 9(5).\n 01 WS-NUM4 PIC 9(6).\n 01 WS-ADDRESS. \n 05 WS-HOUSE-NUMBER PIC 9(3).\n 05 WS-COUNTRY PIC X(5).\n 05 WS-PINCODE PIC 9(6).\n 01 WS-ADDRESS1. \n 05 WS-HOUSE-NUMBER1 PIC 9(3).\n 05 WS-COUNTRY1 PIC X(5).\n 05 WS-PINCODE1 PIC 9(6).\n\nPROCEDURE DIVISION.\n A000-FIRST-PARA.\n MOVE 123456789 TO WS-NUM1.\n MOVE WS-NUM1 TO WS-NUM2 WS-NUM3.\n MOVE WS-NUM1(3:6) TO WS-NUM4.\n MOVE 123 TO WS-HOUSE-NUMBER.\n MOVE 'INDIA' TO WS-COUNTRY.\n MOVE 112233 TO WS-PINCODE.\n MOVE WS-ADDRESS TO WS-ADDRESS1.\n\n DISPLAY \"WS-NUM1 : \" WS-NUM1\n DISPLAY \"WS-NUM2 : \" WS-NUM2\n DISPLAY \"WS-NUM3 : \" WS-NUM3\n DISPLAY \"WS-NUM4 : \" WS-NUM4\n DISPLAY \"WS-ADDRESS : \" WS-ADDRESS\n DISPLAY \"WS-ADDRESS1 : \" WS-ADDRESS1\n\nSTOP RUN." }, { "code": null, "e": 7016, "s": 6976, "text": "JCL to execute the above COBOL program." }, { "code": null, "e": 7093, "s": 7016, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 7176, "s": 7093, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 7324, "s": 7176, "text": "WS-NUM1 : 123456789\nWS-NUM2 : 123456789\nWS-NUM3 : 56789\nWS-NUM4 : 345678\nWS-ADDRESS : 123INDIA112233\nWS-ADDRESS1 : 123INDIA112233\n" }, { "code": null, "e": 7386, "s": 7324, "text": "The following table gives information about the legal moves −" }, { "code": null, "e": 7479, "s": 7386, "text": "Add verb is used to add two or more numbers and store the result in the destination operand." }, { "code": null, "e": 7534, "s": 7479, "text": "Given below is the syntax to Add two or more numbers −" }, { "code": null, "e": 7608, "s": 7534, "text": "ADD A B TO C D\n\nADD A B C TO D GIVING E\n\nADD CORR WS-GROUP1 TO WS-GROUP2\n" }, { "code": null, "e": 7745, "s": 7608, "text": "In syntax-1, A, B, C are added and the result is stored in C (C=A+B+C). A, B, D are added and the result is stored in D (D = A + B + D)." }, { "code": null, "e": 7822, "s": 7745, "text": "In syntax-2, A, B, C, D are added and the result is stored in E (E=A+B+C+D)." }, { "code": null, "e": 7931, "s": 7822, "text": "In syntax-3, sub-group items within WS-GROUP1 and WS-GROUP2 are added and the result is stored in WS-GROUP2." }, { "code": null, "e": 7939, "s": 7931, "text": "Example" }, { "code": null, "e": 8782, "s": 7939, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NUM1 PIC 9(9) VALUE 10 .\n 01 WS-NUM2 PIC 9(9) VALUE 10.\n 01 WS-NUM3 PIC 9(9) VALUE 10.\n 01 WS-NUM4 PIC 9(9) VALUE 10.\n 01 WS-NUMA PIC 9(9) VALUE 10.\n 01 WS-NUMB PIC 9(9) VALUE 10.\n 01 WS-NUMC PIC 9(9) VALUE 10.\n 01 WS-NUMD PIC 9(9) VALUE 10.\n 01 WS-NUME PIC 9(9) VALUE 10.\n\nPROCEDURE DIVISION.\n ADD WS-NUM1 WS-NUM2 TO WS-NUM3 WS-NUM4.\n ADD WS-NUMA WS-NUMB WS-NUMC TO WS-NUMD GIVING WS-NUME.\n DISPLAY \"WS-NUM1 : \" WS-NUM1\n DISPLAY \"WS-NUM2 : \" WS-NUM2\n DISPLAY \"WS-NUM3 : \" WS-NUM3\n DISPLAY \"WS-NUM4 : \" WS-NUM4\n DISPLAY \"WS-NUMA : \" WS-NUMA\n DISPLAY \"WS-NUMB : \" WS-NUMB\n DISPLAY \"WS-NUMC : \" WS-NUMC\n DISPLAY \"WS-NUMD : \" WS-NUMD\n DISPLAY \"WS-NUME : \" WS-NUME\n\nSTOP RUN." }, { "code": null, "e": 8823, "s": 8782, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 8900, "s": 8823, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 8983, "s": 8900, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 9200, "s": 8983, "text": "WS-NUM1 : 000000010\nWS-NUM2 : 000000010\nWS-NUM3 : 000000030\nWS-NUM4 : 000000030\nWS-NUMA : 000000010\nWS-NUMB : 000000010\nWS-NUMC : 000000010\nWS-NUMD : 000000010\nWS-NUME : 000000040\n" }, { "code": null, "e": 9250, "s": 9200, "text": "Subtract verb is used for subtraction operations." }, { "code": null, "e": 9302, "s": 9250, "text": "Given below is the syntax for Subtract operations −" }, { "code": null, "e": 9395, "s": 9302, "text": "SUBTRACT A B FROM C D\n\nSUBTRACT A B C FROM D GIVING E\n\nSUBTRACT CORR WS-GROUP1 TO WS-GROUP2\n" }, { "code": null, "e": 9572, "s": 9395, "text": "In syntax-1, A and B are added and subtracted from C. The result is stored in C (C = C-(A+B)). A and B are added and subtracted from D. The result is stored in D (D = D-(A+B))." }, { "code": null, "e": 9668, "s": 9572, "text": "In syntax-2, A, B, C are added and subtracted from D. The result is stored in E (E = D-(A+B+C))" }, { "code": null, "e": 9782, "s": 9668, "text": "In syntax-3, sub-group items within WS-GROUP1 and WS-GROUP2 are subtracted and the result is stored in WS-GROUP2." }, { "code": null, "e": 9790, "s": 9782, "text": "Example" }, { "code": null, "e": 10651, "s": 9790, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NUM1 PIC 9(9) VALUE 10 .\n 01 WS-NUM2 PIC 9(9) VALUE 10.\n 01 WS-NUM3 PIC 9(9) VALUE 100.\n 01 WS-NUM4 PIC 9(9) VALUE 100.\n 01 WS-NUMA PIC 9(9) VALUE 10.\n 01 WS-NUMB PIC 9(9) VALUE 10.\n 01 WS-NUMC PIC 9(9) VALUE 10.\n 01 WS-NUMD PIC 9(9) VALUE 100.\n 01 WS-NUME PIC 9(9) VALUE 10.\n\nPROCEDURE DIVISION.\n SUBTRACT WS-NUM1 WS-NUM2 FROM WS-NUM3 WS-NUM4.\n SUBTRACT WS-NUMA WS-NUMB WS-NUMC FROM WS-NUMD GIVING WS-NUME.\n\n DISPLAY \"WS-NUM1 : \" WS-NUM1\n DISPLAY \"WS-NUM2 : \" WS-NUM2\n DISPLAY \"WS-NUM3 : \" WS-NUM3\n DISPLAY \"WS-NUM4 : \" WS-NUM4\n DISPLAY \"WS-NUMA : \" WS-NUMA\n DISPLAY \"WS-NUMB : \" WS-NUMB\n DISPLAY \"WS-NUMC : \" WS-NUMC\n DISPLAY \"WS-NUMD : \" WS-NUMD\n DISPLAY \"WS-NUME : \" WS-NUME\n\nSTOP RUN." }, { "code": null, "e": 10692, "s": 10651, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 10769, "s": 10692, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 10852, "s": 10769, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 11069, "s": 10852, "text": "WS-NUM1 : 000000010\nWS-NUM2 : 000000010\nWS-NUM3 : 000000080\nWS-NUM4 : 000000080\nWS-NUMA : 000000010\nWS-NUMB : 000000010\nWS-NUMC : 000000010\nWS-NUMD : 000000100\nWS-NUME : 000000070\n" }, { "code": null, "e": 11122, "s": 11069, "text": "Multiply verb is used for multiplication operations." }, { "code": null, "e": 11182, "s": 11122, "text": "Given below is the syntax to multiply two or more numbers −" }, { "code": null, "e": 11227, "s": 11182, "text": "MULTIPLY A BY B C\n\nMULTIPLY A BY B GIVING E\n" }, { "code": null, "e": 11366, "s": 11227, "text": "In syntax-1, A and B are multipled and the result is stored in B (B=A*B). A and C are multipled and the result is stored in C (C = A * C)." }, { "code": null, "e": 11440, "s": 11366, "text": "In syntax-2, A and B are multipled and the result is stored in E (E=A*B)." }, { "code": null, "e": 11448, "s": 11440, "text": "Example" }, { "code": null, "e": 12077, "s": 11448, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NUM1 PIC 9(9) VALUE 10 .\n 01 WS-NUM2 PIC 9(9) VALUE 10.\n 01 WS-NUM3 PIC 9(9) VALUE 10.\n 01 WS-NUMA PIC 9(9) VALUE 10.\n 01 WS-NUMB PIC 9(9) VALUE 10.\n 01 WS-NUMC PIC 9(9) VALUE 10.\n\nPROCEDURE DIVISION.\n MULTIPLY WS-NUM1 BY WS-NUM2 WS-NUM3.\n MULTIPLY WS-NUMA BY WS-NUMB GIVING WS-NUMC.\n \n DISPLAY \"WS-NUM1 : \" WS-NUM1\n DISPLAY \"WS-NUM2 : \" WS-NUM2\n DISPLAY \"WS-NUM3 : \" WS-NUM3\n DISPLAY \"WS-NUMA : \" WS-NUMA\n DISPLAY \"WS-NUMB : \" WS-NUMB\n DISPLAY \"WS-NUMC : \" WS-NUMC\n \nSTOP RUN." }, { "code": null, "e": 12118, "s": 12077, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 12195, "s": 12118, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 12278, "s": 12195, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 12423, "s": 12278, "text": "WS-NUM1 : 000000010\nWS-NUM2 : 000000100\nWS-NUM3 : 000000100\nWS-NUMA : 000000010\nWS-NUMB : 000000010\nWS-NUMC : 000000100\n" }, { "code": null, "e": 12468, "s": 12423, "text": "Divide verb is used for division operations." }, { "code": null, "e": 12520, "s": 12468, "text": "Given below is the syntax for division operations −" }, { "code": null, "e": 12573, "s": 12520, "text": "DIVIDE A INTO B\n\nDIVIDE A BY B GIVING C REMAINDER R\n" }, { "code": null, "e": 12643, "s": 12573, "text": "In syntax-1, B is divided by A and the result is stored in B (B=B/A)." }, { "code": null, "e": 12746, "s": 12643, "text": "In syntax-2, A is divided by B and the result is stored in C (C=A/B) and the remainder is stored in R." }, { "code": null, "e": 12754, "s": 12746, "text": "Example" }, { "code": null, "e": 13367, "s": 12754, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NUM1 PIC 9(9) VALUE 5.\n 01 WS-NUM2 PIC 9(9) VALUE 250.\n 01 WS-NUMA PIC 9(9) VALUE 100.\n 01 WS-NUMB PIC 9(9) VALUE 15.\n 01 WS-NUMC PIC 9(9).\n 01 WS-REM PIC 9(9). \n\nPROCEDURE DIVISION.\n DIVIDE WS-NUM1 INTO WS-NUM2.\n DIVIDE WS-NUMA BY WS-NUMB GIVING WS-NUMC REMAINDER WS-REM.\n DISPLAY \"WS-NUM1 : \" WS-NUM1\n DISPLAY \"WS-NUM2 : \" WS-NUM2\n DISPLAY \"WS-NUMA : \" WS-NUMA\n DISPLAY \"WS-NUMB : \" WS-NUMB\n DISPLAY \"WS-NUMC : \" WS-NUMC\n DISPLAY \"WS-REM : \" WS-REM\n \nSTOP RUN." }, { "code": null, "e": 13408, "s": 13367, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 13485, "s": 13408, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 13568, "s": 13485, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 13713, "s": 13568, "text": "WS-NUM1 : 000000005\nWS-NUM2 : 000000050\nWS-NUMA : 000000100\nWS-NUMB : 000000015\nWS-NUMC : 000000006\nWS-REM : 000000010\n" }, { "code": null, "e": 13844, "s": 13713, "text": "Compute statement is used to write arithmetic expressions in COBOL. This is a replacement for Add, Subtract, Multiply, and Divide." }, { "code": null, "e": 13852, "s": 13844, "text": "Example" }, { "code": null, "e": 14451, "s": 13852, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NUM1 PIC 9(9) VALUE 10 .\n 01 WS-NUM2 PIC 9(9) VALUE 10.\n 01 WS-NUM3 PIC 9(9) VALUE 10.\n 01 WS-NUMA PIC 9(9) VALUE 50.\n 01 WS-NUMB PIC 9(9) VALUE 10.\n 01 WS-NUMC PIC 9(9).\n\nPROCEDURE DIVISION.\n COMPUTE WS-NUMC= (WS-NUM1 * WS-NUM2) - (WS-NUMA / WS-NUMB) + WS-NUM3.\n DISPLAY \"WS-NUM1 : \" WS-NUM1\n DISPLAY \"WS-NUM2 : \" WS-NUM2\n DISPLAY \"WS-NUM3 : \" WS-NUM3\n DISPLAY \"WS-NUMA : \" WS-NUMA\n DISPLAY \"WS-NUMB : \" WS-NUMB\n DISPLAY \"WS-NUMC : \" WS-NUMC\n\nSTOP RUN." }, { "code": null, "e": 14491, "s": 14451, "text": "JCL to execute the above COBOL program." }, { "code": null, "e": 14568, "s": 14491, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 14651, "s": 14568, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 14796, "s": 14651, "text": "WS-NUM1 : 000000010\nWS-NUM2 : 000000010\nWS-NUM3 : 000000010\nWS-NUMA : 000000050\nWS-NUMB : 000000010\nWS-NUMC : 000000105\n" }, { "code": null, "e": 14831, "s": 14796, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14846, "s": 14831, "text": " Nishant Malik" }, { "code": null, "e": 14881, "s": 14846, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 14905, "s": 14881, "text": " Craig Kenneth Kaercher" }, { "code": null, "e": 14912, "s": 14905, "text": " Print" }, { "code": null, "e": 14923, "s": 14912, "text": " Add Notes" } ]
Set dotted line for border with CSS
To set dotted line for border, use the border-style property. You can try to run the following code to implement border-style property value dotted to set dotted border: <html> <head> </head> <body> <p style = "border-width:3px; border-style:dotted;"> This is a dotted border. </p> </body> </html>
[ { "code": null, "e": 1232, "s": 1062, "text": "To set dotted line for border, use the border-style property. You can try to run the following code to implement border-style property value dotted to set dotted border:" }, { "code": null, "e": 1393, "s": 1232, "text": "<html>\n <head>\n </head>\n <body>\n <p style = \"border-width:3px; border-style:dotted;\">\n This is a dotted border.\n </p>\n </body>\n</html>" } ]
Python - How to Concatenate Two or More Pandas DataFrames along rows?
To concatenate more than two Pandas DataFrames, use the concat() method. Set the axis parameter as axis = 0 to concatenate along rows. At first, import the required library − import pandas as pd Let us create the 1st DataFrame − dataFrame1 = pd.DataFrame( { "Col1": [10, 20, 30],"Col2": [40, 50, 60],"Col3": [70, 80, 90], }, index=[0, 1, 2], ) Let us create the 2nd DataFrame − dataFrame2 = pd.DataFrame( { "Col1": [100, 110, 120],"Col2": [130, 140, 150],"Col3": [160, 170, 180], }, index=[3, 4, 5], ) Let us create the 3rd DataFrame − dataFrame3 = pd.DataFrame( { "Col1": [200, 210, 220],"Col2": [230, 240, 250],"Col3": [260, 270, 280], }, index=[6, 7, 8], ) Concatenate all the 3 DataFrames using concat(). Set "axis=1" for concatenation along rows − res = [dataFrame1, dataFrame2, dataFrame3] pd.concat(res, axis=1)) Following is the code − import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Col1": [10, 20, 30],"Col2": [40, 50, 60],"Col3": [70, 80, 90], }, index=[0, 1, 2], ) # DataFrame1 print"DataFrame1...\n",dataFrame1 # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Col1": [100, 110, 120],"Col2": [130, 140, 150],"Col3": [160, 170, 180], }, index=[3, 4, 5], ) # DataFrame2 print"DataFrame2...\n",dataFrame2 dataFrame3 = pd.DataFrame( { "Col1": [200, 210, 220],"Col2": [230, 240, 250],"Col3": [260, 270, 280], }, index=[6, 7, 8], ) # DataFrame3 print"DataFrame3...\n",dataFrame3 # concatenating more than 2 dataframes # set "axis=0" for concatenation along rows res = [dataFrame1, dataFrame2, dataFrame3] print"\n Concatenating all the 3 DataFrames (along rows)...\n", pd.concat(res, axis=0) This will produce the following output − DataFrame1... Col1 Col2 Col3 0 10 40 70 1 20 50 80 2 30 60 90 DataFrame2... Col1 Col2 Col3 3 100 130 160 4 110 140 170 5 120 150 180 DataFrame3... Col1 Col2 Col3 6 200 230 260 7 210 240 270 8 220 250 280 Concatenating all the 3 DataFrames (along rows)... Col1 Col2 Col3 0 10 40 70 1 20 50 80 2 30 60 90 3 100 130 160 4 110 140 170 5 120 150 180 6 200 230 260 7 210 240 270 8 220 250 280
[ { "code": null, "e": 1237, "s": 1062, "text": "To concatenate more than two Pandas DataFrames, use the concat() method. Set the axis parameter as axis = 0 to concatenate along rows. At first, import the required library −" }, { "code": null, "e": 1257, "s": 1237, "text": "import pandas as pd" }, { "code": null, "e": 1291, "s": 1257, "text": "Let us create the 1st DataFrame −" }, { "code": null, "e": 1423, "s": 1291, "text": "dataFrame1 = pd.DataFrame(\n {\n \"Col1\": [10, 20, 30],\"Col2\": [40, 50, 60],\"Col3\": [70, 80, 90],\n },\n index=[0, 1, 2],\n)\n\n" }, { "code": null, "e": 1457, "s": 1423, "text": "Let us create the 2nd DataFrame −" }, { "code": null, "e": 1598, "s": 1457, "text": "dataFrame2 = pd.DataFrame(\n {\n \"Col1\": [100, 110, 120],\"Col2\": [130, 140, 150],\"Col3\": [160, 170, 180],\n },\n index=[3, 4, 5],\n)\n\n" }, { "code": null, "e": 1632, "s": 1598, "text": "Let us create the 3rd DataFrame −" }, { "code": null, "e": 1771, "s": 1632, "text": "dataFrame3 = pd.DataFrame(\n {\n \"Col1\": [200, 210, 220],\"Col2\": [230, 240, 250],\"Col3\": [260, 270, 280],\n },\n index=[6, 7, 8],\n)" }, { "code": null, "e": 1864, "s": 1771, "text": "Concatenate all the 3 DataFrames using concat(). Set \"axis=1\" for concatenation along rows −" }, { "code": null, "e": 1931, "s": 1864, "text": "res = [dataFrame1, dataFrame2, dataFrame3]\npd.concat(res, axis=1))" }, { "code": null, "e": 1955, "s": 1931, "text": "Following is the code −" }, { "code": null, "e": 2786, "s": 1955, "text": "import pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Col1\": [10, 20, 30],\"Col2\": [40, 50, 60],\"Col3\": [70, 80, 90],\n },\n index=[0, 1, 2],\n)\n\n# DataFrame1\nprint\"DataFrame1...\\n\",dataFrame1\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Col1\": [100, 110, 120],\"Col2\": [130, 140, 150],\"Col3\": [160, 170, 180],\n },\n index=[3, 4, 5],\n)\n\n# DataFrame2\nprint\"DataFrame2...\\n\",dataFrame2\n\ndataFrame3 = pd.DataFrame(\n {\n \"Col1\": [200, 210, 220],\"Col2\": [230, 240, 250],\"Col3\": [260, 270, 280],\n },\n index=[6, 7, 8],\n)\n\n# DataFrame3\nprint\"DataFrame3...\\n\",dataFrame3\n\n# concatenating more than 2 dataframes\n# set \"axis=0\" for concatenation along rows\nres = [dataFrame1, dataFrame2, dataFrame3]\nprint\"\\n Concatenating all the 3 DataFrames (along rows)...\\n\", pd.concat(res, axis=0)\n\n" }, { "code": null, "e": 2827, "s": 2786, "text": "This will produce the following output −" }, { "code": null, "e": 3396, "s": 2827, "text": "DataFrame1...\n Col1 Col2 Col3\n0 10 40 70\n1 20 50 80\n2 30 60 90\nDataFrame2...\n Col1 Col2 Col3\n3 100 130 160\n4 110 140 170\n5 120 150 180\nDataFrame3...\n Col1 Col2 Col3\n6 200 230 260\n7 210 240 270\n8 220 250 280\n\nConcatenating all the 3 DataFrames (along rows)...\n Col1 Col2 Col3\n0 10 40 70\n1 20 50 80\n2 30 60 90\n3 100 130 160\n4 110 140 170\n5 120 150 180\n6 200 230 260\n7 210 240 270\n8 220 250 280" } ]
Explain the dynamic memory allocation of pointer to structure in C language
Pointer to structure holds the add of the entire structure. It is used to create complex data structures such as linked lists, trees, graphs and so on. The members of the structure can be accessed using a special operator called as an arrow operator ( -> ). Following is the declaration for pointers to structures in C programming − struct tagname *ptr; For example: struct student *s; It is explained below how to access the pointers to structures. Ptr-> membername; For example − s->sno, s->sname, s->marks; Following is a C program that explains the dynamic memory allocation of structure in C programming − Live Demo #include <stdio.h> #include <stdlib.h> struct person { int age; float weight; char name[30]; }; int main(){ struct person *ptr; int i, n; printf("Enter the number of persons: "); scanf("%d", &n); // allocating memory for n numbers of struct person ptr = (struct person*) malloc(n * sizeof(struct person)); for(i = 0; i < n; ++i){ printf("Enter name and age respectively: "); // To access members of 1st struct person, // ptr->name and ptr->age is used // To access members of 2nd struct person, // (ptr+1)->name and (ptr+1)->age is used scanf("%s %d", (ptr+i)->name, &(ptr+i)->age); } printf("Displaying Information:\n"); for(i = 0; i < n; ++i) printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age); return 0; } When the above program is executed, it produces the following result − Enter the number of persons: 1 Enter name and age respectively: bhanu 24 Displaying Information: Name: bhanu Age: 24 Consider another example on pointers and structures, wherein, a C program to demonstrate pointers and structures is given. Live Demo #include<stdio.h> //Declaring outer and inter structures// struct Manager{ char Name[15]; int Age; char Gender; float Level; char Role[50]; char temp; }m[20]; void main(){ //Declaring variable for For loop and pointer variable// int i; struct Manager *p; //Defining Pointer// p=&m; //Reading User I/p// for (i=1;i<3;i++){//Declaring function to accept 2 manager's data// printf("Enter the Name of manager %d : ",i); gets(p->Name); printf("Enter the Age of manager %d : ",i); scanf("%d",&p->Age); scanf("%c",&p->temp);//Clearing Buffer// printf("Enter the Gender of manager %d : ",i); scanf("%c",&p->Gender); //scanf("%c",&p->temp);//Clearing Buffer// printf("Enter the level of manager %d : ",i); scanf("%f",&p->Level); scanf("%c",&p->temp);//Clearing Buffer// printf("Enter the role of manager %d : ",i); gets(p->Role); p++; } //Defining Pointer one more time to print output// p=&m; //Printing O/p// for (i=1;i<3;i++){ printf("The Name of Manager %d is : %s\n",i,p->Name); printf("The Age of Manager %d is : %d\n",i,p->Age); printf("The Gender of Manager %d is : %c\n",i,p->Gender); printf("The Level of Manager %d is : %f\n",i,p->Level); printf("The Role of Manager %d is : %s\n",i,p->Role); p++; } } When the above program is executed, it produces the following result − Enter the Name of manager 1 : Hari Enter the Age of manager 1 : 55 Enter the Gender of manager 1 : M Enter the level of manager 1 : 2 Enter the role of manager 1 : Senior Enter the Name of manager 2 : Bob Enter the Age of manager 2 : 60 Enter the Gender of manager 2 : M Enter the level of manager 2 : 1 Enter the role of manager 2 : CEO The Name of Manager 1 is : Hari The Age of Manager 1 is : 55 The Gender of Manager 1 is : M The Level of Manager 1 is : 2.000000 The Role of Manager 1 is : Senior The Name of Manager 2 is : Bob The Age of Manager 2 is : 60 The Gender of Manager 2 is : M The Level of Manager 2 is : 1.000000 The Role of Manager 2 is : CEO
[ { "code": null, "e": 1122, "s": 1062, "text": "Pointer to structure holds the add of the entire structure." }, { "code": null, "e": 1214, "s": 1122, "text": "It is used to create complex data structures such as linked lists, trees, graphs and so on." }, { "code": null, "e": 1320, "s": 1214, "text": "The members of the structure can be accessed using a special operator called as an arrow operator ( -> )." }, { "code": null, "e": 1395, "s": 1320, "text": "Following is the declaration for pointers to structures in C programming −" }, { "code": null, "e": 1416, "s": 1395, "text": "struct tagname *ptr;" }, { "code": null, "e": 1448, "s": 1416, "text": "For example: struct student *s;" }, { "code": null, "e": 1512, "s": 1448, "text": "It is explained below how to access the pointers to structures." }, { "code": null, "e": 1530, "s": 1512, "text": "Ptr-> membername;" }, { "code": null, "e": 1572, "s": 1530, "text": "For example − s->sno, s->sname, s->marks;" }, { "code": null, "e": 1673, "s": 1572, "text": "Following is a C program that explains the dynamic memory allocation of structure in C programming −" }, { "code": null, "e": 1684, "s": 1673, "text": " Live Demo" }, { "code": null, "e": 2485, "s": 1684, "text": "#include <stdio.h>\n#include <stdlib.h>\nstruct person {\n int age;\n float weight;\n char name[30];\n};\nint main(){\n struct person *ptr;\n int i, n;\n printf(\"Enter the number of persons: \");\n scanf(\"%d\", &n);\n // allocating memory for n numbers of struct person\n ptr = (struct person*) malloc(n * sizeof(struct person));\n for(i = 0; i < n; ++i){\n printf(\"Enter name and age respectively: \");\n // To access members of 1st struct person,\n // ptr->name and ptr->age is used\n // To access members of 2nd struct person,\n // (ptr+1)->name and (ptr+1)->age is used\n scanf(\"%s %d\", (ptr+i)->name, &(ptr+i)->age);\n }\n printf(\"Displaying Information:\\n\");\n for(i = 0; i < n; ++i)\n printf(\"Name: %s\\tAge: %d\\n\", (ptr+i)->name, (ptr+i)->age);\n return 0;\n}" }, { "code": null, "e": 2556, "s": 2485, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2673, "s": 2556, "text": "Enter the number of persons: 1\nEnter name and age respectively: bhanu 24\nDisplaying Information:\nName: bhanu Age: 24" }, { "code": null, "e": 2796, "s": 2673, "text": "Consider another example on pointers and structures, wherein, a C program to demonstrate pointers and structures is given." }, { "code": null, "e": 2807, "s": 2796, "text": " Live Demo" }, { "code": null, "e": 4188, "s": 2807, "text": "#include<stdio.h>\n//Declaring outer and inter structures//\nstruct Manager{\n char Name[15];\n int Age;\n char Gender;\n float Level;\n char Role[50];\n char temp;\n}m[20];\nvoid main(){\n //Declaring variable for For loop and pointer variable//\n int i;\n struct Manager *p;\n //Defining Pointer//\n p=&m;\n //Reading User I/p//\n for (i=1;i<3;i++){//Declaring function to accept 2 manager's data//\n printf(\"Enter the Name of manager %d : \",i);\n gets(p->Name);\n printf(\"Enter the Age of manager %d : \",i);\n scanf(\"%d\",&p->Age);\n scanf(\"%c\",&p->temp);//Clearing Buffer//\n printf(\"Enter the Gender of manager %d : \",i);\n scanf(\"%c\",&p->Gender);\n //scanf(\"%c\",&p->temp);//Clearing Buffer//\n printf(\"Enter the level of manager %d : \",i);\n scanf(\"%f\",&p->Level);\n scanf(\"%c\",&p->temp);//Clearing Buffer//\n printf(\"Enter the role of manager %d : \",i);\n gets(p->Role);\n p++;\n }\n //Defining Pointer one more time to print output//\n p=&m;\n //Printing O/p//\n for (i=1;i<3;i++){\n printf(\"The Name of Manager %d is : %s\\n\",i,p->Name);\n printf(\"The Age of Manager %d is : %d\\n\",i,p->Age);\n printf(\"The Gender of Manager %d is : %c\\n\",i,p->Gender);\n printf(\"The Level of Manager %d is : %f\\n\",i,p->Level);\n printf(\"The Role of Manager %d is : %s\\n\",i,p->Role);\n p++;\n }\n}" }, { "code": null, "e": 4259, "s": 4188, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 4919, "s": 4259, "text": "Enter the Name of manager 1 : Hari\nEnter the Age of manager 1 : 55\nEnter the Gender of manager 1 : M\nEnter the level of manager 1 : 2\nEnter the role of manager 1 : Senior\nEnter the Name of manager 2 : Bob\nEnter the Age of manager 2 : 60\nEnter the Gender of manager 2 : M\nEnter the level of manager 2 : 1\nEnter the role of manager 2 : CEO\nThe Name of Manager 1 is : Hari\nThe Age of Manager 1 is : 55\nThe Gender of Manager 1 is : M\nThe Level of Manager 1 is : 2.000000\nThe Role of Manager 1 is : Senior\nThe Name of Manager 2 is : Bob\nThe Age of Manager 2 is : 60\nThe Gender of Manager 2 is : M\nThe Level of Manager 2 is : 1.000000\nThe Role of Manager 2 is : CEO" } ]
Check if an array can be Arranged in Left or Right Positioned Array - GeeksforGeeks
20 Apr, 2021 Given an array arr[] of size n>4, the task is to check whether the given array can be arranged in the form of Left or Right positioned array? Left or Right Positioned Array means each element in the array is equal to the number of elements to its left or number of elements to its right.Examples : Input : arr[] = {1, 3, 3, 2} Output : "YES" This array has one such arrangement {3, 1, 2, 3}. In this arrangement, first element '3' indicates that three numbers are after it, the 2nd element '1' indicates that one number is before it, the 3rd element '2' indicates that two elements are before it. Input : arr[] = {1, 6, 5, 4, 3, 2, 1} Output: "NO" // No such arrangement is possible Input : arr[] = {2, 0, 1, 3} Output: "YES" // Possible arrangement is {0, 1, 2, 3} Input : arr[] = {2, 1, 5, 2, 1, 5} Output: "YES" // Possible arrangement is {5, 1, 2, 2, 1, 5} A simple solution is to generate all possible arrangements (see this article) and check for the Left or Right Positioned Array condition, if each element in the array satisfies the condition then “YES” else “NO”. Time complexity for this approach is O(n*n! + n), n*n! to generate all arrangements and n for checking the condition using temporary array.An efficient solution for this problem needs little bit observation and pen-paper work. To satisfy the Left or Right Positioned Array condition all the numbers in the array should either be equal to index, i or (n-1-i) and arr[i] < n. So we create an visited[] array of size n and initialize its element with 0. Then we traverse array and follow given steps : If visited[arr[i]] = 0 then make it 1, which checks for the condition that number of elements on the left side of array arr[0]...arr[i-1] is equal to arr[i]. Else make visited[n-arr[i]-1] = 1, which checks for the condition that number of elements on the right side of array arr[i+1]...arr[n-1] is equal to arr[i]. Now traverse visited[] array and if all the elements of visited[] array become 1 that means arrangement is possible “YES” else “NO”. C++ Java Python3 C# PHP Javascript // C++ program to check if an array can be arranged// to left or right positioned array.#include<bits/stdc++.h>using namespace std; // Function to check Left or Right Positioned// Array.// arr[] is array of n elements// visited[] is boolean array of size nbool leftRight(int arr[],int n){ // Initially no element is placed at any position int visited[n] = {0}; // Traverse each element of array for (int i=0; i<n; i++) { // Element must be smaller than n. if (arr[i] < n) { // Place "arr[i]" at position "i" // or at position n-arr[i]-1 if (visited[arr[i]] == 0) visited[arr[i]] = 1; else visited[n-arr[i]-1] = 1; } } // All positions must be occupied for (int i=0; i<n; i++) if (visited[i] == 0) return false; return true;} // Driver program to test the caseint main(){ int arr[] = {2, 1, 5, 2, 1, 5}; int n = sizeof(arr)/sizeof(arr[0]); if (leftRight(arr, n) == true) cout << "YES"; else cout << "NO"; return 0;} // Java program to check if an array// can be arranged to left or// right positioned array. class GFG { // Function to check Left or // Right Positioned Array. // arr[] is array of n elements // visited[] is boolean array of size n static boolean leftRight(int arr[], int n) { // Initially no element is // placed at any position int visited[] = new int[n]; // Traverse each element of array for (int i = 0; i < n; i++) { // Element must be smaller than n. if (arr[i] < n) { // Place "arr[i]" at position "i" // or at position n-arr[i]-1 if (visited[arr[i]] == 0) visited[arr[i]] = 1; else visited[n - arr[i] - 1] = 1; } } // All positions must be occupied for (int i = 0; i < n; i++) if (visited[i] == 0) return false; return true;} // Driver codepublic static void main(String[] args){ int arr[] = {2, 1, 5, 2, 1, 5}; int n = arr.length; if (leftRight(arr, n) == true) System.out.print("YES"); else System.out.print("NO");}} // This code is contributed by Anant Agarwal. # Python3 program to check# if an array can be arranged# to left or right positioned array. # Function to check Left# or Right Positioned# Array.# arr[] is array of n elements# visited[] is boolean array of size ndef leftRight(arr,n): # Initially no element # is placed at any position visited=[] for i in range(n+1): visited.append(0) # Traverse each element of array for i in range(n): # Element must be smaller than n. if (arr[i] < n): # Place "arr[i]" at position "i" # or at position n-arr[i]-1 if (visited[arr[i]] == 0): visited[arr[i]] = 1 else: visited[n-arr[i]-1] = 1 # All positions must be occupied for i in range(n): if (visited[i] == 0): return False return True # Driver code arr = [2, 1, 5, 2, 1, 5]n = len(arr) if (leftRight(arr, n) == True): print("YES")else: print("NO") # This code is contributed# by Anant Agarwal. // C# program to check if an array// can be arranged to left or// right positioned array.using System;public class GFG { // Function to check Left or // Right Positioned Array. // arr[] is array of n elements // visited[] is boolean array of size n static bool leftRight(int []arr, int n) { // Initially no element is // placed at any position int []visited = new int[n]; // Traverse each element of array for (int i = 0; i < n; i++) { // Element must be smaller than n. if (arr[i] < n) { // Place "arr[i]" at position "i" // or at position n-arr[i]-1 if (visited[arr[i]] == 0) visited[arr[i]] = 1; else visited[n - arr[i] - 1] = 1; } } // All positions must be occupied for (int i = 0; i < n; i++) if (visited[i] == 0) return false; return true; } // Driver code public static void Main() { int []arr = {2, 1, 5, 2, 1, 5}; int n = arr.Length; if (leftRight(arr, n) == true) Console.WriteLine("YES"); else Console.WriteLine("NO"); }}// This code is contributed by PrinciRaj1992 <?php// PHP program to check if an// array can be arranged to// left or right positioned array. // Function to check Left or// Right Positioned Array.// arr[] is array of n elements// visited[] is boolean array of size nfunction leftRight($arr, $n){ // Initially no element is // placed at any position $visited[$n] = array(0); // Traverse each element of array for ($i = 0; $i < $n; $i++) { // Element must be smaller than n. if ($arr[$i] < $n) { // Place "arr[i]" at position "i" // or at position n-arr[i]-1 $visited[$arr[$i]] = 1; $visited[$n - $arr[$i] - 1] = 1; } } // All positions must be occupied for ($i = 0; $i < $n; $i++) if ($visited[$i] == 0) return false; return true;} // Driver Code$arr = array(2, 1, 5, 2, 1, 5);$n = sizeof($arr);if (leftRight($arr, $n) == true) echo "YES";else echo "NO"; // This code is contributed by ajit?> <script> // Javascript program to check if an array // can be arranged to left or // right positioned array. // Function to check Left or // Right Positioned Array. // arr[] is array of n elements // visited[] is boolean array of size n function leftRight(arr, n) { // Initially no element is // placed at any position let visited = new Array(n); // Traverse each element of array for (let i = 0; i < n; i++) { // Element must be smaller than n. if (arr[i] < n) { // Place "arr[i]" at position "i" // or at position n-arr[i]-1 if (visited[arr[i]] == 0) visited[arr[i]] = 1; else visited[n - arr[i] - 1] = 1; } } // All positions must be occupied for (let i = 0; i < n; i++) if (visited[i] == 0) return false; return true; } let arr = [2, 1, 5, 2, 1, 5]; let n = arr.length; if (leftRight(arr, n) == true) document.write("YES"); else document.write("NO"); </script> Output : "YES" Time Complexity : O(n) Auxiliary Space : O(n)This article is contributed by Shashank Mishra ( Gullu ). 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. jit_t princiraj1992 divyesh072019 permutation Arrays Arrays permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Multidimensional Arrays in Java Introduction to Arrays Python | Using 2D arrays/lists the right way Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Queue | Set 1 (Introduction and Array Implementation) Find the Missing Number Subset Sum Problem | DP-25 Array of Strings in C++ (5 Different Ways to Create)
[ { "code": null, "e": 25324, "s": 25296, "text": "\n20 Apr, 2021" }, { "code": null, "e": 25624, "s": 25324, "text": "Given an array arr[] of size n>4, the task is to check whether the given array can be arranged in the form of Left or Right positioned array? Left or Right Positioned Array means each element in the array is equal to the number of elements to its left or number of elements to its right.Examples : " }, { "code": null, "e": 26198, "s": 25624, "text": "Input : arr[] = {1, 3, 3, 2}\nOutput : \"YES\" \nThis array has one such arrangement {3, 1, 2, 3}. \nIn this arrangement, first element '3' indicates \nthat three numbers are after it, the 2nd element \n'1' indicates that one number is before it, the \n3rd element '2' indicates that two elements are \nbefore it.\n\nInput : arr[] = {1, 6, 5, 4, 3, 2, 1}\nOutput: \"NO\"\n// No such arrangement is possible\n\nInput : arr[] = {2, 0, 1, 3}\nOutput: \"YES\"\n// Possible arrangement is {0, 1, 2, 3}\n\nInput : arr[] = {2, 1, 5, 2, 1, 5}\nOutput: \"YES\"\n// Possible arrangement is {5, 1, 2, 2, 1, 5}" }, { "code": null, "e": 26913, "s": 26200, "text": "A simple solution is to generate all possible arrangements (see this article) and check for the Left or Right Positioned Array condition, if each element in the array satisfies the condition then “YES” else “NO”. Time complexity for this approach is O(n*n! + n), n*n! to generate all arrangements and n for checking the condition using temporary array.An efficient solution for this problem needs little bit observation and pen-paper work. To satisfy the Left or Right Positioned Array condition all the numbers in the array should either be equal to index, i or (n-1-i) and arr[i] < n. So we create an visited[] array of size n and initialize its element with 0. Then we traverse array and follow given steps : " }, { "code": null, "e": 27071, "s": 26913, "text": "If visited[arr[i]] = 0 then make it 1, which checks for the condition that number of elements on the left side of array arr[0]...arr[i-1] is equal to arr[i]." }, { "code": null, "e": 27228, "s": 27071, "text": "Else make visited[n-arr[i]-1] = 1, which checks for the condition that number of elements on the right side of array arr[i+1]...arr[n-1] is equal to arr[i]." }, { "code": null, "e": 27361, "s": 27228, "text": "Now traverse visited[] array and if all the elements of visited[] array become 1 that means arrangement is possible “YES” else “NO”." }, { "code": null, "e": 27367, "s": 27363, "text": "C++" }, { "code": null, "e": 27372, "s": 27367, "text": "Java" }, { "code": null, "e": 27380, "s": 27372, "text": "Python3" }, { "code": null, "e": 27383, "s": 27380, "text": "C#" }, { "code": null, "e": 27387, "s": 27383, "text": "PHP" }, { "code": null, "e": 27398, "s": 27387, "text": "Javascript" }, { "code": "// C++ program to check if an array can be arranged// to left or right positioned array.#include<bits/stdc++.h>using namespace std; // Function to check Left or Right Positioned// Array.// arr[] is array of n elements// visited[] is boolean array of size nbool leftRight(int arr[],int n){ // Initially no element is placed at any position int visited[n] = {0}; // Traverse each element of array for (int i=0; i<n; i++) { // Element must be smaller than n. if (arr[i] < n) { // Place \"arr[i]\" at position \"i\" // or at position n-arr[i]-1 if (visited[arr[i]] == 0) visited[arr[i]] = 1; else visited[n-arr[i]-1] = 1; } } // All positions must be occupied for (int i=0; i<n; i++) if (visited[i] == 0) return false; return true;} // Driver program to test the caseint main(){ int arr[] = {2, 1, 5, 2, 1, 5}; int n = sizeof(arr)/sizeof(arr[0]); if (leftRight(arr, n) == true) cout << \"YES\"; else cout << \"NO\"; return 0;}", "e": 28492, "s": 27398, "text": null }, { "code": "// Java program to check if an array// can be arranged to left or// right positioned array. class GFG { // Function to check Left or // Right Positioned Array. // arr[] is array of n elements // visited[] is boolean array of size n static boolean leftRight(int arr[], int n) { // Initially no element is // placed at any position int visited[] = new int[n]; // Traverse each element of array for (int i = 0; i < n; i++) { // Element must be smaller than n. if (arr[i] < n) { // Place \"arr[i]\" at position \"i\" // or at position n-arr[i]-1 if (visited[arr[i]] == 0) visited[arr[i]] = 1; else visited[n - arr[i] - 1] = 1; } } // All positions must be occupied for (int i = 0; i < n; i++) if (visited[i] == 0) return false; return true;} // Driver codepublic static void main(String[] args){ int arr[] = {2, 1, 5, 2, 1, 5}; int n = arr.length; if (leftRight(arr, n) == true) System.out.print(\"YES\"); else System.out.print(\"NO\");}} // This code is contributed by Anant Agarwal.", "e": 29617, "s": 28492, "text": null }, { "code": "# Python3 program to check# if an array can be arranged# to left or right positioned array. # Function to check Left# or Right Positioned# Array.# arr[] is array of n elements# visited[] is boolean array of size ndef leftRight(arr,n): # Initially no element # is placed at any position visited=[] for i in range(n+1): visited.append(0) # Traverse each element of array for i in range(n): # Element must be smaller than n. if (arr[i] < n): # Place \"arr[i]\" at position \"i\" # or at position n-arr[i]-1 if (visited[arr[i]] == 0): visited[arr[i]] = 1 else: visited[n-arr[i]-1] = 1 # All positions must be occupied for i in range(n): if (visited[i] == 0): return False return True # Driver code arr = [2, 1, 5, 2, 1, 5]n = len(arr) if (leftRight(arr, n) == True): print(\"YES\")else: print(\"NO\") # This code is contributed# by Anant Agarwal.", "e": 30623, "s": 29617, "text": null }, { "code": " // C# program to check if an array// can be arranged to left or// right positioned array.using System;public class GFG { // Function to check Left or // Right Positioned Array. // arr[] is array of n elements // visited[] is boolean array of size n static bool leftRight(int []arr, int n) { // Initially no element is // placed at any position int []visited = new int[n]; // Traverse each element of array for (int i = 0; i < n; i++) { // Element must be smaller than n. if (arr[i] < n) { // Place \"arr[i]\" at position \"i\" // or at position n-arr[i]-1 if (visited[arr[i]] == 0) visited[arr[i]] = 1; else visited[n - arr[i] - 1] = 1; } } // All positions must be occupied for (int i = 0; i < n; i++) if (visited[i] == 0) return false; return true; } // Driver code public static void Main() { int []arr = {2, 1, 5, 2, 1, 5}; int n = arr.Length; if (leftRight(arr, n) == true) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); }}// This code is contributed by PrinciRaj1992", "e": 31874, "s": 30623, "text": null }, { "code": "<?php// PHP program to check if an// array can be arranged to// left or right positioned array. // Function to check Left or// Right Positioned Array.// arr[] is array of n elements// visited[] is boolean array of size nfunction leftRight($arr, $n){ // Initially no element is // placed at any position $visited[$n] = array(0); // Traverse each element of array for ($i = 0; $i < $n; $i++) { // Element must be smaller than n. if ($arr[$i] < $n) { // Place \"arr[i]\" at position \"i\" // or at position n-arr[i]-1 $visited[$arr[$i]] = 1; $visited[$n - $arr[$i] - 1] = 1; } } // All positions must be occupied for ($i = 0; $i < $n; $i++) if ($visited[$i] == 0) return false; return true;} // Driver Code$arr = array(2, 1, 5, 2, 1, 5);$n = sizeof($arr);if (leftRight($arr, $n) == true) echo \"YES\";else echo \"NO\"; // This code is contributed by ajit?>", "e": 32857, "s": 31874, "text": null }, { "code": "<script> // Javascript program to check if an array // can be arranged to left or // right positioned array. // Function to check Left or // Right Positioned Array. // arr[] is array of n elements // visited[] is boolean array of size n function leftRight(arr, n) { // Initially no element is // placed at any position let visited = new Array(n); // Traverse each element of array for (let i = 0; i < n; i++) { // Element must be smaller than n. if (arr[i] < n) { // Place \"arr[i]\" at position \"i\" // or at position n-arr[i]-1 if (visited[arr[i]] == 0) visited[arr[i]] = 1; else visited[n - arr[i] - 1] = 1; } } // All positions must be occupied for (let i = 0; i < n; i++) if (visited[i] == 0) return false; return true; } let arr = [2, 1, 5, 2, 1, 5]; let n = arr.length; if (leftRight(arr, n) == true) document.write(\"YES\"); else document.write(\"NO\"); </script>", "e": 34002, "s": 32857, "text": null }, { "code": null, "e": 34012, "s": 34002, "text": "Output : " }, { "code": null, "e": 34018, "s": 34012, "text": "\"YES\"" }, { "code": null, "e": 34497, "s": 34018, "text": "Time Complexity : O(n) Auxiliary Space : O(n)This article is contributed by Shashank Mishra ( Gullu ). 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": 34503, "s": 34497, "text": "jit_t" }, { "code": null, "e": 34517, "s": 34503, "text": "princiraj1992" }, { "code": null, "e": 34531, "s": 34517, "text": "divyesh072019" }, { "code": null, "e": 34543, "s": 34531, "text": "permutation" }, { "code": null, "e": 34550, "s": 34543, "text": "Arrays" }, { "code": null, "e": 34557, "s": 34550, "text": "Arrays" }, { "code": null, "e": 34569, "s": 34557, "text": "permutation" }, { "code": null, "e": 34667, "s": 34569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34735, "s": 34667, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34767, "s": 34735, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34790, "s": 34767, "text": "Introduction to Arrays" }, { "code": null, "e": 34835, "s": 34790, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 34856, "s": 34835, "text": "Linked List vs Array" }, { "code": null, "e": 34941, "s": 34856, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34995, "s": 34941, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 35019, "s": 34995, "text": "Find the Missing Number" }, { "code": null, "e": 35046, "s": 35019, "text": "Subset Sum Problem | DP-25" } ]
Check if a string contains only alphabets in Java using Lambda expression
Let’s say our string is − String str = "Amit123"; Now, using allMatch() method, get the boolean result whether the string has only alphabets or now − boolean result = str.chars().allMatch(Character::isLetter); Following is an example to check if a string contains only alphabets using Lambda Expressions − class Main { public static void main(String[] args) { String str = "Amit123"; boolean result = str.chars().allMatch(Character::isLetter); System.out.println("String contains only alphabets? = "+result); } } Let us see another example with a different input − String contains only alphabets? = false class Main { public static void main(String[] args) { String str = "Jacob"; boolean result = str.chars().allMatch(Character::isLetter); System.out.println("String contains only alphabets? = "+result); } } String contains only alphabets? = true
[ { "code": null, "e": 1088, "s": 1062, "text": "Let’s say our string is −" }, { "code": null, "e": 1112, "s": 1088, "text": "String str = \"Amit123\";" }, { "code": null, "e": 1212, "s": 1112, "text": "Now, using allMatch() method, get the boolean result whether the string has only alphabets or now −" }, { "code": null, "e": 1272, "s": 1212, "text": "boolean result = str.chars().allMatch(Character::isLetter);" }, { "code": null, "e": 1368, "s": 1272, "text": "Following is an example to check if a string contains only alphabets using Lambda Expressions −" }, { "code": null, "e": 1599, "s": 1368, "text": "class Main {\n public static void main(String[] args) {\n String str = \"Amit123\";\n boolean result = str.chars().allMatch(Character::isLetter);\n System.out.println(\"String contains only alphabets? = \"+result);\n }\n}" }, { "code": null, "e": 1651, "s": 1599, "text": "Let us see another example with a different input −" }, { "code": null, "e": 1691, "s": 1651, "text": "String contains only alphabets? = false" }, { "code": null, "e": 1920, "s": 1691, "text": "class Main {\n public static void main(String[] args) {\n String str = \"Jacob\";\n boolean result = str.chars().allMatch(Character::isLetter);\n System.out.println(\"String contains only alphabets? = \"+result);\n }\n}" }, { "code": null, "e": 1959, "s": 1920, "text": "String contains only alphabets? = true" } ]
gzip.compress(s) in Python - GeeksforGeeks
23 Mar, 2020 With the help of gzip.compress(s) method, we can get compress the bytes of string by using gzip.compress(s) method. Syntax : gzip.compress(string)Return : Return compressed string. Example #1 :In this example we can see that by using gzip.compress(s) method, we are able to compress the string in the byte format by using this method. # import gzip and compressimport gzip s = b'This is GFG author, and final year student.'print(len(s)) # using gzip.compress(s) methodt = gzip.compress(s)print(len(t)) Output : 4361 Example #2 : # import gzip and compressimport gzip s = b'GeeksForGeeks@12345678'print(len(s)) # using gzip.compress(s) methodt = gzip.compress(s)print(len(t)) Output : 2239 Python-gzip Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n23 Mar, 2020" }, { "code": null, "e": 24017, "s": 23901, "text": "With the help of gzip.compress(s) method, we can get compress the bytes of string by using gzip.compress(s) method." }, { "code": null, "e": 24082, "s": 24017, "text": "Syntax : gzip.compress(string)Return : Return compressed string." }, { "code": null, "e": 24236, "s": 24082, "text": "Example #1 :In this example we can see that by using gzip.compress(s) method, we are able to compress the string in the byte format by using this method." }, { "code": "# import gzip and compressimport gzip s = b'This is GFG author, and final year student.'print(len(s)) # using gzip.compress(s) methodt = gzip.compress(s)print(len(t))", "e": 24405, "s": 24236, "text": null }, { "code": null, "e": 24414, "s": 24405, "text": "Output :" }, { "code": null, "e": 24419, "s": 24414, "text": "4361" }, { "code": null, "e": 24432, "s": 24419, "text": "Example #2 :" }, { "code": "# import gzip and compressimport gzip s = b'GeeksForGeeks@12345678'print(len(s)) # using gzip.compress(s) methodt = gzip.compress(s)print(len(t))", "e": 24580, "s": 24432, "text": null }, { "code": null, "e": 24589, "s": 24580, "text": "Output :" }, { "code": null, "e": 24594, "s": 24589, "text": "2239" }, { "code": null, "e": 24606, "s": 24594, "text": "Python-gzip" }, { "code": null, "e": 24613, "s": 24606, "text": "Python" }, { "code": null, "e": 24711, "s": 24613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24720, "s": 24711, "text": "Comments" }, { "code": null, "e": 24733, "s": 24720, "text": "Old Comments" }, { "code": null, "e": 24769, "s": 24733, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 24792, "s": 24769, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 24831, "s": 24792, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 24864, "s": 24831, "text": "Python | Convert set into a list" }, { "code": null, "e": 24913, "s": 24864, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 24954, "s": 24913, "text": "Python - Call function from another file" }, { "code": null, "e": 24970, "s": 24954, "text": "loops in python" }, { "code": null, "e": 25021, "s": 24970, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 25053, "s": 25021, "text": "Python Dictionary keys() method" } ]
How to Execute Native Shell Commands from Java Program? - GeeksforGeeks
03 Mar, 2021 A shell command is a command that we can trigger using a keyboard and a command-line or a shell instead of a Graphical user interface. Usually, we would trigger shell commands manually. However, there can be instances where this needs to be done programmatically through Java. Java provides support to run native shell commands with two classes: RunTime and ProcessBuilder. The main disadvantage of using these classes and running shell commands from inside a Java Program is Java loses its portability. What does losing portability mean? Java goes by the principle “compile once, run anywhere.” This means that a Java program written and compiled on one operating system can run on any other operating system without making any changes. When we use either the ProcessBuilder or the Runtime classes to run Native shell commands, we make the Java program dependent on the underlying operating system. For example, a Java program running specifically Linux shell commands cannot run as-is on a Windows machine mainly because Windows has a different folder structure and shell commands. Examples: The first three examples will look at implementing the ProcessBuilder class to run shell commands in Java. The following example is for the RunTime class. Example 1: Loss of portability. This example shows what happens if we execute a Java program meant for the Linux/Unix operating system on a Windows operating system. Java // if we execute a Java program meant for the Linux/Unix// operating system on a Windows operating systemimport java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader; public class ShellCommandRunner4 { public static void main(String[] args) { try { System.out.println( System.getProperty("os.name")); System.out.println(); // This process cannot be run on Windows. So the // program will throw an exception. ProcessBuilder pb = new ProcessBuilder("sh", "-c", "ls"); // Exception thrown here because folder // structure of Windows and Linux are different. pb.directory( new File(System.getProperty("user.home"))); // It will throw and exception Process process = pb.start(); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line + "\n"); } int exitVal = process.waitFor(); if (exitVal == 0) { System.out.println( "**************************** The Output is ******************************"); System.out.println(output); System.exit(0); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }} The output of the above program when run on a Windows machine. Example 2: Run a simple shell command This example shows how to run a simple Windows shell command. We use a list to build commands and then execute them using the “start” method of the ProcessBuilder class. The program runs the command to find the chrome browser processes from the tasklist running in the machine. Java // Run a simple Windows shell commandimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List; public class ShellCommandRunner { public static void main(String[] args) { ProcessBuilder processBuilder = new ProcessBuilder(); List<String> builderList = new ArrayList<>(); // add the list of commands to a list builderList.add("cmd.exe"); builderList.add("/C"); builderList.add("tasklist | findstr chrome"); try { // Using the list , trigger the command processBuilder.command(builderList); Process process = processBuilder.start(); // To read the output list BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } int exitCode = process.waitFor(); System.out.println("\nExited with error code : " + exitCode); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }} Chrome browser processes. Example 3: Run a bat file This example shows how to run a simple .bat program in the Java console. The .bat file displays the windows system information. Java // Run a simple .bat program in the Java consoleimport java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader; public class ShellCommandRunner3 { public static void main(String[] args) { try { // File location for the bat script File dir = new File("D:\\bat_scripts"); // Command to run the bat file in the same // console ProcessBuilder pb = new ProcessBuilder( "cmd.exe", "/C", "sysinfo.bat"); pb.directory(dir); Process process = pb.start(); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line + "\n"); } int exitVal = process.waitFor(); if (exitVal == 0) { System.out.println( "**************************** The Output is ******************************"); System.out.println(output); System.exit(0); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }} System info bat file program output Example 4:Run a shell command using the RunTime class. This example shows how to run a simple command using the RunTime class. We use the exec() method of the Runtime class. Java // Run a simple command using the RunTime classimport java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader; public class ShellCommandRunner2 { public static void main(String[] args) { try { Process process = Runtime.getRuntime().exec("where java"); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line + "\n"); } int exitVal = process.waitFor(); if (exitVal == 0) { System.out.println( "**************************** The Output is ******************************"); System.out.println(output); System.exit(0); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }} where java in Java program Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23948, "s": 23920, "text": "\n03 Mar, 2021" }, { "code": null, "e": 24225, "s": 23948, "text": "A shell command is a command that we can trigger using a keyboard and a command-line or a shell instead of a Graphical user interface. Usually, we would trigger shell commands manually. However, there can be instances where this needs to be done programmatically through Java." }, { "code": null, "e": 24452, "s": 24225, "text": "Java provides support to run native shell commands with two classes: RunTime and ProcessBuilder. The main disadvantage of using these classes and running shell commands from inside a Java Program is Java loses its portability." }, { "code": null, "e": 24487, "s": 24452, "text": "What does losing portability mean?" }, { "code": null, "e": 24687, "s": 24487, "text": "Java goes by the principle “compile once, run anywhere.” This means that a Java program written and compiled on one operating system can run on any other operating system without making any changes. " }, { "code": null, "e": 25033, "s": 24687, "text": "When we use either the ProcessBuilder or the Runtime classes to run Native shell commands, we make the Java program dependent on the underlying operating system. For example, a Java program running specifically Linux shell commands cannot run as-is on a Windows machine mainly because Windows has a different folder structure and shell commands." }, { "code": null, "e": 25043, "s": 25033, "text": "Examples:" }, { "code": null, "e": 25198, "s": 25043, "text": "The first three examples will look at implementing the ProcessBuilder class to run shell commands in Java. The following example is for the RunTime class." }, { "code": null, "e": 25230, "s": 25198, "text": "Example 1: Loss of portability." }, { "code": null, "e": 25366, "s": 25230, "text": "This example shows what happens if we execute a Java program meant for the Linux/Unix operating system on a Windows operating system. " }, { "code": null, "e": 25371, "s": 25366, "text": "Java" }, { "code": "// if we execute a Java program meant for the Linux/Unix// operating system on a Windows operating systemimport java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader; public class ShellCommandRunner4 { public static void main(String[] args) { try { System.out.println( System.getProperty(\"os.name\")); System.out.println(); // This process cannot be run on Windows. So the // program will throw an exception. ProcessBuilder pb = new ProcessBuilder(\"sh\", \"-c\", \"ls\"); // Exception thrown here because folder // structure of Windows and Linux are different. pb.directory( new File(System.getProperty(\"user.home\"))); // It will throw and exception Process process = pb.start(); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line + \"\\n\"); } int exitVal = process.waitFor(); if (exitVal == 0) { System.out.println( \"**************************** The Output is ******************************\"); System.out.println(output); System.exit(0); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }}", "e": 27065, "s": 25371, "text": null }, { "code": null, "e": 27128, "s": 27065, "text": "The output of the above program when run on a Windows machine." }, { "code": null, "e": 27166, "s": 27128, "text": "Example 2: Run a simple shell command" }, { "code": null, "e": 27444, "s": 27166, "text": "This example shows how to run a simple Windows shell command. We use a list to build commands and then execute them using the “start” method of the ProcessBuilder class. The program runs the command to find the chrome browser processes from the tasklist running in the machine." }, { "code": null, "e": 27449, "s": 27444, "text": "Java" }, { "code": "// Run a simple Windows shell commandimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List; public class ShellCommandRunner { public static void main(String[] args) { ProcessBuilder processBuilder = new ProcessBuilder(); List<String> builderList = new ArrayList<>(); // add the list of commands to a list builderList.add(\"cmd.exe\"); builderList.add(\"/C\"); builderList.add(\"tasklist | findstr chrome\"); try { // Using the list , trigger the command processBuilder.command(builderList); Process process = processBuilder.start(); // To read the output list BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } int exitCode = process.waitFor(); System.out.println(\"\\nExited with error code : \" + exitCode); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }}", "e": 28804, "s": 27449, "text": null }, { "code": null, "e": 28830, "s": 28804, "text": "Chrome browser processes." }, { "code": null, "e": 28856, "s": 28830, "text": "Example 3: Run a bat file" }, { "code": null, "e": 28985, "s": 28856, "text": "This example shows how to run a simple .bat program in the Java console. The .bat file displays the windows system information. " }, { "code": null, "e": 28990, "s": 28985, "text": "Java" }, { "code": "// Run a simple .bat program in the Java consoleimport java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader; public class ShellCommandRunner3 { public static void main(String[] args) { try { // File location for the bat script File dir = new File(\"D:\\\\bat_scripts\"); // Command to run the bat file in the same // console ProcessBuilder pb = new ProcessBuilder( \"cmd.exe\", \"/C\", \"sysinfo.bat\"); pb.directory(dir); Process process = pb.start(); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line + \"\\n\"); } int exitVal = process.waitFor(); if (exitVal == 0) { System.out.println( \"**************************** The Output is ******************************\"); System.out.println(output); System.exit(0); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }}", "e": 30387, "s": 28990, "text": null }, { "code": null, "e": 30423, "s": 30387, "text": "System info bat file program output" }, { "code": null, "e": 30478, "s": 30423, "text": "Example 4:Run a shell command using the RunTime class." }, { "code": null, "e": 30597, "s": 30478, "text": "This example shows how to run a simple command using the RunTime class. We use the exec() method of the Runtime class." }, { "code": null, "e": 30602, "s": 30597, "text": "Java" }, { "code": "// Run a simple command using the RunTime classimport java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader; public class ShellCommandRunner2 { public static void main(String[] args) { try { Process process = Runtime.getRuntime().exec(\"where java\"); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line + \"\\n\"); } int exitVal = process.waitFor(); if (exitVal == 0) { System.out.println( \"**************************** The Output is ******************************\"); System.out.println(output); System.exit(0); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }}", "e": 31745, "s": 30602, "text": null }, { "code": null, "e": 31772, "s": 31745, "text": "where java in Java program" }, { "code": null, "e": 31779, "s": 31772, "text": "Picked" }, { "code": null, "e": 31803, "s": 31779, "text": "Technical Scripter 2020" }, { "code": null, "e": 31808, "s": 31803, "text": "Java" }, { "code": null, "e": 31822, "s": 31808, "text": "Java Programs" }, { "code": null, "e": 31841, "s": 31822, "text": "Technical Scripter" }, { "code": null, "e": 31846, "s": 31841, "text": "Java" }, { "code": null, "e": 31944, "s": 31846, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31959, "s": 31944, "text": "Stream In Java" }, { "code": null, "e": 32005, "s": 31959, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 32026, "s": 32005, "text": "Constructors in Java" }, { "code": null, "e": 32045, "s": 32026, "text": "Exceptions in Java" }, { "code": null, "e": 32062, "s": 32045, "text": "Generics in Java" }, { "code": null, "e": 32106, "s": 32062, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 32132, "s": 32106, "text": "Java Programming Examples" }, { "code": null, "e": 32166, "s": 32132, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 32213, "s": 32166, "text": "Implementing a Linked List in Java using Class" } ]
HTML Tables with Fixed Header on Scroll in CSS
By setting postion: sticky and top: 0, we can create a fixed header on a scroll in HTML tables. The following examples give us an idea of how to implement this − Live Demo <!DOCTYPE html> <html> <head> <style> div { color: white; display: flex; padding: 2%; background-color: rgba(190,155,150); height: 135px; overflow-y: scroll; } td,th,p { text-align: center; font-size: 1.25em; } table { padding: 3%; border-collapse: collapse; border: 2px ridge green; } th { top: 0; position: sticky; background: #e5d2f1; color: black; } </style> </head> <body> <div> <table> <thead> <tr> <th>A </th> <th>B </th> <th>C </th> <th>D </th> <th>E </th> </tr> </thead> <tr> <td>Hey</td> <td>Hey</td> <td>Hey</td> <td>Hey</td> <td>Hey</td> </tr> <tr> <td>Demo</td> <td>Demo</td> <td>Demo</td> <td>Demo</td> <td>Demo</td> </tr> <tr> <td>Yo</td> <td>Yo</td> <td>Yo</td> <td>Yo</td> <td>Yo</td> </tr> <tr> <td>Demo</td> <td>Demo</td> <td>Demo</td> <td>Demo</td> <td>Demo</td> </tr> </table> <p> Duis tincidunt fermentum ipsum vel sagittis. Sed ultrices quis dui ut rutrum. Quisque et varius tellus, ut vestibulum purus. Etiam in erat fringilla, laoreet libero eu, facilisis ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Duis eu ornare augue, ut facilisis odio. </p> </div> </body> </html> This will produce the following result − Live Demo <!DOCTYPE html> <html> <head> <style> div { padding: 2%; height: 40px; overflow-y: scroll; box-shadow: inset 0 0 12px lightgreen; } tr th { background: #25f2f1; } table { text-align: center; position: relative; border-collapse: separated; width: 100%; } th { top: 0; position: sticky; background: white; } </style> </head> <body> <div> <table> <thead> <tr> <th>A </th> <th>B </th> <th>C </th> <th>D </th> <th>E </th> </tr> </thead> <tr> <td>Hey</td> <td>Hey</td> <td>Hey</td> <td>Hey</td> <td>Hey</td> </tr> <tr> <td>Demo</td> <td>Demo</td> <td>Demo</td> <td>Demo</td> <td>Demo</td> </tr> <tr> <td>Yo</td> <td>Yo</td> <td>Yo</td> <td>Yo</td> <td>Yo</td> </tr> <tr> <td>Demo</td> <td>Demo</td> <td>Demo</td> <td>Demo</td> <td>Demo</td> </tr> </table> </div> </body> </html> This will produce the following result −
[ { "code": null, "e": 1158, "s": 1062, "text": "By setting postion: sticky and top: 0, we can create a fixed header on a scroll in HTML tables." }, { "code": null, "e": 1224, "s": 1158, "text": "The following examples give us an idea of how to implement this −" }, { "code": null, "e": 1235, "s": 1224, "text": " Live Demo" }, { "code": null, "e": 2424, "s": 1235, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n color: white;\n display: flex;\n padding: 2%;\n background-color: rgba(190,155,150);\n height: 135px;\n overflow-y: scroll;\n}\ntd,th,p {\n text-align: center;\n font-size: 1.25em;\n}\ntable {\n padding: 3%;\n border-collapse: collapse;\n border: 2px ridge green;\n}\nth {\n top: 0;\n position: sticky;\n background: #e5d2f1;\n color: black;\n}\n</style>\n</head>\n<body>\n<div>\n<table>\n<thead>\n<tr>\n<th>A </th>\n<th>B </th>\n<th>C </th>\n<th>D </th>\n<th>E </th>\n</tr>\n</thead>\n<tr>\n<td>Hey</td>\n<td>Hey</td>\n<td>Hey</td>\n<td>Hey</td>\n<td>Hey</td>\n</tr>\n<tr>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n</tr>\n<tr>\n<td>Yo</td>\n<td>Yo</td>\n<td>Yo</td>\n<td>Yo</td>\n<td>Yo</td>\n</tr>\n<tr>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n</tr>\n</table>\n<p>\nDuis tincidunt fermentum ipsum vel sagittis. Sed ultrices quis dui ut rutrum. Quisque et varius tellus, ut vestibulum purus. Etiam in erat fringilla, laoreet libero eu, facilisis ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Duis eu ornare augue, ut facilisis odio.\n</p>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2465, "s": 2424, "text": "This will produce the following result −" }, { "code": null, "e": 2476, "s": 2465, "text": " Live Demo" }, { "code": null, "e": 3285, "s": 2476, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n padding: 2%;\n height: 40px;\n overflow-y: scroll;\n box-shadow: inset 0 0 12px lightgreen;\n}\ntr th {\n background: #25f2f1;\n}\ntable {\n text-align: center;\n position: relative;\n border-collapse: separated;\n width: 100%;\n}\nth {\n top: 0;\n position: sticky;\n background: white;\n}\n</style>\n</head>\n<body>\n<div>\n<table>\n<thead>\n<tr>\n<th>A </th>\n<th>B </th>\n<th>C </th>\n<th>D </th>\n<th>E </th>\n</tr>\n</thead>\n<tr>\n<td>Hey</td>\n<td>Hey</td>\n<td>Hey</td>\n<td>Hey</td>\n<td>Hey</td>\n</tr>\n<tr>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n</tr>\n<tr>\n<td>Yo</td>\n<td>Yo</td>\n<td>Yo</td>\n<td>Yo</td>\n<td>Yo</td>\n</tr>\n<tr>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n<td>Demo</td>\n</tr>\n</table>\n</div>\n</body>\n</html>" }, { "code": null, "e": 3326, "s": 3285, "text": "This will produce the following result −" } ]
How to create a MySQL table with indexes?
To create a MySQL table with indexes, the syntax is as follows − create table yourTableName ( yourColumnName1 dataType, yourColumnName2 dataType . . . N ); create index yourIndexName1 on(yourColumnName1 ); create index yourIndexName2 on(yourColumnName2 ); Let us first create a table − mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.63 sec) Here is the query to create indexes with table − mysql> create index id_index on DemoTable(Id); Query OK, 0 rows affected (0.36 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> create index Name_index on DemoTable(Name); Query OK, 0 rows affected (0.38 sec) Records: 0 Duplicates: 0 Warnings: 0 Now you can check the structure of table − mysql> show create table DemoTable; This will produce the following output − +---------------+-----------------------------------------------------------------------------------------+ | Table | Create Table | +---------------+-----------------------------------------------------------------------------------------+ | DemoTable | CREATE TABLE `DemoTable` ( `Id` int(11) DEFAULT NULL, `Name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, KEY `id_index` (`Id`), KEY `Name_index` (`Name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci | +---------------+------------------------------------------------------------------------------------------+ 1 row in set (0.05 sec)
[ { "code": null, "e": 1127, "s": 1062, "text": "To create a MySQL table with indexes, the syntax is as follows −" }, { "code": null, "e": 1318, "s": 1127, "text": "create table yourTableName\n(\nyourColumnName1 dataType,\nyourColumnName2 dataType\n.\n.\n.\nN\n);\ncreate index yourIndexName1 on(yourColumnName1 );\ncreate index yourIndexName2 on(yourColumnName2 );" }, { "code": null, "e": 1348, "s": 1318, "text": "Let us first create a table −" }, { "code": null, "e": 1469, "s": 1348, "text": "mysql> create table DemoTable\n -> (\n -> Id int,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.63 sec)" }, { "code": null, "e": 1518, "s": 1469, "text": "Here is the query to create indexes with table −" }, { "code": null, "e": 1764, "s": 1518, "text": "mysql> create index id_index on DemoTable(Id);\nQuery OK, 0 rows affected (0.36 sec)\nRecords: 0 Duplicates: 0 Warnings: 0\nmysql> create index Name_index on DemoTable(Name);\nQuery OK, 0 rows affected (0.38 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1807, "s": 1764, "text": "Now you can check the structure of table −" }, { "code": null, "e": 1843, "s": 1807, "text": "mysql> show create table DemoTable;" }, { "code": null, "e": 1884, "s": 1843, "text": "This will produce the following output −" }, { "code": null, "e": 2669, "s": 1884, "text": "+---------------+-----------------------------------------------------------------------------------------+\n| Table | Create Table | \n+---------------+-----------------------------------------------------------------------------------------+\n| DemoTable | CREATE TABLE `DemoTable` ( `Id` int(11) DEFAULT NULL, `Name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, KEY `id_index` (`Id`), KEY `Name_index` (`Name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |\n+---------------+------------------------------------------------------------------------------------------+\n1 row in set (0.05 sec)" } ]
Count occurrences of a word in string - GeeksforGeeks
06 Oct, 2021 You are given a string and a word your task is that count the number of the occurrence of the given word in the string and print the number of occurrences of the word. Examples: Input : string = "GeeksforGeeks A computer science portal for geeks" word = "portal" Output : Occurrences of Word = 1 Time Input : string = "GeeksforGeeks A computer science portal for geeks" word = "technical" Output : Occurrences of Word = 0 Time Approach: First, we split the string by spaces in a Then, take a variable count = 0 and in every true condition we increment the count by 1 Now run a loop at 0 to length of string and check if our string is equal to the word if condition is true then we increment the value of count by 1 and in the end, we print the value of count. Below is the implementation of the above approach : C++ Java Python 3 C# PHP Javascript // C++ program to count the number// of occurrence of a word in// the given string#include <bits/stdc++.h>using namespace std; int countOccurrences(char *str, string word){ char *p; // split the string by spaces in a vector<string> a; p = strtok(str, " "); while (p != NULL) { a.push_back(p); p = strtok(NULL, " "); } // search for pattern in a int c = 0; for (int i = 0; i < a.size(); i++) // if match found increase count if (word == a[i]) c++; return c;} // Driver codeint main(){ char str[] = "GeeksforGeeks A computer science portal for geeks "; string word = "portal"; cout << countOccurrences(str, word); return 0;} // This code is contributed by// sanjeev2552 // Java program to count the number// of occurrence of a word in// the given stringimport java.io.*; class GFG { static int countOccurrences(String str, String word){ // split the string by spaces in a String a[] = str.split(" "); // search for pattern in a int count = 0; for (int i = 0; i < a.length; i++) { // if match found increase count if (word.equals(a[i])) count++; } return count;} // Driver codepublic static void main(String args[]){ String str = "GeeksforGeeks A computer science portal for geeks "; String word = "portal"; System.out.println(countOccurrences(str, word));}} /*This code is contributed by Nikita Tiwari.*/ # Python program to count the number of occurrence# of a word in the given string def countOccurrences(str, word): # split the string by spaces in a a = str.split(" ") # search for pattern in a count = 0 for i in range(0, len(a)): # if match found increase count if (word == a[i]): count = count + 1 return count # Driver codestr ="GeeksforGeeks A computer science portal for geeks "word ="portal"print(countOccurrences(str, word)) // C# program to count the number// of occurrence of a word in// the given stringusing System; class GFG{static int countOccurrences(string str, string word){ // split the string by spaces string[] a = str.Split(' '); // search for pattern in string int count = 0; for (int i = 0; i < a.Length; i++) { // if match found increase count if (word.Equals(a[i])) count++; } return count;} // Driver codepublic static void Main(){ string str = "GeeksforGeeks A computer science portal for geeks "; string word = "portal"; Console.Write(countOccurrences(str, word));}} // This code is contributed// by ChitraNayal <?php// PHP program to count the number// of occurrence of a word in// the given string function countOccurrences($str, $word){ // split the string by spaces $a = explode(" ", $str); // search for pattern in string $count = 0; for ($i = 0; $i < sizeof($a); $i++) { // if match found increase count if ($word == $a[$i]) $count++; } return $count;} // Driver code$str = "GeeksforGeeks A computer science portal for geeks ";$word = "portal";echo (countOccurrences($str, $word)); // This code is contributed// by ChitraNayal?> <script> // Javascript program to count the number// of occurrence of a word in// the given string function countOccurrences(str,word) { // split the string by spaces in a let a = str.split(" "); // search for pattern in a let count = 0; for (let i = 0; i < a.length; i++) { // if match found increase count if (word==(a[i])) count++; } return count; } // Driver code let str = "GeeksforGeeks A computer science portal for geeks "; let word = "portal"; document.write(countOccurrences(str, word)); // This code is contributed by avanitrachhadiya2155 </script> Output: 1 First, we split the string by spaces and store in list. We use count() to find count of that word in list. Below is the implementation: Python3 # Python program to count the number of occurrence# of a word in the given stringdef countOccurrences(str, word): wordslist = list(str.split()) return wordslist.count(word) # Driver codestr = "GeeksforGeeks A computer science portal for geeks "word = "portal"print(countOccurrences(str, word)) # This code is contributed by vikkycirus 1 YouTubeGeeksforGeeks502K subscribersCount occurences of a word in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:02•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=AFj5gEmjimE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Reference : split function python ukasp sanjeev2552 vikkycirus avanitrachhadiya2155 saurabh1990aror CoderSaty Python Strings Technical Scripter Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25028, "s": 25000, "text": "\n06 Oct, 2021" }, { "code": null, "e": 25207, "s": 25028, "text": "You are given a string and a word your task is that count the number of the occurrence of the given word in the string and print the number of occurrences of the word. Examples: " }, { "code": null, "e": 25458, "s": 25207, "text": "Input : string = \"GeeksforGeeks A computer science portal for geeks\"\nword = \"portal\"\nOutput : Occurrences of Word = 1 Time\n\nInput : string = \"GeeksforGeeks A computer science portal for geeks\"\nword = \"technical\" \nOutput : Occurrences of Word = 0 Time" }, { "code": null, "e": 25468, "s": 25458, "text": "Approach:" }, { "code": null, "e": 25510, "s": 25468, "text": "First, we split the string by spaces in a" }, { "code": null, "e": 25598, "s": 25510, "text": "Then, take a variable count = 0 and in every true condition we increment the count by 1" }, { "code": null, "e": 25683, "s": 25598, "text": "Now run a loop at 0 to length of string and check if our string is equal to the word" }, { "code": null, "e": 25791, "s": 25683, "text": "if condition is true then we increment the value of count by 1 and in the end, we print the value of count." }, { "code": null, "e": 25844, "s": 25791, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 25848, "s": 25844, "text": "C++" }, { "code": null, "e": 25853, "s": 25848, "text": "Java" }, { "code": null, "e": 25862, "s": 25853, "text": "Python 3" }, { "code": null, "e": 25865, "s": 25862, "text": "C#" }, { "code": null, "e": 25869, "s": 25865, "text": "PHP" }, { "code": null, "e": 25880, "s": 25869, "text": "Javascript" }, { "code": "// C++ program to count the number// of occurrence of a word in// the given string#include <bits/stdc++.h>using namespace std; int countOccurrences(char *str, string word){ char *p; // split the string by spaces in a vector<string> a; p = strtok(str, \" \"); while (p != NULL) { a.push_back(p); p = strtok(NULL, \" \"); } // search for pattern in a int c = 0; for (int i = 0; i < a.size(); i++) // if match found increase count if (word == a[i]) c++; return c;} // Driver codeint main(){ char str[] = \"GeeksforGeeks A computer science portal for geeks \"; string word = \"portal\"; cout << countOccurrences(str, word); return 0;} // This code is contributed by// sanjeev2552", "e": 26655, "s": 25880, "text": null }, { "code": "// Java program to count the number// of occurrence of a word in// the given stringimport java.io.*; class GFG { static int countOccurrences(String str, String word){ // split the string by spaces in a String a[] = str.split(\" \"); // search for pattern in a int count = 0; for (int i = 0; i < a.length; i++) { // if match found increase count if (word.equals(a[i])) count++; } return count;} // Driver codepublic static void main(String args[]){ String str = \"GeeksforGeeks A computer science portal for geeks \"; String word = \"portal\"; System.out.println(countOccurrences(str, word));}} /*This code is contributed by Nikita Tiwari.*/", "e": 27338, "s": 26655, "text": null }, { "code": "# Python program to count the number of occurrence# of a word in the given string def countOccurrences(str, word): # split the string by spaces in a a = str.split(\" \") # search for pattern in a count = 0 for i in range(0, len(a)): # if match found increase count if (word == a[i]): count = count + 1 return count # Driver codestr =\"GeeksforGeeks A computer science portal for geeks \"word =\"portal\"print(countOccurrences(str, word))", "e": 27846, "s": 27338, "text": null }, { "code": "// C# program to count the number// of occurrence of a word in// the given stringusing System; class GFG{static int countOccurrences(string str, string word){ // split the string by spaces string[] a = str.Split(' '); // search for pattern in string int count = 0; for (int i = 0; i < a.Length; i++) { // if match found increase count if (word.Equals(a[i])) count++; } return count;} // Driver codepublic static void Main(){ string str = \"GeeksforGeeks A computer science portal for geeks \"; string word = \"portal\"; Console.Write(countOccurrences(str, word));}} // This code is contributed// by ChitraNayal", "e": 28536, "s": 27846, "text": null }, { "code": "<?php// PHP program to count the number// of occurrence of a word in// the given string function countOccurrences($str, $word){ // split the string by spaces $a = explode(\" \", $str); // search for pattern in string $count = 0; for ($i = 0; $i < sizeof($a); $i++) { // if match found increase count if ($word == $a[$i]) $count++; } return $count;} // Driver code$str = \"GeeksforGeeks A computer science portal for geeks \";$word = \"portal\";echo (countOccurrences($str, $word)); // This code is contributed// by ChitraNayal?>", "e": 29107, "s": 28536, "text": null }, { "code": "<script> // Javascript program to count the number// of occurrence of a word in// the given string function countOccurrences(str,word) { // split the string by spaces in a let a = str.split(\" \"); // search for pattern in a let count = 0; for (let i = 0; i < a.length; i++) { // if match found increase count if (word==(a[i])) count++; } return count; } // Driver code let str = \"GeeksforGeeks A computer science portal for geeks \"; let word = \"portal\"; document.write(countOccurrences(str, word)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 29758, "s": 29107, "text": null }, { "code": null, "e": 29767, "s": 29758, "text": "Output: " }, { "code": null, "e": 29769, "s": 29767, "text": "1" }, { "code": null, "e": 29825, "s": 29769, "text": "First, we split the string by spaces and store in list." }, { "code": null, "e": 29876, "s": 29825, "text": "We use count() to find count of that word in list." }, { "code": null, "e": 29905, "s": 29876, "text": "Below is the implementation:" }, { "code": null, "e": 29913, "s": 29905, "text": "Python3" }, { "code": "# Python program to count the number of occurrence# of a word in the given stringdef countOccurrences(str, word): wordslist = list(str.split()) return wordslist.count(word) # Driver codestr = \"GeeksforGeeks A computer science portal for geeks \"word = \"portal\"print(countOccurrences(str, word)) # This code is contributed by vikkycirus", "e": 30257, "s": 29913, "text": null }, { "code": null, "e": 30259, "s": 30257, "text": "1" }, { "code": null, "e": 31096, "s": 30259, "text": "YouTubeGeeksforGeeks502K subscribersCount occurences of a word in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:02•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=AFj5gEmjimE\" 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": 31131, "s": 31096, "text": "Reference : split function python " }, { "code": null, "e": 31137, "s": 31131, "text": "ukasp" }, { "code": null, "e": 31149, "s": 31137, "text": "sanjeev2552" }, { "code": null, "e": 31160, "s": 31149, "text": "vikkycirus" }, { "code": null, "e": 31181, "s": 31160, "text": "avanitrachhadiya2155" }, { "code": null, "e": 31197, "s": 31181, "text": "saurabh1990aror" }, { "code": null, "e": 31207, "s": 31197, "text": "CoderSaty" }, { "code": null, "e": 31214, "s": 31207, "text": "Python" }, { "code": null, "e": 31222, "s": 31214, "text": "Strings" }, { "code": null, "e": 31241, "s": 31222, "text": "Technical Scripter" }, { "code": null, "e": 31249, "s": 31241, "text": "Strings" }, { "code": null, "e": 31347, "s": 31249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31365, "s": 31347, "text": "Python Dictionary" }, { "code": null, "e": 31400, "s": 31365, "text": "Read a file line by line in Python" }, { "code": null, "e": 31422, "s": 31400, "text": "Enumerate() in Python" }, { "code": null, "e": 31454, "s": 31422, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31484, "s": 31454, "text": "Iterate over a list in Python" }, { "code": null, "e": 31509, "s": 31484, "text": "Reverse a string in Java" }, { "code": null, "e": 31555, "s": 31509, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31589, "s": 31555, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 31649, "s": 31589, "text": "Write a program to print all permutations of a given string" } ]
wxPython - GridBagSizer
GridBagSizer is a versatile sizer. It offers more enhancements than FlexiGridSizer. Child widget can be added to a specific cell within the grid. Furthermore, a child widget can occupy more than one cell horizontally and/or vertically. Hence, a static text and multiline text control in the same row can have different width and height. Gridbag layout should be meticulously planned by deciding the position, span and the gap. wx.GridBagSizer class has only one constructor taking two arguments. Wx.GridBagSizer(vgap,hgap) The most important method of GridBagsizer class is Add() which takes position as the mandatory argument. Span, alignment, border flags, and border size parameters are optional. If not explicitly used they assume default values. Wx.GridbagSizer().Add(control, pos, span, flags, border) The following table lists the methods of GridBagSizer class − Add() Adds given control at the specified position in the grid GetItemPosition() Returns the position of control in the grid SetItemPosition() Places a control at the specified position in the grid GetItemSpan() Returns row/column spanning of an item SetItemSpan() Spans the specified item over the number of rows/columns The following code displays a form in which there are labels (StaticText) associated with textboxes (TexCtrl). TextCtrl objects are added with span parameter specified. Hence, the width of text boxes spans more than one column. Text box for name spans over two columns. tc = wx.TextCtrl(panel) sizer.Add(tc, pos = (0, 1), span = (1, 2), flag = wx.EXPAND|wx.ALL, border = 5) Textbox for address is a multiline text control spanning over three columns. tc1 = wx.TextCtrl(panel,style = wx.TE_MULTILINE) sizer.Add(tc1, pos = (1,1), span = (1, 3), flag = wx.EXPAND|wx.ALL, border = 5) The row containing multiline text control for description is set to be growable so that it expands vertically downwards, if the form is stretched. tc4 = wx.TextCtrl(panel,style = wx.TE_MULTILINE) sizer.Add(tc4, pos = (3,1), span = (1,3), flag = wx.EXPAND|wx.ALL, border = 5) sizer.AddGrowableRow(3) Following is the complete code − import wx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title = title) self.InitUI() self.Centre() self.Show() def InitUI(self): panel = wx.Panel(self) sizer = wx.GridBagSizer(0,0) text = wx.StaticText(panel, label = "Name:") sizer.Add(text, pos = (0, 0), flag = wx.ALL, border = 5) tc = wx.TextCtrl(panel) sizer.Add(tc, pos = (0, 1), span = (1, 2), flag = wx.EXPAND|wx.ALL, border = 5) text1 = wx.StaticText(panel, label = "address") sizer.Add(text1, pos = (1, 0), flag = wx.ALL, border = 5) tc1 = wx.TextCtrl(panel,style = wx.TE_MULTILINE) sizer.Add(tc1, pos = (1,1), span = (1, 3), flag = wx.EXPAND|wx.ALL, border = 5) text2 = wx.StaticText(panel,label = "age") sizer.Add(text2, pos = (2, 0), flag = wx.ALL, border = 5) tc2 = wx.TextCtrl(panel) sizer.Add(tc2, pos = (2,1), flag = wx.ALL, border = 5) text3 = wx.StaticText(panel,label = "Mob.No") sizer.Add(text3, pos = (2, 2), flag = wx.ALIGN_CENTER|wx.ALL, border = 5) tc3 = wx.TextCtrl(panel) sizer.Add(tc3, pos = (2,3),flag = wx.EXPAND|wx.ALL, border = 5) text4 = wx.StaticText(panel, label = "Description") sizer.Add(text4, pos = (3, 0), flag = wx.ALL, border = 5) tc4 = wx.TextCtrl(panel,style = wx.TE_MULTILINE) sizer.Add(tc4, pos = (3,1), span = (1,3), flag = wx.EXPAND|wx.ALL, border = 5) sizer.AddGrowableRow(3) buttonOk = wx.Button(panel, label = "Ok") buttonClose = wx.Button(panel, label = "Close" ) sizer.Add(buttonOk, pos = (4, 2),flag = wx.ALL, border = 5) sizer.Add(buttonClose, pos = (4, 3), flag = wx.ALL, border = 5) panel.SetSizerAndFit(sizer) app = wx.App() Example(None, title = 'GridBag Demo') app.MainLoop() The above code produces the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2219, "s": 1882, "text": "GridBagSizer is a versatile sizer. It offers more enhancements than FlexiGridSizer. Child widget can be added to a specific cell within the grid. Furthermore, a child widget can occupy more than one cell horizontally and/or vertically. Hence, a static text and multiline text control in the same row can have different width and height." }, { "code": null, "e": 2378, "s": 2219, "text": "Gridbag layout should be meticulously planned by deciding the position, span and the gap. wx.GridBagSizer class has only one constructor taking two arguments." }, { "code": null, "e": 2406, "s": 2378, "text": "Wx.GridBagSizer(vgap,hgap)\n" }, { "code": null, "e": 2634, "s": 2406, "text": "The most important method of GridBagsizer class is Add() which takes position as the mandatory argument. Span, alignment, border flags, and border size parameters are optional. If not explicitly used they assume default values." }, { "code": null, "e": 2692, "s": 2634, "text": "Wx.GridbagSizer().Add(control, pos, span, flags, border)\n" }, { "code": null, "e": 2754, "s": 2692, "text": "The following table lists the methods of GridBagSizer class −" }, { "code": null, "e": 2760, "s": 2754, "text": "Add()" }, { "code": null, "e": 2817, "s": 2760, "text": "Adds given control at the specified position in the grid" }, { "code": null, "e": 2835, "s": 2817, "text": "GetItemPosition()" }, { "code": null, "e": 2879, "s": 2835, "text": "Returns the position of control in the grid" }, { "code": null, "e": 2897, "s": 2879, "text": "SetItemPosition()" }, { "code": null, "e": 2952, "s": 2897, "text": "Places a control at the specified position in the grid" }, { "code": null, "e": 2966, "s": 2952, "text": "GetItemSpan()" }, { "code": null, "e": 3005, "s": 2966, "text": "Returns row/column spanning of an item" }, { "code": null, "e": 3019, "s": 3005, "text": "SetItemSpan()" }, { "code": null, "e": 3076, "s": 3019, "text": "Spans the specified item over the number of rows/columns" }, { "code": null, "e": 3346, "s": 3076, "text": "The following code displays a form in which there are labels (StaticText) associated with textboxes (TexCtrl). TextCtrl objects are added with span parameter specified. Hence, the width of text boxes spans more than one column. Text box for name spans over two columns." }, { "code": null, "e": 3452, "s": 3346, "text": "tc = wx.TextCtrl(panel) \nsizer.Add(tc, pos = (0, 1), span = (1, 2), flag = wx.EXPAND|wx.ALL, border = 5)\n" }, { "code": null, "e": 3529, "s": 3452, "text": "Textbox for address is a multiline text control spanning over three columns." }, { "code": null, "e": 3660, "s": 3529, "text": "tc1 = wx.TextCtrl(panel,style = wx.TE_MULTILINE) \nsizer.Add(tc1, pos = (1,1), span = (1, 3), flag = wx.EXPAND|wx.ALL, border = 5)\n" }, { "code": null, "e": 3807, "s": 3660, "text": "The row containing multiline text control for description is set to be growable so that it expands vertically downwards, if the form is stretched." }, { "code": null, "e": 3961, "s": 3807, "text": "tc4 = wx.TextCtrl(panel,style = wx.TE_MULTILINE) \nsizer.Add(tc4, pos = (3,1), span = (1,3), flag = wx.EXPAND|wx.ALL, border = 5)\nsizer.AddGrowableRow(3)\n" }, { "code": null, "e": 3994, "s": 3961, "text": "Following is the complete code −" }, { "code": null, "e": 5976, "s": 3994, "text": "import wx \n\nclass Example(wx.Frame): \n \n def __init__(self, parent, title): \n super(Example, self).__init__(parent, title = title) \n \n self.InitUI() \n self.Centre() \n self.Show() \n \n def InitUI(self): \n \n panel = wx.Panel(self) \n sizer = wx.GridBagSizer(0,0)\n\t\t\n text = wx.StaticText(panel, label = \"Name:\") \n sizer.Add(text, pos = (0, 0), flag = wx.ALL, border = 5)\n\t\t\n tc = wx.TextCtrl(panel) \n sizer.Add(tc, pos = (0, 1), span = (1, 2), flag = wx.EXPAND|wx.ALL, border = 5) \n \n text1 = wx.StaticText(panel, label = \"address\") \n sizer.Add(text1, pos = (1, 0), flag = wx.ALL, border = 5) \n\t\t\n tc1 = wx.TextCtrl(panel,style = wx.TE_MULTILINE) \n sizer.Add(tc1, pos = (1,1), span = (1, 3), flag = wx.EXPAND|wx.ALL, border = 5) \n \n text2 = wx.StaticText(panel,label = \"age\") \n sizer.Add(text2, pos = (2, 0), flag = wx.ALL, border = 5) \n\t\t\n tc2 = wx.TextCtrl(panel) \n sizer.Add(tc2, pos = (2,1), flag = wx.ALL, border = 5) \n\t\t\n text3 = wx.StaticText(panel,label = \"Mob.No\") \n sizer.Add(text3, pos = (2, 2), flag = wx.ALIGN_CENTER|wx.ALL, border = 5)\n\t\t\n tc3 = wx.TextCtrl(panel) \n sizer.Add(tc3, pos = (2,3),flag = wx.EXPAND|wx.ALL, border = 5) \n \n text4 = wx.StaticText(panel, label = \"Description\") \n sizer.Add(text4, pos = (3, 0), flag = wx.ALL, border = 5) \n\t\t\n tc4 = wx.TextCtrl(panel,style = wx.TE_MULTILINE) \n sizer.Add(tc4, pos = (3,1), span = (1,3), flag = wx.EXPAND|wx.ALL, border = 5) \n sizer.AddGrowableRow(3) \n \n buttonOk = wx.Button(panel, label = \"Ok\") \n buttonClose = wx.Button(panel, label = \"Close\" ) \n\t\t\n sizer.Add(buttonOk, pos = (4, 2),flag = wx.ALL, border = 5) \n sizer.Add(buttonClose, pos = (4, 3), flag = wx.ALL, border = 5)\n\t\t\n panel.SetSizerAndFit(sizer)\n\t\t\napp = wx.App() \nExample(None, title = 'GridBag Demo') \napp.MainLoop()" }, { "code": null, "e": 6023, "s": 5976, "text": "The above code produces the following output −" }, { "code": null, "e": 6030, "s": 6023, "text": " Print" }, { "code": null, "e": 6041, "s": 6030, "text": " Add Notes" } ]
Model Lift — the missing link. How to talk about Machine Learning... | by Andrzej Szymanski, PhD | Towards Data Science
Half of the success in data modelling is the perception of our model by the stakeholder/audience. The critical point is to understand their expectation and address them in our presentation, using simple language, understandable by a broad, non-technical audience. Usually, the audience are the members of marketing and/or finance team who want to use the model in some kind of cross-sell or retention campaign. They are usually more interested in how much the model can improve campaign performance rather than how good the model is itself. It is a subtle difference which I will try to explain in a moment. As Data Scientists, we have a tendency to concentrate on the overall model performance and by using the ROC curve and confusion matrix tell the story of how good the model is in differentiating between positives and negatives. However, this is not always the best approach. The understanding of how the model will be deployed in real life is the critical point, which determines how the model should be evaluated. ROC is a very good evaluation method when it comes to identifying fraudulent behaviour, building a credit scorecard or identifying patients with cancer. These are the cases when we need to correctly identify each existing or a new record. However, in a marketing or political environment, the majority of campaigns target only a narrow group of our base — those most open to the message (target group). Because of that, the priority is to understand how the model performs within that group. The performance outside the group is irrelevant. Therefore, using ROC, which evaluates the whole base, is not necessarily the best option. Secondly, our audience may not understand a confusion matrix or ROC. For them, AUC equal to 0.6 or 0.75 is an abstract, irrelevant figure. Talking about specificity and sensitivity, won’t work. We have to start broadcasting on the same frequency as our audience, speak in their own language. It is us who have to adjust, not them! Remember, you are there not to impress them with your knowledge, but to pass a clear message about the findings of your model. The message should be understood within seconds. To achieve that, we need something easier to understand than ROC and something we can easily put a value on. This is where Model Lift shines. The definition of genius is taking the complex and making it simpleAlbert Einstein Model Lift tells us by how much we can improve the campaign by using our model. It tells us, what is the chance of finding positives (goods) in our selection and how does it compare to finding them on a random basis? The comparison of success ratio using our model and random selection is the Model Lift. What is great about Model Lift, is that we can immediately assign financial value to our model. If the Model Lift in our top decile is equal, for example to 3, we can say that using the top decile of our model, the campaign can generate 3 times more revenue than a campaign based on a random selection. Model Lift is basically a Return on Investment (ROI), where investment is the model we have built. To obtain Model Lift, we need to follow these steps: Obtain a model probability score for each record in our base. Sort the base out using probability score and split it into equal groups. Deciles seems to be most frequent selection, therefore, for the rest of the article I will refer to these groups as deciles. Calculate the proportion of positives in each decile (decile Response Rate) Calculate the average Response Rate Calculate Model Lift To illustrate it, let’s take an example of a direct marketing campaign of a Portuguese bank. The data came from UCI Machine Learning repository and are available here. After running data cleansing, features reduction, and resampling, I ended up with this dataset. The full code including data cleansing can be found here. Our objective is to identify customers likely to give a positive response to the offer. Our dependent variable is y, where 1= positive reaction(positives) and 0=no/negative reaction(negatives). One of the features in the dataset (duration of a call) is causing a data leakage. Duration of a call can be the result of a purchase not a reason for it. Secondly, it is unknown until data for the campaign are selected and calls made. Therefore it should be excluded from the data selected for modelling. However, as I want to concentrate on Model Lift itself, I decided to leave all variables as they are in the dataset. First, we need to split the data into train and test samples df= pd.read_csv('banking_campaign.csv')X = df.iloc[:,1:]y = df.iloc[:,0]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) I have selected Gradient Boosting for modelling from sklearn.ensemble import GradientBoostingClassifierfrom sklearn.metrics import classification_reportGBM = GradientBoostingClassifier(learning_rate=0.01, n_estimators=1000, max_depth=6, min_samples_split=50, min_samples_leaf=25, subsample=0.8, max_features=10, random_state=10)GBM.fit(X_train,y_train)predictors=list(X_train) Let’s have a brief look at the overall model performance. print('Accuracy of the GBM on test set: {:.3f}'.format(GBM.score(X_test, y_test)))pred=GBM.predict(X_test)print(classification_report(y_test, pred))from sklearn.metrics import roc_auc_scoreprint (roc_auc_score(y_test, pred)) The ROC AUC score of the model is 0.75 but let’s ignore it. The first step to obtain Model Lift is getting probabilities. To do so we use predict_proba. y_pred2=GBM.predict_proba(X_test) The first value in y_pred2 is probability of 0 (negatives), the second probability of 1 (positives). To calculate the Model Lift, run the code below. The code produces a pandas data frame which will be used for the final evaluation of the model and for building a graphical presentation. What you need to do is to call the function, specifying your test dependent variable (y_test), its predicted probabilities (y_pred2) and number of groups you want to split the base into (I decided to use deciles, so 10). ModelLift=lift(y_test,y_pred2,10) The output looks as follow: Scr_grp represents our deciles, sorted and split using probability score. Now we can compare the distribution of positives and negatives across the deciles. You can see the diminishing number of positives as we are going down the deciles. We have 800 positives in decile 1 compared with 1 in decile 10! That means our model is doing the right job. Now we can calculate the response rate (resp_rate). Response rate is the proportion of positives in a decile. For decile 1 it is 800/(800+436)=0.65. Again, you can see that the response rate is quickly diminishing down the decile groups. Finally, we need to calculate lift. For that we need the overall proportion of positives and negatives in the test group, which is: 1376/12357 = 0.11. Now the lift for the decile 1 is 5.84 (0.65/0.11). This means that a campaign based on decile 1 selection can be 5.84 times more successful than a campaign based on random selection. The other features in the table are:cmltv_p_perc: cumulative % of positivescmltv_n_perc: cumulative % of negativescmltv_rand_p_perc: cumulative % of random positivecmltv_resp_rate: cumulative response ratecmltv_lift: cumulative liftKS: Kolmogorov-Smirnov test Now compare these two messages: Now, you tell me which message our audience will be excited about! Creating a chart is the best way to pass the message across, but the audience should be able to grasp the idea within seconds. Therefore I would avoid anything more complicated, like for example gain charts. Three questions which we need to answer when presenting the results are: Is the model working?What is the relationship between selection and model performance?What is the optimal selection? Is the model working? What is the relationship between selection and model performance? What is the optimal selection? Let’s adjust the output a little bit. I have changed the dataframe index into something more informative, like Decile1 to 10 and selected only variables in scope. dec = ['Decile 1','Decile 2','Decile 3','Decile 4','Decile 5','Decile 6','Decile 7','Decile 8','Decile 9','Decile 10',]MLift=ModelLift[['Positives','Negatives','cmltv_lift','KS']].copy()MLift.index = (dec) We can quickly visualise how the model is working using the code below. import cufflinks as cfcf.go_offline()cf.set_config_file(offline=False, world_readable=True)MLift[['Positives','Negatives']].iplot(kind='bar',yTitle='Volume',xTitle='Model decile', title='Positives & Negatives by model decile') The relationship between selection size and performance can be done using cumulative lift. MLift[['cmltv_lift']].iplot(kind='bar',color='LightSkyBlue',yTitle='Lift',xTitle='Model decile', title='Cumulative Lift', yrange=[1.11, 6]) As we increase the targeted group, we can expect smaller ROI (Model Lift). For example, if we decide to use decile 1 and 2 together, ROI will drop from 5.84 (decile 1 only ) to 2.87. Still, the campaign will be almost 3 times more successful than a random selection! The optimal selection is identified using Kolmogorov-Smirnov test, which in simple language evaluates the difference between cumulative positives and cumulative negatives. The test finds the point in our data where we can have maximum positives with minimum negatives. To illustrate this I used to build gain charts but I have changed my mind and I now think bar charts are so much easier to read! MLift[['KS']].iplot(kind='bar',color='DarkSlateGrey', yTitle='Separation',xTitle='Model decile', title='Target separation') In our example the best split is around decile 2 and 3. At this point, we have got the maximum of positives with the minimum of negatives. This is the point at which we can maximise the revenue using our model. Summarising, the 3 main advantage of Model Lift over ROC are: · Even an average model can still present some value and seriously contribute to marketing campaigns. · Model Lift can be directly translated into revenue. · Model Lift is easy to understand and less confusing than confusion matrix!
[ { "code": null, "e": 780, "s": 172, "text": "Half of the success in data modelling is the perception of our model by the stakeholder/audience. The critical point is to understand their expectation and address them in our presentation, using simple language, understandable by a broad, non-technical audience. Usually, the audience are the members of marketing and/or finance team who want to use the model in some kind of cross-sell or retention campaign. They are usually more interested in how much the model can improve campaign performance rather than how good the model is itself. It is a subtle difference which I will try to explain in a moment." }, { "code": null, "e": 1054, "s": 780, "text": "As Data Scientists, we have a tendency to concentrate on the overall model performance and by using the ROC curve and confusion matrix tell the story of how good the model is in differentiating between positives and negatives. However, this is not always the best approach." }, { "code": null, "e": 1194, "s": 1054, "text": "The understanding of how the model will be deployed in real life is the critical point, which determines how the model should be evaluated." }, { "code": null, "e": 1433, "s": 1194, "text": "ROC is a very good evaluation method when it comes to identifying fraudulent behaviour, building a credit scorecard or identifying patients with cancer. These are the cases when we need to correctly identify each existing or a new record." }, { "code": null, "e": 1825, "s": 1433, "text": "However, in a marketing or political environment, the majority of campaigns target only a narrow group of our base — those most open to the message (target group). Because of that, the priority is to understand how the model performs within that group. The performance outside the group is irrelevant. Therefore, using ROC, which evaluates the whole base, is not necessarily the best option." }, { "code": null, "e": 2474, "s": 1825, "text": "Secondly, our audience may not understand a confusion matrix or ROC. For them, AUC equal to 0.6 or 0.75 is an abstract, irrelevant figure. Talking about specificity and sensitivity, won’t work. We have to start broadcasting on the same frequency as our audience, speak in their own language. It is us who have to adjust, not them! Remember, you are there not to impress them with your knowledge, but to pass a clear message about the findings of your model. The message should be understood within seconds. To achieve that, we need something easier to understand than ROC and something we can easily put a value on. This is where Model Lift shines." }, { "code": null, "e": 2557, "s": 2474, "text": "The definition of genius is taking the complex and making it simpleAlbert Einstein" }, { "code": null, "e": 2862, "s": 2557, "text": "Model Lift tells us by how much we can improve the campaign by using our model. It tells us, what is the chance of finding positives (goods) in our selection and how does it compare to finding them on a random basis? The comparison of success ratio using our model and random selection is the Model Lift." }, { "code": null, "e": 3264, "s": 2862, "text": "What is great about Model Lift, is that we can immediately assign financial value to our model. If the Model Lift in our top decile is equal, for example to 3, we can say that using the top decile of our model, the campaign can generate 3 times more revenue than a campaign based on a random selection. Model Lift is basically a Return on Investment (ROI), where investment is the model we have built." }, { "code": null, "e": 3317, "s": 3264, "text": "To obtain Model Lift, we need to follow these steps:" }, { "code": null, "e": 3379, "s": 3317, "text": "Obtain a model probability score for each record in our base." }, { "code": null, "e": 3578, "s": 3379, "text": "Sort the base out using probability score and split it into equal groups. Deciles seems to be most frequent selection, therefore, for the rest of the article I will refer to these groups as deciles." }, { "code": null, "e": 3654, "s": 3578, "text": "Calculate the proportion of positives in each decile (decile Response Rate)" }, { "code": null, "e": 3690, "s": 3654, "text": "Calculate the average Response Rate" }, { "code": null, "e": 3711, "s": 3690, "text": "Calculate Model Lift" }, { "code": null, "e": 4227, "s": 3711, "text": "To illustrate it, let’s take an example of a direct marketing campaign of a Portuguese bank. The data came from UCI Machine Learning repository and are available here. After running data cleansing, features reduction, and resampling, I ended up with this dataset. The full code including data cleansing can be found here. Our objective is to identify customers likely to give a positive response to the offer. Our dependent variable is y, where 1= positive reaction(positives) and 0=no/negative reaction(negatives)." }, { "code": null, "e": 4650, "s": 4227, "text": "One of the features in the dataset (duration of a call) is causing a data leakage. Duration of a call can be the result of a purchase not a reason for it. Secondly, it is unknown until data for the campaign are selected and calls made. Therefore it should be excluded from the data selected for modelling. However, as I want to concentrate on Model Lift itself, I decided to leave all variables as they are in the dataset." }, { "code": null, "e": 4711, "s": 4650, "text": "First, we need to split the data into train and test samples" }, { "code": null, "e": 4872, "s": 4711, "text": "df= pd.read_csv('banking_campaign.csv')X = df.iloc[:,1:]y = df.iloc[:,0]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)" }, { "code": null, "e": 4920, "s": 4872, "text": "I have selected Gradient Boosting for modelling" }, { "code": null, "e": 5513, "s": 4920, "text": "from sklearn.ensemble import GradientBoostingClassifierfrom sklearn.metrics import classification_reportGBM = GradientBoostingClassifier(learning_rate=0.01, n_estimators=1000, max_depth=6, min_samples_split=50, min_samples_leaf=25, subsample=0.8, max_features=10, random_state=10)GBM.fit(X_train,y_train)predictors=list(X_train)" }, { "code": null, "e": 5571, "s": 5513, "text": "Let’s have a brief look at the overall model performance." }, { "code": null, "e": 5796, "s": 5571, "text": "print('Accuracy of the GBM on test set: {:.3f}'.format(GBM.score(X_test, y_test)))pred=GBM.predict(X_test)print(classification_report(y_test, pred))from sklearn.metrics import roc_auc_scoreprint (roc_auc_score(y_test, pred))" }, { "code": null, "e": 5856, "s": 5796, "text": "The ROC AUC score of the model is 0.75 but let’s ignore it." }, { "code": null, "e": 5949, "s": 5856, "text": "The first step to obtain Model Lift is getting probabilities. To do so we use predict_proba." }, { "code": null, "e": 5983, "s": 5949, "text": "y_pred2=GBM.predict_proba(X_test)" }, { "code": null, "e": 6084, "s": 5983, "text": "The first value in y_pred2 is probability of 0 (negatives), the second probability of 1 (positives)." }, { "code": null, "e": 6271, "s": 6084, "text": "To calculate the Model Lift, run the code below. The code produces a pandas data frame which will be used for the final evaluation of the model and for building a graphical presentation." }, { "code": null, "e": 6492, "s": 6271, "text": "What you need to do is to call the function, specifying your test dependent variable (y_test), its predicted probabilities (y_pred2) and number of groups you want to split the base into (I decided to use deciles, so 10)." }, { "code": null, "e": 6526, "s": 6492, "text": "ModelLift=lift(y_test,y_pred2,10)" }, { "code": null, "e": 6554, "s": 6526, "text": "The output looks as follow:" }, { "code": null, "e": 6902, "s": 6554, "text": "Scr_grp represents our deciles, sorted and split using probability score. Now we can compare the distribution of positives and negatives across the deciles. You can see the diminishing number of positives as we are going down the deciles. We have 800 positives in decile 1 compared with 1 in decile 10! That means our model is doing the right job." }, { "code": null, "e": 7140, "s": 6902, "text": "Now we can calculate the response rate (resp_rate). Response rate is the proportion of positives in a decile. For decile 1 it is 800/(800+436)=0.65. Again, you can see that the response rate is quickly diminishing down the decile groups." }, { "code": null, "e": 7474, "s": 7140, "text": "Finally, we need to calculate lift. For that we need the overall proportion of positives and negatives in the test group, which is: 1376/12357 = 0.11. Now the lift for the decile 1 is 5.84 (0.65/0.11). This means that a campaign based on decile 1 selection can be 5.84 times more successful than a campaign based on random selection." }, { "code": null, "e": 7734, "s": 7474, "text": "The other features in the table are:cmltv_p_perc: cumulative % of positivescmltv_n_perc: cumulative % of negativescmltv_rand_p_perc: cumulative % of random positivecmltv_resp_rate: cumulative response ratecmltv_lift: cumulative liftKS: Kolmogorov-Smirnov test" }, { "code": null, "e": 7766, "s": 7734, "text": "Now compare these two messages:" }, { "code": null, "e": 7833, "s": 7766, "text": "Now, you tell me which message our audience will be excited about!" }, { "code": null, "e": 8041, "s": 7833, "text": "Creating a chart is the best way to pass the message across, but the audience should be able to grasp the idea within seconds. Therefore I would avoid anything more complicated, like for example gain charts." }, { "code": null, "e": 8114, "s": 8041, "text": "Three questions which we need to answer when presenting the results are:" }, { "code": null, "e": 8231, "s": 8114, "text": "Is the model working?What is the relationship between selection and model performance?What is the optimal selection?" }, { "code": null, "e": 8253, "s": 8231, "text": "Is the model working?" }, { "code": null, "e": 8319, "s": 8253, "text": "What is the relationship between selection and model performance?" }, { "code": null, "e": 8350, "s": 8319, "text": "What is the optimal selection?" }, { "code": null, "e": 8513, "s": 8350, "text": "Let’s adjust the output a little bit. I have changed the dataframe index into something more informative, like Decile1 to 10 and selected only variables in scope." }, { "code": null, "e": 8719, "s": 8513, "text": "dec = ['Decile 1','Decile 2','Decile 3','Decile 4','Decile 5','Decile 6','Decile 7','Decile 8','Decile 9','Decile 10',]MLift=ModelLift[['Positives','Negatives','cmltv_lift','KS']].copy()MLift.index = (dec)" }, { "code": null, "e": 8791, "s": 8719, "text": "We can quickly visualise how the model is working using the code below." }, { "code": null, "e": 9018, "s": 8791, "text": "import cufflinks as cfcf.go_offline()cf.set_config_file(offline=False, world_readable=True)MLift[['Positives','Negatives']].iplot(kind='bar',yTitle='Volume',xTitle='Model decile', title='Positives & Negatives by model decile')" }, { "code": null, "e": 9109, "s": 9018, "text": "The relationship between selection size and performance can be done using cumulative lift." }, { "code": null, "e": 9249, "s": 9109, "text": "MLift[['cmltv_lift']].iplot(kind='bar',color='LightSkyBlue',yTitle='Lift',xTitle='Model decile', title='Cumulative Lift', yrange=[1.11, 6])" }, { "code": null, "e": 9516, "s": 9249, "text": "As we increase the targeted group, we can expect smaller ROI (Model Lift). For example, if we decide to use decile 1 and 2 together, ROI will drop from 5.84 (decile 1 only ) to 2.87. Still, the campaign will be almost 3 times more successful than a random selection!" }, { "code": null, "e": 9914, "s": 9516, "text": "The optimal selection is identified using Kolmogorov-Smirnov test, which in simple language evaluates the difference between cumulative positives and cumulative negatives. The test finds the point in our data where we can have maximum positives with minimum negatives. To illustrate this I used to build gain charts but I have changed my mind and I now think bar charts are so much easier to read!" }, { "code": null, "e": 10038, "s": 9914, "text": "MLift[['KS']].iplot(kind='bar',color='DarkSlateGrey', yTitle='Separation',xTitle='Model decile', title='Target separation')" }, { "code": null, "e": 10249, "s": 10038, "text": "In our example the best split is around decile 2 and 3. At this point, we have got the maximum of positives with the minimum of negatives. This is the point at which we can maximise the revenue using our model." }, { "code": null, "e": 10311, "s": 10249, "text": "Summarising, the 3 main advantage of Model Lift over ROC are:" }, { "code": null, "e": 10413, "s": 10311, "text": "· Even an average model can still present some value and seriously contribute to marketing campaigns." }, { "code": null, "e": 10467, "s": 10413, "text": "· Model Lift can be directly translated into revenue." } ]
Crafting a Machine Learning Model to Predict Student Retention Using R | by Luciano Vilas Boas | Towards Data Science
First and foremost, let’s start by defining what student retention is, at least in the scope of this article. We’ll define it, as the indicator that tells us if a student that started in College for the first time in a particular Fall semester, came back to the following next Fall (or not). For instance, let’s say a student started on particular University for the first time in the Fall of 2018. If this student enrolled himself/herself for Fall 2019, then this student was retained. Another common names for retention are, persistence, and/or drop out. Here, these names mean the same thing: one year undergraduate retention. The reader may ask at this point, “Why is student retention important anyways?” That’s a fair question, and without the pretension of exhausting this answer, we can say that is important for a myriad of reasons, starting with the financial impact, the ranks and prestige that schools can get and the list may go on and on. By the way, when we say “school” here, we are specifically referring to Universities and Colleges (Higher Education). Finding a dataset that goes at the student level is very hard — if you have one and want to send me, please do so, but it must be anonymized. Meaning, no student’s name or ID, or any other information that allows the researcher to identify the student — particularly, when we have regulations that rightfully, protect student’s data, such as FERPA. This is a big deal, and we must be very careful when handling sensitive information. That is to say, locating the right dataset, explicitly for this experiment, really imposes a challenging. However, and on the positive side, we managed to find one dataset that we could use, and that is the one we’ll be manipulating here. You can find it at UCI Machine Learning Repository, just click here. To use this data, it’s requested that we do a proper citation, and please refer toe the “Reference” section of this article to check that out. On an additional note, a big shout out for these researchers that made this dataset available. Thank you. Although we found this dataset, the truth is that it’s really a small dataset for a Machine Learning (ML) project, and on top of that, we’ll see later, that the variables are not really relevant in the big scheme of things. So, ultimately, the ML model can potentially have a poor performance. We’ll cover more on that as we go. Another important point to emphasize is that, originally, this dataset was used to predict student performance [1], and NOT retention. Funny enough, the dataset has interesting features, but with no relevant significance when predicting the performance [1], and the retention. What I mean here, is that despite the fact that we have several variables, basically, just very few of them tell us the history. We are going to use a lot of creativity here. Note that the original data is about students in High School. But for here, let’s imagine that those students are College students. Additionally, we had to create and incorporate a new feature called “retention”, which was randomly created to simulate whether or not a student was retained. Apparently, this had a negative impact on the model, since this is actually our predictor variable — and it’s random. In spite of that, the main goal of performing this experiment is to make available a machine learning pipeline that can be used, especially with the right dataset, to leverage student retention in Higher Ed. I hope this ML project can help administrators and researches on that regard. Here is how we broke down our task into four main phases as following: Phase 1: Data Munging In this phase, we’ll look for missing data, and get familiar with the dataset. Curiously, we have not found any missing data here. While one may think that this is good, which ultimately is, it also makes us think if some imputation was done prior to us working with this dataset. Here is a tip: whenever you decide to input missing values, please document that by leaving the original column with the missing values, and the new column with the imputation on the dataset. Additionally, state which technique was used to input values of if you just dropped. By reading the original article that was used with this dataset, we came to the conclusion that the missing data was dropped out, and what we have was the actual responses, meaning we have no missing values. Phase 2: Exploratory Analysis I can never get my head around of people that perform “Exploratory Analysis” without knowing which variables are really relevant in a particular dataset. Don’t go around plotting charts randomly. It’s okay to have some initial assumptions, but you should always try to figure out what features matter for what you are trying to study. So, some of our plots were done based on what we found to be relevant and what we wanted to see, but mostly, based on scientific understanding of the dataset. Phase 3: Dimensionality Reduction In my opinion, one of the most important steps. Particularly, because this dataset is really small and it has a considerable number of variables. Here, we’ll look for multicollinearity, and how to eliminate variables. We’ll use Logistic Regression to get rid of irrelevant variables. On top of that, we’ll also performed PCA (Principal Component Analysis) with the goal of figuring out relevant features. Phase 4: Machine Learning That’s the part we perform a ML modeling and get awesome results, right!? Well, it turns out that this phase wast quite challenging, and we’ll get to that later. But some of the techniques we used here was to balance the predictor using ROSE [2] library, assessing the AUC (Area Under to Curve) and ROC curve, and checking accuracy and kappa scores of multiple algorithms in order to check each one works best with this data. Small datasets tend to impose challenges for ML algorithms. Especially when features are not really significant and the predictor is artificially created, random, and imbalanced. What a recipe for a disaster, huh?! With this in mind, and even before actually starting to work with this dataset, we came up with these following assumptions, but not limited to: Above we can see the six main assumptions and some of their causes. We won’t go through all of them here, for the sake of time, but we tried to mitigate the effects of them as much as we could when coding and developing the model. Note that the Imbalanced and Random Classifier issues were created for this project, and they are not part of the original dataset. Remember, the reason we were anticipating these problems has to do with the fact we artificially created a new feature called retention, which sorted the binary values (1 or 0) randomly, according to the weight that was given to them. To make it clear, the total students in the dataset we are using is just 649, and when creating this artificial predictor — retention — we said that ~85% of those students would be flagged as “retained” (binary indicator is 1) and ~15% “not retained” (binary indicator 0). That’s pretty much the average retention rate for a public College/University. We used the statistical and open-source application called R to perform this task. And, to make this more visually appealing (that’s our hope), we won’t be showing all codes here, but you’ll find everything on the link as shown below. All codes and files can be found here on my GitHub page. Likewise, we’ll break down this hands-on section into the same four phases we saw previously. Without further ado, let’s start from the beginning: Again, you can find the original dataset and paper on UCI ML Repository. But, here is a snapshot of all variables for you: Keep in mind that the retention variable that we talked before, was inserted into this dataset set artificially in order to simulate predictive modeling for student’s retention. You don’t see it here in this table, but in the R codes. There are also two datasets available, one for Math and one for Portuguese. We’ll only use the one for Portuguese simply because this was the one with more students (649) on it. The article [1] combined Math and Portuguese into one single set, but that has an even smaller sample size. One of the main goals in this phase 1 was to create the artificial variable, get familiarized with this dataset, and check for missing values. As we can see in the plot 1, there were no missing values in this dataset. As a matter of fact, we have stated that previously, but here is the proof. Note that we added the retention variable in this plot. Additionally, I had to create dummy variables for some of the variables in the dataset that was not dummy-coded. At the end of this processing, a new csv file, just with the dummy codes, numeric values, and the predictor, can be exported using the R codes provided. Now that we have the green light, and the dataset ready for the initial assessments, we can move to the next step. This is where people go crazy on plotting histograms and box plots, isn’t it?! They are necessary, don’t get me wrong. We’ll see some of those in a sec. Also, you can check things like skewness, kurtosis and other basic statistical checklist on the R codes. In this simple bar chart, we can see the counts for the predictor variable, according to the weight we set for them when creating this artificial predictor. As we stated previously, students that were retained are flagged with “1” (538) and students not retained “0” (111). Ultimately, it also shows the imbalance between the classifier, and we’ll take care of later. In the original article [1], the variable “G1” was a very strong predictor for student’s performance. The following scatterplot tells us a little bit of this expected positive correlation between the first grade (G1), and the final (G3). We can also spot some potential outliers. Continuing with this analysis, we were interested to see what could impact student’s performance on G1. For that, we focused on checking the studytime, and the freetime students have available, and we broke that down by gender. Okay, I surrender! Here is where I come up with a box plot for all variables. We can easily see here where we have presence of outliers, and quickly think about some option to whether or not deal with this issue. For this testing, we are not going to exclude the outliers. Once more, I want to give some attention to the variable G1, so let’s check it’s distribution as following below: Considering this is a real world data, its distribution it’s not too bad, really. But, it’s not perfect — obviously. In conclusion of this Phase 3, we just want to check one more thing. That is, how G1 and G2 variables interact when adding the students into a bivariate plot, like the one as following below: Think about this bivariate plot as being an ordinary box plot, but mixing together two variables instead of just one. Specifically, the numbers in blue could be the students ID (that’s not the case here because we don’t have students IDs in the dataset). Any student outside of the bigger ellipse would be an outlier. This could be helpful when trying to identify which students we would reach out in order to take some proactive actions towards to, let’s say, improve their grades on G3. This is where the fun starts. A good practice is to always check for collinearity/multicollinearity among the dataset. The easiest way to do that is by checking the correlation that independent and dependent variables may have. If two or more variables have a very strong or almost perfect correlation, that might be an indication of collinearity/multicollinearity. When facing a scenario where two or more variables have a strong correlation, we want to eliminate one of them. Why? Because in essence, you have two variables telling you the same story. But being a little be more technical, collinearity can mess up with the variance of at least one estimated regression coefficient, and this can lead to some regressor to come up with the wrong sign. Which can deteriorate your analysis and lead you the wrong way. Let’s check if we can spot some of this issue using the following Correlation Matrix: There are some interesting correlations here, but mainly about the grades (G1, G2, and G3). They seem to have a very strong correlation, indicating some potential collinearity. We also see a strong negative correlation between grades and failures, as well as some other features. You can always check the actual numbers using a correlation table, or by simply adding them directly on the plot itself. For now, we just want to get a big picture of how the variables may be correlated. The Principal Component Analysis (PCA) is used to shape the original variables into a new set of features, which are linear combinations of the original variables. PCA’s main goal is to reduce the number of variables, but considering the original variation as much as possible. In the first component, or dimension, you’ll see a combination of the original variables whose sample variance is greatest amongst all possible linear combinations. In the second dimension, we account for the maximal proportion of the rest of the remaining variance, which can be uncorrelated with the first dimension. The other components follows a similar approach. When analyzing the output from running a PCA, we want to see a “Cumulative Proportion”, between dimension one and dimension two, that is significative. Generally speaking, a cumulative proportion equal or greater than 0.7 is considered to be very good. Meaning, the reduction from multiple variables into two dimensions can still have a strong representation of the entire dataset. One important thing prior to performing a PCA is to make sure the dataset is standardized. Deciding whether or not to remove outliers is also a good practice at this point. To kick off our analysis using PCA, we’ll start with a bar chart that displays all the cumulative proportions among the components as well as their variances. In essence, we are particularly interested in shrinking down our analysis up to the first two dimensions. We want to make sure that the cumulative proportion between them both are significant enough to “explain” the rest of the dataset. Unfortunately, as you’ll see in the next plot, the cumulative proportion is just about 21% (12.9% + 8.1%). So reducing into two dimensions would not be recommended, hence, we would be losing information and end up with two dimensions that don’t “explain” the dataset much. From the biplot, we can also see the correlation among the variables e.g., grades (G1, G2 and G3) and failures pointing on the opposite direction. Although the cumulative proportion of the two dimensions are not really useful when boils down to dimensionality reduction of this dataset, we want to check which are the contributions of the top ten variables for each dimension. This might help us to understand a lit bit more about this dataset. We can see that in Dim 1, grades are the variables that contributes the most in this dimension. But, it’s important to stress that we still have that assumption of collinearity present here. So this is one more clue that, indeed, we may have collinearity here because we see all grades with very similar contribution levels. On the other hand, in the Dim 2 the Walc feature has the highest contribution. In summary, if one asks what Dim 1 and Dim 2 is about, we can say that Dim 1 is about student grades, and Dim 2 student’s alcohol consumption. Meaning that we should expect some of these variables to have statistical significance when predicting the retention. All of this testing would be extremely helpful when guiding our decision about which variables to keep and which ones to disregard moving further in our analysis. Unfortunately, we won’t be using PCA to take any decisions just yet. Circling back, the hypothesis that we have collinearity is still alive, but how to measure that, and how to decide each variable to get rid of? In the light of acknowledging this issue, and with this in mind, we’ll take advantage of VIF (Variable Inflation Factors) to detect and support our decision towards to the best approach when dealing with multicollinearity. To make it short, VIF detects how strong the correlation between variable is, and its score guide us on each variable(s) to drop and mitigate collinearity. As a general rule of thumb, VIF scores equal to or greater than 5 suggests collinearity. We will use 5 as our threshold here as well. As we can see below, the VIF output, which was based on a Logistic Regression, tell us that G2 and G3 are the variables we should disregard moving further on our analysis. Usually, you should get rid of one variable at the time and run the analysis again. That is, G2 would be the first to leave, and G3 the second. Here is a graphical way to visualize the before and after of the removal of these two variables (G2 and G3): As a result of all this wrangling, we just got rid of two variables. That was not really productive in some sense. We still have a considerable large set of features that doesn’t tell much about what we trying to do. So, our shortcut will be using the Logistic Regression to not only help us in finding the predictors but also to eliminate non statistically significant variables. As has been noted from the Logit Regression output — on the left side — we have five variables that could work as predictors. However, only three of them has meaningful significance at 0.05 - we marked them down with a red arrow. The R-squared is a common indicator that some researchers may use when picking a model over others. Here, we would just use the AIC (Akaike Information Criterion) score to compare the output with 5 variable, against the output with 3 variables. As you can see below, eliminating two of the less significant variables doesn’t affect the AIC score much. All five statistically significant variables: AIC: 589.84 All three statistically significant variables at 0.05: AIC: 589.67M Yes, the AIC for the whole dataset is bigger (622.4), but because it’s full of not really useful features, we are taking this curve here and deciding to work with only these three variables in the next phase. Considering all the challenges we have been facing so far, what could possibly go wrong when modeling the ML model? A poor performance model is what can go wrong. But, we want to get the best outcome possible, and at least a fair model. That being said, we gotta be real here, ML is really suitable for large datasets. But with some tweaks we can make it work. In this case, we’ll take advantage of a library called ROSE to balance the predictor and improve the model’s performance. Originally, our predictor was split this way: 1= 538, and 0= 111. As you can clearly see, we have an imbalanced classifier. We’ll artificially balance it to improve the outcome and mitigate some of the statistical issues that comes along with it. However, we’ll do that over the quantities for the trainSplit. Thus, our train set has a total of 553 students, where: 1= 458, and 0= 95. In other words, we’ll be balancing the training data and not the entire dataset for now. ROSE offers some different options to balance the classifier. We’ll cover 4 different approaches and pick the one that gives us the best result. Below are the codes we borrowed from the paper “ROSE: A Package for Binary Imbalanced Learning” [2]. ### Balancing the data:# Resampling Option 1 (over):data.bal.ov <- ovun.sample(retention ~ ., data = trainSplit, method = "over", p=0.5, seed = 2)$datatable(data.bal.ov$retention)# Resampling Option 2 (under):data.bal.un <- ovun.sample(retention ~ ., data = trainSplit, method = "under", p = 0.5, seed = 2)$data table(data.bal.un$retention)# Resampling Option 3 (both):data.bal.ou <- ovun.sample(retention ~ ., data = trainSplit, method = "both", N = 553, p = 0.5, seed = 2)$data table(data.bal.ou$retention)# Resampling Option 4 (ROSE):data.rose <- ROSE(retention ~ ., data = trainSplit, seed = 1)$datatable(data.rose$retention) Resampling Option 1 (over): Here we oversampling the “0” until it’s leveled with the counts of “ones”. As a result, we’ve balanced the classifier as following: 1= 458, and 0=453. Resampling Option 2 (under): By undersampling the majority class (1) to match the minority, we get this result: 1=97, and 0=95. Resampling Option 3 (both): In this case we use the entire train set (553) and split, such as: 1=281, and 0=272. Resampling Option 4 (ROSE): Finally, we use ROSE to split the data and we got this outcome: 1=293, and 0=260. Next, we train the classifiers, run the test set using Classification Trees, and plot the ROC Curve. # Training the Classifiers and run test set using classification trees:library(rpart)tree.ov <- rpart(retention ~ ., data = data.bal.ov)tree.un <- rpart(retention ~ ., data = data.bal.un)tree.ou <- rpart(retention ~ ., data = data.bal.ou)tree.rose <- rpart(retention ~ ., data = data.rose)# Predict in the new data (test):pred.tree.ov <- predict(tree.ov, newdata = testSplit)pred.tree.un <- predict(tree.un, newdata = testSplit)pred.tree.ou <- predict(tree.un, newdata = testSplit)pred.tree.rose <- predict(tree.rose, newdata = testSplit)# Plot ROC Curve - Model Evaluation:roc.curve(testSplit$retention, pred.tree.rose[,2], col = 0, main= "AUC: 0.75", lty = 1)roc.curve(testSplit$retention, pred.tree.ov[,2], add.roc = TRUE, col = 12, lty = 2) roc.curve(testSplit$retention, pred.tree.un[,2], add.roc = TRUE, col = 0, lty = 3) roc.curve(testSplit$retention, pred.tree.ou[,2], add.roc = TRUE, col = 0, lty = 4) Resampling Option 2 (under) has given us the best AUC (Area Under the Curve) output. See below: The AUC is an algorithm, which is widely used to measure the trade-off between the True Positive (TP) and False Positive (FP) rates of a said ML classifier. Likewise, a model that fails to predict will have a score of 0%, while a model that is able to make “perfect” predictions will get a score of 100%. Accordingly, our model scored 75%, which is not too bad, but a number ≥80% would be preferable. On the positive side, using the ROSE package gave us a huge improvement over the imbalanced scenario. So, we’ll celebrate this as a big victory. YAY! Another very common way to measure classifiers is by getting a Decision Tree, which would give us more intuition on how the model is performing. We’ll skip that here, and move to the next and final piece of this ML analysis. A lot of people rely on accuracy to pick a ML model. That alone can be misleading, but since this is a very “quick and dirty” type of project, I’ll allow myself to experiment with that. Accuracy: it basically pinpoints the proportion of “1” and “0” that were flagged correctly. Kappa: tells us the performance of the classifier in comparison with values assigned randomly. Without delay, here is how we’ll handle this part of the analysis: we’ll again use ROSE to balance the entire dataset now (649 rows). This time we won’t split between train and test, and that is because the set is very small. We are going to use everything we have. Similarly, we’ll use the following code to balance the predictor, but as you’ll see, we are artificially duplicating the dataset up to 1298 observations, and using the “both” method here. # Create balanced training data for LR:dataC <- ovun.sample(retention ~ ., data = dataC, method = "both", N = 1298, seed =1)$data # 1298 (649x2)table(dataC$retention) Therefore, we get the new balanced classifier such as: 1=652, and 0=646. Now, we will use the “mlbench” library to run a benchmark comparison between few different algorithms to see each one(s) has the best performance. As we can see above, the “best” algorithm for this analysis was the svm (Support Vector Machines), with an accuracy of almost 70%, and kappa of 39%. Those are fair results, but definitely not optimal. Keep in mind that when choosing each model to actually use in production, many other factors has to be taken in consideration, and not only the accuracy scores alone. For the purpose of what we were trying to accomplish, our ML analysis ends here. In conclusion, you saw that the three main predictors were Medu, famsup_yes, and Dalc. A next step would be getting the odds ratio out of the Logit Regression and make the analysis more interpretable. I’ll leave that for future improvements and save our time here. As a reminder, our goal here was to provide some guidelines of how to use multiple techniques to work with a small dataset and get a fair to good results. There are many other ways to tackle this problem, and here we are providing you a solid one - using a real world dataset. With a more well-designed dataset that is suited to predict retention, and with more observations, we can certainly expect to have better results. This analysis was created for that purpose. Ultimately, retention rates is one of the most important indicator in Higher Education, and this pipeline can be useful to further research on the subject, and for administrators to make better decisions based on data. ‘Till next time! References: [1] P. Cortez and A. Silva. Using Data Mining to Predict Secondary School Student Performance. In A. Brito and J. Teixeira Eds., Proceedings of 5th FUture BUsiness TEChnology Conference (FUBUTEC 2008) pp. 5–12, Porto, Portugal, April, 2008, EUROSIS, ISBN 978–9077381–39–7. [2] Nicola Lunardon, Giovanna Menardi, and Nicola Torelli. ROSE: A Package for Binay Imbalanced Learning. The R Journal Vol. 6/1, June 2014. ISSN 2073-4859. [3] Whitlock, Joshua Lee, "Using Data Science and Predictive Analytics to Understand 4-Year University Student Churn" (2018). Electronic Theses and Dissertations. Paper 3356. https://dc.etsu.edu/etd/3356
[ { "code": null, "e": 659, "s": 172, "text": "First and foremost, let’s start by defining what student retention is, at least in the scope of this article. We’ll define it, as the indicator that tells us if a student that started in College for the first time in a particular Fall semester, came back to the following next Fall (or not). For instance, let’s say a student started on particular University for the first time in the Fall of 2018. If this student enrolled himself/herself for Fall 2019, then this student was retained." }, { "code": null, "e": 1243, "s": 659, "text": "Another common names for retention are, persistence, and/or drop out. Here, these names mean the same thing: one year undergraduate retention. The reader may ask at this point, “Why is student retention important anyways?” That’s a fair question, and without the pretension of exhausting this answer, we can say that is important for a myriad of reasons, starting with the financial impact, the ranks and prestige that schools can get and the list may go on and on. By the way, when we say “school” here, we are specifically referring to Universities and Colleges (Higher Education)." }, { "code": null, "e": 1677, "s": 1243, "text": "Finding a dataset that goes at the student level is very hard — if you have one and want to send me, please do so, but it must be anonymized. Meaning, no student’s name or ID, or any other information that allows the researcher to identify the student — particularly, when we have regulations that rightfully, protect student’s data, such as FERPA. This is a big deal, and we must be very careful when handling sensitive information." }, { "code": null, "e": 1985, "s": 1677, "text": "That is to say, locating the right dataset, explicitly for this experiment, really imposes a challenging. However, and on the positive side, we managed to find one dataset that we could use, and that is the one we’ll be manipulating here. You can find it at UCI Machine Learning Repository, just click here." }, { "code": null, "e": 2234, "s": 1985, "text": "To use this data, it’s requested that we do a proper citation, and please refer toe the “Reference” section of this article to check that out. On an additional note, a big shout out for these researchers that made this dataset available. Thank you." }, { "code": null, "e": 2563, "s": 2234, "text": "Although we found this dataset, the truth is that it’s really a small dataset for a Machine Learning (ML) project, and on top of that, we’ll see later, that the variables are not really relevant in the big scheme of things. So, ultimately, the ML model can potentially have a poor performance. We’ll cover more on that as we go." }, { "code": null, "e": 2969, "s": 2563, "text": "Another important point to emphasize is that, originally, this dataset was used to predict student performance [1], and NOT retention. Funny enough, the dataset has interesting features, but with no relevant significance when predicting the performance [1], and the retention. What I mean here, is that despite the fact that we have several variables, basically, just very few of them tell us the history." }, { "code": null, "e": 3424, "s": 2969, "text": "We are going to use a lot of creativity here. Note that the original data is about students in High School. But for here, let’s imagine that those students are College students. Additionally, we had to create and incorporate a new feature called “retention”, which was randomly created to simulate whether or not a student was retained. Apparently, this had a negative impact on the model, since this is actually our predictor variable — and it’s random." }, { "code": null, "e": 3781, "s": 3424, "text": "In spite of that, the main goal of performing this experiment is to make available a machine learning pipeline that can be used, especially with the right dataset, to leverage student retention in Higher Ed. I hope this ML project can help administrators and researches on that regard. Here is how we broke down our task into four main phases as following:" }, { "code": null, "e": 3803, "s": 3781, "text": "Phase 1: Data Munging" }, { "code": null, "e": 4569, "s": 3803, "text": "In this phase, we’ll look for missing data, and get familiar with the dataset. Curiously, we have not found any missing data here. While one may think that this is good, which ultimately is, it also makes us think if some imputation was done prior to us working with this dataset. Here is a tip: whenever you decide to input missing values, please document that by leaving the original column with the missing values, and the new column with the imputation on the dataset. Additionally, state which technique was used to input values of if you just dropped. By reading the original article that was used with this dataset, we came to the conclusion that the missing data was dropped out, and what we have was the actual responses, meaning we have no missing values." }, { "code": null, "e": 4599, "s": 4569, "text": "Phase 2: Exploratory Analysis" }, { "code": null, "e": 5093, "s": 4599, "text": "I can never get my head around of people that perform “Exploratory Analysis” without knowing which variables are really relevant in a particular dataset. Don’t go around plotting charts randomly. It’s okay to have some initial assumptions, but you should always try to figure out what features matter for what you are trying to study. So, some of our plots were done based on what we found to be relevant and what we wanted to see, but mostly, based on scientific understanding of the dataset." }, { "code": null, "e": 5127, "s": 5093, "text": "Phase 3: Dimensionality Reduction" }, { "code": null, "e": 5532, "s": 5127, "text": "In my opinion, one of the most important steps. Particularly, because this dataset is really small and it has a considerable number of variables. Here, we’ll look for multicollinearity, and how to eliminate variables. We’ll use Logistic Regression to get rid of irrelevant variables. On top of that, we’ll also performed PCA (Principal Component Analysis) with the goal of figuring out relevant features." }, { "code": null, "e": 5558, "s": 5532, "text": "Phase 4: Machine Learning" }, { "code": null, "e": 5984, "s": 5558, "text": "That’s the part we perform a ML modeling and get awesome results, right!? Well, it turns out that this phase wast quite challenging, and we’ll get to that later. But some of the techniques we used here was to balance the predictor using ROSE [2] library, assessing the AUC (Area Under to Curve) and ROC curve, and checking accuracy and kappa scores of multiple algorithms in order to check each one works best with this data." }, { "code": null, "e": 6199, "s": 5984, "text": "Small datasets tend to impose challenges for ML algorithms. Especially when features are not really significant and the predictor is artificially created, random, and imbalanced. What a recipe for a disaster, huh?!" }, { "code": null, "e": 6344, "s": 6199, "text": "With this in mind, and even before actually starting to work with this dataset, we came up with these following assumptions, but not limited to:" }, { "code": null, "e": 6707, "s": 6344, "text": "Above we can see the six main assumptions and some of their causes. We won’t go through all of them here, for the sake of time, but we tried to mitigate the effects of them as much as we could when coding and developing the model. Note that the Imbalanced and Random Classifier issues were created for this project, and they are not part of the original dataset." }, { "code": null, "e": 6942, "s": 6707, "text": "Remember, the reason we were anticipating these problems has to do with the fact we artificially created a new feature called retention, which sorted the binary values (1 or 0) randomly, according to the weight that was given to them." }, { "code": null, "e": 7294, "s": 6942, "text": "To make it clear, the total students in the dataset we are using is just 649, and when creating this artificial predictor — retention — we said that ~85% of those students would be flagged as “retained” (binary indicator is 1) and ~15% “not retained” (binary indicator 0). That’s pretty much the average retention rate for a public College/University." }, { "code": null, "e": 7529, "s": 7294, "text": "We used the statistical and open-source application called R to perform this task. And, to make this more visually appealing (that’s our hope), we won’t be showing all codes here, but you’ll find everything on the link as shown below." }, { "code": null, "e": 7586, "s": 7529, "text": "All codes and files can be found here on my GitHub page." }, { "code": null, "e": 7733, "s": 7586, "text": "Likewise, we’ll break down this hands-on section into the same four phases we saw previously. Without further ado, let’s start from the beginning:" }, { "code": null, "e": 7856, "s": 7733, "text": "Again, you can find the original dataset and paper on UCI ML Repository. But, here is a snapshot of all variables for you:" }, { "code": null, "e": 8377, "s": 7856, "text": "Keep in mind that the retention variable that we talked before, was inserted into this dataset set artificially in order to simulate predictive modeling for student’s retention. You don’t see it here in this table, but in the R codes. There are also two datasets available, one for Math and one for Portuguese. We’ll only use the one for Portuguese simply because this was the one with more students (649) on it. The article [1] combined Math and Portuguese into one single set, but that has an even smaller sample size." }, { "code": null, "e": 8520, "s": 8377, "text": "One of the main goals in this phase 1 was to create the artificial variable, get familiarized with this dataset, and check for missing values." }, { "code": null, "e": 8727, "s": 8520, "text": "As we can see in the plot 1, there were no missing values in this dataset. As a matter of fact, we have stated that previously, but here is the proof. Note that we added the retention variable in this plot." }, { "code": null, "e": 8993, "s": 8727, "text": "Additionally, I had to create dummy variables for some of the variables in the dataset that was not dummy-coded. At the end of this processing, a new csv file, just with the dummy codes, numeric values, and the predictor, can be exported using the R codes provided." }, { "code": null, "e": 9108, "s": 8993, "text": "Now that we have the green light, and the dataset ready for the initial assessments, we can move to the next step." }, { "code": null, "e": 9366, "s": 9108, "text": "This is where people go crazy on plotting histograms and box plots, isn’t it?! They are necessary, don’t get me wrong. We’ll see some of those in a sec. Also, you can check things like skewness, kurtosis and other basic statistical checklist on the R codes." }, { "code": null, "e": 9523, "s": 9366, "text": "In this simple bar chart, we can see the counts for the predictor variable, according to the weight we set for them when creating this artificial predictor." }, { "code": null, "e": 9640, "s": 9523, "text": "As we stated previously, students that were retained are flagged with “1” (538) and students not retained “0” (111)." }, { "code": null, "e": 9734, "s": 9640, "text": "Ultimately, it also shows the imbalance between the classifier, and we’ll take care of later." }, { "code": null, "e": 10014, "s": 9734, "text": "In the original article [1], the variable “G1” was a very strong predictor for student’s performance. The following scatterplot tells us a little bit of this expected positive correlation between the first grade (G1), and the final (G3). We can also spot some potential outliers." }, { "code": null, "e": 10242, "s": 10014, "text": "Continuing with this analysis, we were interested to see what could impact student’s performance on G1. For that, we focused on checking the studytime, and the freetime students have available, and we broke that down by gender." }, { "code": null, "e": 10515, "s": 10242, "text": "Okay, I surrender! Here is where I come up with a box plot for all variables. We can easily see here where we have presence of outliers, and quickly think about some option to whether or not deal with this issue. For this testing, we are not going to exclude the outliers." }, { "code": null, "e": 10629, "s": 10515, "text": "Once more, I want to give some attention to the variable G1, so let’s check it’s distribution as following below:" }, { "code": null, "e": 10746, "s": 10629, "text": "Considering this is a real world data, its distribution it’s not too bad, really. But, it’s not perfect — obviously." }, { "code": null, "e": 10938, "s": 10746, "text": "In conclusion of this Phase 3, we just want to check one more thing. That is, how G1 and G2 variables interact when adding the students into a bivariate plot, like the one as following below:" }, { "code": null, "e": 11427, "s": 10938, "text": "Think about this bivariate plot as being an ordinary box plot, but mixing together two variables instead of just one. Specifically, the numbers in blue could be the students ID (that’s not the case here because we don’t have students IDs in the dataset). Any student outside of the bigger ellipse would be an outlier. This could be helpful when trying to identify which students we would reach out in order to take some proactive actions towards to, let’s say, improve their grades on G3." }, { "code": null, "e": 11793, "s": 11427, "text": "This is where the fun starts. A good practice is to always check for collinearity/multicollinearity among the dataset. The easiest way to do that is by checking the correlation that independent and dependent variables may have. If two or more variables have a very strong or almost perfect correlation, that might be an indication of collinearity/multicollinearity." }, { "code": null, "e": 12244, "s": 11793, "text": "When facing a scenario where two or more variables have a strong correlation, we want to eliminate one of them. Why? Because in essence, you have two variables telling you the same story. But being a little be more technical, collinearity can mess up with the variance of at least one estimated regression coefficient, and this can lead to some regressor to come up with the wrong sign. Which can deteriorate your analysis and lead you the wrong way." }, { "code": null, "e": 12330, "s": 12244, "text": "Let’s check if we can spot some of this issue using the following Correlation Matrix:" }, { "code": null, "e": 12814, "s": 12330, "text": "There are some interesting correlations here, but mainly about the grades (G1, G2, and G3). They seem to have a very strong correlation, indicating some potential collinearity. We also see a strong negative correlation between grades and failures, as well as some other features. You can always check the actual numbers using a correlation table, or by simply adding them directly on the plot itself. For now, we just want to get a big picture of how the variables may be correlated." }, { "code": null, "e": 13092, "s": 12814, "text": "The Principal Component Analysis (PCA) is used to shape the original variables into a new set of features, which are linear combinations of the original variables. PCA’s main goal is to reduce the number of variables, but considering the original variation as much as possible." }, { "code": null, "e": 13460, "s": 13092, "text": "In the first component, or dimension, you’ll see a combination of the original variables whose sample variance is greatest amongst all possible linear combinations. In the second dimension, we account for the maximal proportion of the rest of the remaining variance, which can be uncorrelated with the first dimension. The other components follows a similar approach." }, { "code": null, "e": 13842, "s": 13460, "text": "When analyzing the output from running a PCA, we want to see a “Cumulative Proportion”, between dimension one and dimension two, that is significative. Generally speaking, a cumulative proportion equal or greater than 0.7 is considered to be very good. Meaning, the reduction from multiple variables into two dimensions can still have a strong representation of the entire dataset." }, { "code": null, "e": 14015, "s": 13842, "text": "One important thing prior to performing a PCA is to make sure the dataset is standardized. Deciding whether or not to remove outliers is also a good practice at this point." }, { "code": null, "e": 14174, "s": 14015, "text": "To kick off our analysis using PCA, we’ll start with a bar chart that displays all the cumulative proportions among the components as well as their variances." }, { "code": null, "e": 14411, "s": 14174, "text": "In essence, we are particularly interested in shrinking down our analysis up to the first two dimensions. We want to make sure that the cumulative proportion between them both are significant enough to “explain” the rest of the dataset." }, { "code": null, "e": 14684, "s": 14411, "text": "Unfortunately, as you’ll see in the next plot, the cumulative proportion is just about 21% (12.9% + 8.1%). So reducing into two dimensions would not be recommended, hence, we would be losing information and end up with two dimensions that don’t “explain” the dataset much." }, { "code": null, "e": 15129, "s": 14684, "text": "From the biplot, we can also see the correlation among the variables e.g., grades (G1, G2 and G3) and failures pointing on the opposite direction. Although the cumulative proportion of the two dimensions are not really useful when boils down to dimensionality reduction of this dataset, we want to check which are the contributions of the top ten variables for each dimension. This might help us to understand a lit bit more about this dataset." }, { "code": null, "e": 15533, "s": 15129, "text": "We can see that in Dim 1, grades are the variables that contributes the most in this dimension. But, it’s important to stress that we still have that assumption of collinearity present here. So this is one more clue that, indeed, we may have collinearity here because we see all grades with very similar contribution levels. On the other hand, in the Dim 2 the Walc feature has the highest contribution." }, { "code": null, "e": 15794, "s": 15533, "text": "In summary, if one asks what Dim 1 and Dim 2 is about, we can say that Dim 1 is about student grades, and Dim 2 student’s alcohol consumption. Meaning that we should expect some of these variables to have statistical significance when predicting the retention." }, { "code": null, "e": 16026, "s": 15794, "text": "All of this testing would be extremely helpful when guiding our decision about which variables to keep and which ones to disregard moving further in our analysis. Unfortunately, we won’t be using PCA to take any decisions just yet." }, { "code": null, "e": 16170, "s": 16026, "text": "Circling back, the hypothesis that we have collinearity is still alive, but how to measure that, and how to decide each variable to get rid of?" }, { "code": null, "e": 16549, "s": 16170, "text": "In the light of acknowledging this issue, and with this in mind, we’ll take advantage of VIF (Variable Inflation Factors) to detect and support our decision towards to the best approach when dealing with multicollinearity. To make it short, VIF detects how strong the correlation between variable is, and its score guide us on each variable(s) to drop and mitigate collinearity." }, { "code": null, "e": 16855, "s": 16549, "text": "As a general rule of thumb, VIF scores equal to or greater than 5 suggests collinearity. We will use 5 as our threshold here as well. As we can see below, the VIF output, which was based on a Logistic Regression, tell us that G2 and G3 are the variables we should disregard moving further on our analysis." }, { "code": null, "e": 17108, "s": 16855, "text": "Usually, you should get rid of one variable at the time and run the analysis again. That is, G2 would be the first to leave, and G3 the second. Here is a graphical way to visualize the before and after of the removal of these two variables (G2 and G3):" }, { "code": null, "e": 17489, "s": 17108, "text": "As a result of all this wrangling, we just got rid of two variables. That was not really productive in some sense. We still have a considerable large set of features that doesn’t tell much about what we trying to do. So, our shortcut will be using the Logistic Regression to not only help us in finding the predictors but also to eliminate non statistically significant variables." }, { "code": null, "e": 17615, "s": 17489, "text": "As has been noted from the Logit Regression output — on the left side — we have five variables that could work as predictors." }, { "code": null, "e": 17719, "s": 17615, "text": "However, only three of them has meaningful significance at 0.05 - we marked them down with a red arrow." }, { "code": null, "e": 17964, "s": 17719, "text": "The R-squared is a common indicator that some researchers may use when picking a model over others. Here, we would just use the AIC (Akaike Information Criterion) score to compare the output with 5 variable, against the output with 3 variables." }, { "code": null, "e": 18071, "s": 17964, "text": "As you can see below, eliminating two of the less significant variables doesn’t affect the AIC score much." }, { "code": null, "e": 18129, "s": 18071, "text": "All five statistically significant variables: AIC: 589.84" }, { "code": null, "e": 18197, "s": 18129, "text": "All three statistically significant variables at 0.05: AIC: 589.67M" }, { "code": null, "e": 18406, "s": 18197, "text": "Yes, the AIC for the whole dataset is bigger (622.4), but because it’s full of not really useful features, we are taking this curve here and deciding to work with only these three variables in the next phase." }, { "code": null, "e": 18643, "s": 18406, "text": "Considering all the challenges we have been facing so far, what could possibly go wrong when modeling the ML model? A poor performance model is what can go wrong. But, we want to get the best outcome possible, and at least a fair model." }, { "code": null, "e": 18889, "s": 18643, "text": "That being said, we gotta be real here, ML is really suitable for large datasets. But with some tweaks we can make it work. In this case, we’ll take advantage of a library called ROSE to balance the predictor and improve the model’s performance." }, { "code": null, "e": 19363, "s": 18889, "text": "Originally, our predictor was split this way: 1= 538, and 0= 111. As you can clearly see, we have an imbalanced classifier. We’ll artificially balance it to improve the outcome and mitigate some of the statistical issues that comes along with it. However, we’ll do that over the quantities for the trainSplit. Thus, our train set has a total of 553 students, where: 1= 458, and 0= 95. In other words, we’ll be balancing the training data and not the entire dataset for now." }, { "code": null, "e": 19609, "s": 19363, "text": "ROSE offers some different options to balance the classifier. We’ll cover 4 different approaches and pick the one that gives us the best result. Below are the codes we borrowed from the paper “ROSE: A Package for Binary Imbalanced Learning” [2]." }, { "code": null, "e": 20291, "s": 19609, "text": "### Balancing the data:# Resampling Option 1 (over):data.bal.ov <- ovun.sample(retention ~ ., data = trainSplit, method = \"over\", p=0.5, seed = 2)$datatable(data.bal.ov$retention)# Resampling Option 2 (under):data.bal.un <- ovun.sample(retention ~ ., data = trainSplit, method = \"under\", p = 0.5, seed = 2)$data table(data.bal.un$retention)# Resampling Option 3 (both):data.bal.ou <- ovun.sample(retention ~ ., data = trainSplit, method = \"both\", N = 553, p = 0.5, seed = 2)$data table(data.bal.ou$retention)# Resampling Option 4 (ROSE):data.rose <- ROSE(retention ~ ., data = trainSplit, seed = 1)$datatable(data.rose$retention)" }, { "code": null, "e": 20470, "s": 20291, "text": "Resampling Option 1 (over): Here we oversampling the “0” until it’s leveled with the counts of “ones”. As a result, we’ve balanced the classifier as following: 1= 458, and 0=453." }, { "code": null, "e": 20598, "s": 20470, "text": "Resampling Option 2 (under): By undersampling the majority class (1) to match the minority, we get this result: 1=97, and 0=95." }, { "code": null, "e": 20711, "s": 20598, "text": "Resampling Option 3 (both): In this case we use the entire train set (553) and split, such as: 1=281, and 0=272." }, { "code": null, "e": 20821, "s": 20711, "text": "Resampling Option 4 (ROSE): Finally, we use ROSE to split the data and we got this outcome: 1=293, and 0=260." }, { "code": null, "e": 20922, "s": 20821, "text": "Next, we train the classifiers, run the test set using Classification Trees, and plot the ROC Curve." }, { "code": null, "e": 21833, "s": 20922, "text": "# Training the Classifiers and run test set using classification trees:library(rpart)tree.ov <- rpart(retention ~ ., data = data.bal.ov)tree.un <- rpart(retention ~ ., data = data.bal.un)tree.ou <- rpart(retention ~ ., data = data.bal.ou)tree.rose <- rpart(retention ~ ., data = data.rose)# Predict in the new data (test):pred.tree.ov <- predict(tree.ov, newdata = testSplit)pred.tree.un <- predict(tree.un, newdata = testSplit)pred.tree.ou <- predict(tree.un, newdata = testSplit)pred.tree.rose <- predict(tree.rose, newdata = testSplit)# Plot ROC Curve - Model Evaluation:roc.curve(testSplit$retention, pred.tree.rose[,2], col = 0, main= \"AUC: 0.75\", lty = 1)roc.curve(testSplit$retention, pred.tree.ov[,2], add.roc = TRUE, col = 12, lty = 2) roc.curve(testSplit$retention, pred.tree.un[,2], add.roc = TRUE, col = 0, lty = 3) roc.curve(testSplit$retention, pred.tree.ou[,2], add.roc = TRUE, col = 0, lty = 4)" }, { "code": null, "e": 21929, "s": 21833, "text": "Resampling Option 2 (under) has given us the best AUC (Area Under the Curve) output. See below:" }, { "code": null, "e": 22086, "s": 21929, "text": "The AUC is an algorithm, which is widely used to measure the trade-off between the True Positive (TP) and False Positive (FP) rates of a said ML classifier." }, { "code": null, "e": 22234, "s": 22086, "text": "Likewise, a model that fails to predict will have a score of 0%, while a model that is able to make “perfect” predictions will get a score of 100%." }, { "code": null, "e": 22330, "s": 22234, "text": "Accordingly, our model scored 75%, which is not too bad, but a number ≥80% would be preferable." }, { "code": null, "e": 22480, "s": 22330, "text": "On the positive side, using the ROSE package gave us a huge improvement over the imbalanced scenario. So, we’ll celebrate this as a big victory. YAY!" }, { "code": null, "e": 22705, "s": 22480, "text": "Another very common way to measure classifiers is by getting a Decision Tree, which would give us more intuition on how the model is performing. We’ll skip that here, and move to the next and final piece of this ML analysis." }, { "code": null, "e": 22891, "s": 22705, "text": "A lot of people rely on accuracy to pick a ML model. That alone can be misleading, but since this is a very “quick and dirty” type of project, I’ll allow myself to experiment with that." }, { "code": null, "e": 22983, "s": 22891, "text": "Accuracy: it basically pinpoints the proportion of “1” and “0” that were flagged correctly." }, { "code": null, "e": 23078, "s": 22983, "text": "Kappa: tells us the performance of the classifier in comparison with values assigned randomly." }, { "code": null, "e": 23344, "s": 23078, "text": "Without delay, here is how we’ll handle this part of the analysis: we’ll again use ROSE to balance the entire dataset now (649 rows). This time we won’t split between train and test, and that is because the set is very small. We are going to use everything we have." }, { "code": null, "e": 23532, "s": 23344, "text": "Similarly, we’ll use the following code to balance the predictor, but as you’ll see, we are artificially duplicating the dataset up to 1298 observations, and using the “both” method here." }, { "code": null, "e": 23722, "s": 23532, "text": "# Create balanced training data for LR:dataC <- ovun.sample(retention ~ ., data = dataC, method = \"both\", N = 1298, seed =1)$data # 1298 (649x2)table(dataC$retention)" }, { "code": null, "e": 23942, "s": 23722, "text": "Therefore, we get the new balanced classifier such as: 1=652, and 0=646. Now, we will use the “mlbench” library to run a benchmark comparison between few different algorithms to see each one(s) has the best performance." }, { "code": null, "e": 24143, "s": 23942, "text": "As we can see above, the “best” algorithm for this analysis was the svm (Support Vector Machines), with an accuracy of almost 70%, and kappa of 39%. Those are fair results, but definitely not optimal." }, { "code": null, "e": 24391, "s": 24143, "text": "Keep in mind that when choosing each model to actually use in production, many other factors has to be taken in consideration, and not only the accuracy scores alone. For the purpose of what we were trying to accomplish, our ML analysis ends here." }, { "code": null, "e": 24656, "s": 24391, "text": "In conclusion, you saw that the three main predictors were Medu, famsup_yes, and Dalc. A next step would be getting the odds ratio out of the Logit Regression and make the analysis more interpretable. I’ll leave that for future improvements and save our time here." }, { "code": null, "e": 24933, "s": 24656, "text": "As a reminder, our goal here was to provide some guidelines of how to use multiple techniques to work with a small dataset and get a fair to good results. There are many other ways to tackle this problem, and here we are providing you a solid one - using a real world dataset." }, { "code": null, "e": 25124, "s": 24933, "text": "With a more well-designed dataset that is suited to predict retention, and with more observations, we can certainly expect to have better results. This analysis was created for that purpose." }, { "code": null, "e": 25343, "s": 25124, "text": "Ultimately, retention rates is one of the most important indicator in Higher Education, and this pipeline can be useful to further research on the subject, and for administrators to make better decisions based on data." }, { "code": null, "e": 25360, "s": 25343, "text": "‘Till next time!" }, { "code": null, "e": 25372, "s": 25360, "text": "References:" }, { "code": null, "e": 25645, "s": 25372, "text": "[1] P. Cortez and A. Silva. Using Data Mining to Predict Secondary School Student Performance. In A. Brito and J. Teixeira Eds., Proceedings of 5th FUture BUsiness TEChnology Conference (FUBUTEC 2008) pp. 5–12, Porto, Portugal, April, 2008, EUROSIS, ISBN 978–9077381–39–7." }, { "code": null, "e": 25802, "s": 25645, "text": "[2] Nicola Lunardon, Giovanna Menardi, and Nicola Torelli. ROSE: A Package for Binay Imbalanced Learning. The R Journal Vol. 6/1, June 2014. ISSN 2073-4859." } ]
Java Numeric Literals with Underscore - GeeksforGeeks
24 Nov, 2020 A new feature was introduced by JDK 7 which allows writing numeric literals using the underscore character. Numeric literals are broken to enhance the readability. This feature is used to separate a group of digits in numeric literal which can improve the readability of source code. There are some rules the programmer has to follow before using numeric literals like 1. We should not use underscore before or after an integer number. int p = _10; // Error, this is an identifier, not a numeric literal int p = 10_; // Error, cannot put underscores at the end of a number 2. We should not use underscore before or after a decimal point in a floating-point literal. float a = 10._0f; // Error, cannot put underscores adjacent to a decimal point float a = 10_.0f; // Error, cannot put underscores adjacent to a decimal point 3. We should not use prior to L or F suffix in long and float integers respectively. long a = 10_100_00_L; // Error, cannot put underscores prior to an L suffix float a = 10_100_00_F; // Error, cannot put underscores prior to an F suffix 4. We cannot use underscore in positions where a string of digits is expected. Example Java // Java program to demonstrate Numeric Literals with// Underscore public class Example { public static void main(String args[]) { // Underscore in integral literal int a = 7_7; System.out.println("The value of a is=" + a); // Underscore in floating literal double p = 11.239_67_45; System.out.println("The value of p is=" + p); float q = 16.45_56f; System.out.println("The value of q is=" + q); // Underscore in binary literal int c = 0B01_01; System.out.println("c = " + c); // Underscore in hexadecimal literal int d = 0x2_2; System.out.println("d = " + d); // Underscore in octal literal int e = 02_3; System.out.println("e = " + e); }} The value of a is=77 The value of p is=11.2396745 The value of q is=16.4556 c = 5 d = 34 e = 19 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23948, "s": 23920, "text": "\n24 Nov, 2020" }, { "code": null, "e": 24318, "s": 23948, "text": " A new feature was introduced by JDK 7 which allows writing numeric literals using the underscore character. Numeric literals are broken to enhance the readability. This feature is used to separate a group of digits in numeric literal which can improve the readability of source code. There are some rules the programmer has to follow before using numeric literals like" }, { "code": null, "e": 24385, "s": 24318, "text": "1. We should not use underscore before or after an integer number." }, { "code": null, "e": 24526, "s": 24385, "text": "int p = _10; // Error, this is an identifier, not a numeric literal \nint p = 10_; // Error, cannot put underscores at the end of a number " }, { "code": null, "e": 24619, "s": 24526, "text": "2. We should not use underscore before or after a decimal point in a floating-point literal." }, { "code": null, "e": 24781, "s": 24619, "text": "float a = 10._0f; // Error, cannot put underscores adjacent to a decimal point \nfloat a = 10_.0f; // Error, cannot put underscores adjacent to a decimal point " }, { "code": null, "e": 24866, "s": 24781, "text": "3. We should not use prior to L or F suffix in long and float integers respectively." }, { "code": null, "e": 25023, "s": 24866, "text": "long a = 10_100_00_L; // Error, cannot put underscores prior to an L suffix \nfloat a = 10_100_00_F; // Error, cannot put underscores prior to an F suffix " }, { "code": null, "e": 25102, "s": 25023, "text": "4. We cannot use underscore in positions where a string of digits is expected." }, { "code": null, "e": 25110, "s": 25102, "text": "Example" }, { "code": null, "e": 25115, "s": 25110, "text": "Java" }, { "code": "// Java program to demonstrate Numeric Literals with// Underscore public class Example { public static void main(String args[]) { // Underscore in integral literal int a = 7_7; System.out.println(\"The value of a is=\" + a); // Underscore in floating literal double p = 11.239_67_45; System.out.println(\"The value of p is=\" + p); float q = 16.45_56f; System.out.println(\"The value of q is=\" + q); // Underscore in binary literal int c = 0B01_01; System.out.println(\"c = \" + c); // Underscore in hexadecimal literal int d = 0x2_2; System.out.println(\"d = \" + d); // Underscore in octal literal int e = 02_3; System.out.println(\"e = \" + e); }}", "e": 25894, "s": 25115, "text": null }, { "code": null, "e": 25991, "s": 25894, "text": "The value of a is=77\nThe value of p is=11.2396745\nThe value of q is=16.4556\nc = 5\nd = 34\ne = 19\n" }, { "code": null, "e": 25998, "s": 25991, "text": "Picked" }, { "code": null, "e": 26003, "s": 25998, "text": "Java" }, { "code": null, "e": 26017, "s": 26003, "text": "Java Programs" }, { "code": null, "e": 26022, "s": 26017, "text": "Java" }, { "code": null, "e": 26120, "s": 26022, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26135, "s": 26120, "text": "Stream In Java" }, { "code": null, "e": 26181, "s": 26135, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26202, "s": 26181, "text": "Constructors in Java" }, { "code": null, "e": 26221, "s": 26202, "text": "Exceptions in Java" }, { "code": null, "e": 26251, "s": 26221, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26295, "s": 26251, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 26321, "s": 26295, "text": "Java Programming Examples" }, { "code": null, "e": 26355, "s": 26321, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26402, "s": 26355, "text": "Implementing a Linked List in Java using Class" } ]
XPath - Axes
As location path defines the location of a node using absolute or relative path, axes are used to identify elements by their relationship like parent, child, sibling, etc. Axes are named so because they refer to axis on which elements are lying relative to an element. Following is the list of various Axis values. ancestor Represents the ancestors of the current node which include the parents up to the root node. ancestor-or-self Represents the current node and it's ancestors. attribute Represents the attributes of the current node. child Represents the children of the current node. descendant Represents the descendants of the current node. Descendants include the node's children upto the leaf node(no more children). descendant-or-self Represents the current node and it's descendants. following Represents all nodes that come after the current node. following-sibling Represents the following siblings of the context node. Siblings are at the same level as the current node and share it's parent. namespace Represents the namespace of the current node. parent Represents the parent of the current node. preceding Represents all nodes that come before the current node (i.e. before it's opening tag). self Represents the current node. Following are a few examples on the uses of axes. firstname − select firstname related to student nodes. <p><xsl:value-of select = "firstname"/></p> <xsl:value-of select = "/class/student/preceding-sibling::comment()"/> In this example, we've created a sample XML document students.xml and its stylesheet document students.xsl which uses the XPath expressions. Following is the sample XML used. <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <!-- Comment: This is a list of student --> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/" > <html> <body> <xsl:value-of select = "/class/student/preceding-sibling::comment()"/> <br/> <xsl:text>First Student: </xsl:text> <xsl:value-of select = "/class/student/child::firstname" /> </body> </html> </xsl:template> </xsl:stylesheet> 90 Lectures 20 hours Arun Motoori 23 Lectures 8 hours Sanjay Kumar 13 Lectures 1.5 hours Sanjay Kumar 24 Lectures 1.5 hours Sanjay Kumar 47 Lectures 3 hours Krishna Sakinala Print Add Notes Bookmark this page
[ { "code": null, "e": 1998, "s": 1729, "text": "As location path defines the location of a node using absolute or relative path, axes are used to identify elements by their relationship like parent, child, sibling, etc. Axes are named so because they refer to axis on which elements are lying relative to an element." }, { "code": null, "e": 2044, "s": 1998, "text": "Following is the list of various Axis values." }, { "code": null, "e": 2053, "s": 2044, "text": "ancestor" }, { "code": null, "e": 2145, "s": 2053, "text": "Represents the ancestors of the current node which include the parents up to the root node." }, { "code": null, "e": 2162, "s": 2145, "text": "ancestor-or-self" }, { "code": null, "e": 2210, "s": 2162, "text": "Represents the current node and it's ancestors." }, { "code": null, "e": 2220, "s": 2210, "text": "attribute" }, { "code": null, "e": 2267, "s": 2220, "text": "Represents the attributes of the current node." }, { "code": null, "e": 2273, "s": 2267, "text": "child" }, { "code": null, "e": 2318, "s": 2273, "text": "Represents the children of the current node." }, { "code": null, "e": 2329, "s": 2318, "text": "descendant" }, { "code": null, "e": 2455, "s": 2329, "text": "Represents the descendants of the current node. Descendants include the node's children upto the leaf node(no more children)." }, { "code": null, "e": 2474, "s": 2455, "text": "descendant-or-self" }, { "code": null, "e": 2524, "s": 2474, "text": "Represents the current node and it's descendants." }, { "code": null, "e": 2534, "s": 2524, "text": "following" }, { "code": null, "e": 2589, "s": 2534, "text": "Represents all nodes that come after the current node." }, { "code": null, "e": 2607, "s": 2589, "text": "following-sibling" }, { "code": null, "e": 2736, "s": 2607, "text": "Represents the following siblings of the context node. Siblings are at the same level as the current node and share it's parent." }, { "code": null, "e": 2746, "s": 2736, "text": "namespace" }, { "code": null, "e": 2792, "s": 2746, "text": "Represents the namespace of the current node." }, { "code": null, "e": 2799, "s": 2792, "text": "parent" }, { "code": null, "e": 2842, "s": 2799, "text": "Represents the parent of the current node." }, { "code": null, "e": 2852, "s": 2842, "text": "preceding" }, { "code": null, "e": 2939, "s": 2852, "text": "Represents all nodes that come before the current node (i.e. before it's opening tag)." }, { "code": null, "e": 2944, "s": 2939, "text": "self" }, { "code": null, "e": 2973, "s": 2944, "text": "Represents the current node." }, { "code": null, "e": 3023, "s": 2973, "text": "Following are a few examples on the uses of axes." }, { "code": null, "e": 3078, "s": 3023, "text": "firstname − select firstname related to student nodes." }, { "code": null, "e": 3193, "s": 3078, "text": "<p><xsl:value-of select = \"firstname\"/></p>\n<xsl:value-of select = \"/class/student/preceding-sibling::comment()\"/>" }, { "code": null, "e": 3334, "s": 3193, "text": "In this example, we've created a sample XML document students.xml and its stylesheet document students.xsl which uses the XPath expressions." }, { "code": null, "e": 3368, "s": 3334, "text": "Following is the sample XML used." }, { "code": null, "e": 4017, "s": 3368, "text": "<?xml version = \"1.0\"?>\n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?>\n<class>\n <!-- Comment: This is a list of student -->\n <student rollno = \"393\">\n <firstname>Dinkar</firstname>\n <lastname>Kad</lastname>\n <nickname>Dinkar</nickname>\n <marks>85</marks>\n </student>\n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>Vinni</nickname>\n <marks>95</marks>\n </student>\n <student rollno = \"593\">\n <firstname>Jasvir</firstname>\n <lastname>Singh</lastname>\n <nickname>Jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 4506, "s": 4017, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<xsl:stylesheet version = \"1.0\"\n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\"> \n\t\n <xsl:template match = \"/\" >\n <html>\n <body> \n <xsl:value-of select = \"/class/student/preceding-sibling::comment()\"/>\n <br/>\n <xsl:text>First Student: </xsl:text>\n <xsl:value-of select = \"/class/student/child::firstname\" /> \n </body>\n </html>\n </xsl:template>\n</xsl:stylesheet>" }, { "code": null, "e": 4540, "s": 4506, "text": "\n 90 Lectures \n 20 hours \n" }, { "code": null, "e": 4554, "s": 4540, "text": " Arun Motoori" }, { "code": null, "e": 4587, "s": 4554, "text": "\n 23 Lectures \n 8 hours \n" }, { "code": null, "e": 4601, "s": 4587, "text": " Sanjay Kumar" }, { "code": null, "e": 4636, "s": 4601, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4650, "s": 4636, "text": " Sanjay Kumar" }, { "code": null, "e": 4685, "s": 4650, "text": "\n 24 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4699, "s": 4685, "text": " Sanjay Kumar" }, { "code": null, "e": 4732, "s": 4699, "text": "\n 47 Lectures \n 3 hours \n" }, { "code": null, "e": 4750, "s": 4732, "text": " Krishna Sakinala" }, { "code": null, "e": 4757, "s": 4750, "text": " Print" }, { "code": null, "e": 4768, "s": 4757, "text": " Add Notes" } ]
Extracting ML-Features from Graph Data with DeepGL on Neo4j | by Mark Needham | Towards Data Science
In 2013 Tomas Mikolov and his Google colleagues released a paper describing word2vec, and popularised the idea of generating embeddings to represent pieces of data. An embedding is an array or vector of numbers used to represent something, in word2vec’s case: a word. Adrian Colyer has a nice diagram showing a very simple hot encoding representation of a vocabulary of words (with one element “hot” below): In this example we have one column for each word and the vector for one word will have a 1 in the appropriate column and 0s everywhere else. With this simple representation we can’t really do any meaningful comparisons between our embeddings, but word2vec goes much further than this and comes up with a representation for each word that is a distribution of weights across those elements. For example, we might end up with a representation for words that looks like this: Since word2vec was released other people have used similar approaches to come up with embeddings for things other than words. Pinterest created pin2vec which is used to recommend pins to users and Airbnb use embeddings to find similar property listings. Embeddings can be considered as an implementation of Representational learning where we automatically come up with features to feed into our machine learning models rather than creating them by hand. For example, the output of these algorithms could be used as the input to a Tensorflow model. We could also build a kNN similarity graph from the embeddings using the Cosine Similarity procedure introduced in the 3.4.7.0 release of the Graph Algorithms library. The similarity graph could then be used to make recommendations as part of a k-Nearest Neighbors query. There are several algorithms that can be used to generate graph embeddings. These are the ones that we’re aware of: node2Vec struc2vec: Learning Node Representations from Structural Identity DeepWalk — Online Learning of Social Representations The idea is the same as for word embedding algorithms. We want to determine a vector representation for each entity (usually nodes) in our graph and then feed those representations into a machine learning algorithm. A recent addition to the list is Deep Feature Learning for Graphs (DeepGL), created by Ryan A. Rossi, Rong Zhou, and Nesreen K. Ahmed. This one looked very interesting to us as it’s specifically designed to keep memory usage low and also returns the names of the features that it comes up with, which is helpful in these days of machine learning model interpretability and feature extraction. Another nice feature is, that it allows you to also pass numeric node attributes to the algorithm whereas the others only rely on the graph structure. We start by building a set of base features for each node: in-degree, out-degree, and both-degree. We can also choose to include any other numeric properties (or projections) of the node. The paper describes more base features that can be generated through local graphlet decomposition, but we haven’t implemented that yet. For a very simple graph containing 4 nodes, these base features may look like this: We then apply logarithmic binning by column on these values. This results in the following embedding: Next we apply a set of operators over this set of features for the (in, out, whole) neighbourhoods of each node. The operators we apply are Hadamard, mean, sum, maximum, L1 norm, and RBF. This means that for, say, the sum operator we will create 9 new columns for each node: sum of the in-degree of our in neighbourhood sum of the out-degree of our in neighbourhood sum of the both-degree of our in neighbourhood sum of the in-degree of our out neighbourhood sum of the out-degree of our out neighbourhood sum of the both-degree of our out neighbourhood sum of the in-degree of our whole neighbourhood sum of the out-degree of our whole neighbourhood sum of the both-degree of our whole neighbourhood Let’s have a look at a what would happen if we just apply the sum operator to the in neighbourhood. We end up with 3 extra columns, summing up the scores of each nodes’ neighbors for in-degree, out-degree, and both-degree. Our resulting set of features would look like this: We calculate the same values for our other neighbourhoods and for all the other operators as well which give us a matrix of 57 columns and 4 rows. We then apply a diffusion process where each node distributes its score to its neighbours. The way we’ve implemented this is that each node takes the mean value of all of its neighbors for each feature. The diffusion process excludes the base features, so in our example we’ll only diffuse sum-in-in, sum-in-out, and sum-in-both. Our resulting set of features would look like this: Before we continued to the next stage we apply logarithmic binning again, which results in this set of features: After that step, we apply feature pruning, which involves running the weakly connected components algorithm over a feature similarity graph and then keeping only a single column per connected component. We work out the similarity of features by doing an item wise comparison of values in each column. If all values across two columns are identical then we’d have a similarity score of 1 for that column. This is the case for diffused-sum-in-out and diffused-sum-in-both in our example, as well as a few other pairs of columns. Assuming a pruning lambda of 0.7 to remove lower ranked relationships, this is the feature graph that we end up with: The connected component algorithm would give us 3 components: sum-in-in sum-in-both, in-degree, sum-in-out both-degree, diffused-sum-in-both, diffused-sum-in-out, out-degree, diffused-sum-in-in We bias towards keeping features that we had from an earlier iteration, which in this case means the base features. We keep one feature per component, which in this example means that we keep: sum-in-in in-degree out-degree or both-degree (we randomly choose between these) We repeat this process for as many iterations as we want. On the 2nd and subsequent iterations, we’ll apply the operators to the features that we have left from the previous iteration rather than applying them to the base features again. Once the algorithm has completed we’ll have vectors of equal length for each node in our graph. In our example these vectors would be: So the vector for node 0 is [0,0,0], for node 1 it’s [1,1,0], for node 2 it’s [2,0,2] and for node 3 it’s [0,2,1] Over the last couple of months Pete Meltzer, who works at BrainTree as a Research Associate and is s`tudying for a PhD at UCL, and I have been implementing this algorithm as a Neo4j procedure and now have a version ready for you to try out! The DeepGL algorithm is available as part of the ml-models library. You’ll want to grab the 1.0.2 release. Once you’ve got that installed (instructions in the repository) you’ll find two versions of the algorithm that you can use: embedding.deepgl — this stores the embeddings as a property on each node embedding.deepgl.stream — this returns a stream of node, embedding While you’re playing around with the algorithm the streaming probably makes sense, but once you want to use it on a proper dataset I’d suggest using the first version. This is the signature of the algorithm: CALL embedding.deepgl("NodeLabel" ,"RelationshipType", { nodeFeatures: [string] pruningLambda: double, diffusions: integer, iterations: integer, writeProperty: string}) nodeFeatures — contains an array of additional property names that you want to use as part of the algorithms base features (defaults to []) pruningLambda — how strict the algorithm should be when removing similar features. Lower means prune morse aggressively (defaults to 0.7) diffusions — how many diffusions the algorithm should execute (defaults to 10)s iterations — how many iterations the algorithm should run for (defaults to 10) writeProperty — the name of the property in which the embedding array will be stored (defaults to “deepgl”) You can also utilize Graph projections (views) by passing the graph: “cypher” config parameter and providing Cypher queries for node-id- and relationship-lists, instead of NodeLabel and RelationshipType. The defaults we’ve set seemed to work well on the datasets we’ve tested against, but they are different than the ones suggested in the paper so YMMV. We’ve tried the algorithm out on the Enzyme and EU network datasets referenced in the paper and it seems to work reasonably well when compared with embeddings created using other algorithms. We hope this algorithm is useful and that you’re able to use it against your own datasets. If you have any questions or suggestions on what we should do next let us know in the comments or send us an email to [email protected]. You can also ask any questions in our new Neo4j community forum. If you want to get in contact with Pete Meltzer you can reach him at [email protected].
[ { "code": null, "e": 337, "s": 172, "text": "In 2013 Tomas Mikolov and his Google colleagues released a paper describing word2vec, and popularised the idea of generating embeddings to represent pieces of data." }, { "code": null, "e": 440, "s": 337, "text": "An embedding is an array or vector of numbers used to represent something, in word2vec’s case: a word." }, { "code": null, "e": 580, "s": 440, "text": "Adrian Colyer has a nice diagram showing a very simple hot encoding representation of a vocabulary of words (with one element “hot” below):" }, { "code": null, "e": 721, "s": 580, "text": "In this example we have one column for each word and the vector for one word will have a 1 in the appropriate column and 0s everywhere else." }, { "code": null, "e": 970, "s": 721, "text": "With this simple representation we can’t really do any meaningful comparisons between our embeddings, but word2vec goes much further than this and comes up with a representation for each word that is a distribution of weights across those elements." }, { "code": null, "e": 1053, "s": 970, "text": "For example, we might end up with a representation for words that looks like this:" }, { "code": null, "e": 1307, "s": 1053, "text": "Since word2vec was released other people have used similar approaches to come up with embeddings for things other than words. Pinterest created pin2vec which is used to recommend pins to users and Airbnb use embeddings to find similar property listings." }, { "code": null, "e": 1507, "s": 1307, "text": "Embeddings can be considered as an implementation of Representational learning where we automatically come up with features to feed into our machine learning models rather than creating them by hand." }, { "code": null, "e": 1601, "s": 1507, "text": "For example, the output of these algorithms could be used as the input to a Tensorflow model." }, { "code": null, "e": 1769, "s": 1601, "text": "We could also build a kNN similarity graph from the embeddings using the Cosine Similarity procedure introduced in the 3.4.7.0 release of the Graph Algorithms library." }, { "code": null, "e": 1873, "s": 1769, "text": "The similarity graph could then be used to make recommendations as part of a k-Nearest Neighbors query." }, { "code": null, "e": 1989, "s": 1873, "text": "There are several algorithms that can be used to generate graph embeddings. These are the ones that we’re aware of:" }, { "code": null, "e": 1998, "s": 1989, "text": "node2Vec" }, { "code": null, "e": 2064, "s": 1998, "text": "struc2vec: Learning Node Representations from Structural Identity" }, { "code": null, "e": 2117, "s": 2064, "text": "DeepWalk — Online Learning of Social Representations" }, { "code": null, "e": 2333, "s": 2117, "text": "The idea is the same as for word embedding algorithms. We want to determine a vector representation for each entity (usually nodes) in our graph and then feed those representations into a machine learning algorithm." }, { "code": null, "e": 2468, "s": 2333, "text": "A recent addition to the list is Deep Feature Learning for Graphs (DeepGL), created by Ryan A. Rossi, Rong Zhou, and Nesreen K. Ahmed." }, { "code": null, "e": 2877, "s": 2468, "text": "This one looked very interesting to us as it’s specifically designed to keep memory usage low and also returns the names of the features that it comes up with, which is helpful in these days of machine learning model interpretability and feature extraction. Another nice feature is, that it allows you to also pass numeric node attributes to the algorithm whereas the others only rely on the graph structure." }, { "code": null, "e": 3065, "s": 2877, "text": "We start by building a set of base features for each node: in-degree, out-degree, and both-degree. We can also choose to include any other numeric properties (or projections) of the node." }, { "code": null, "e": 3201, "s": 3065, "text": "The paper describes more base features that can be generated through local graphlet decomposition, but we haven’t implemented that yet." }, { "code": null, "e": 3285, "s": 3201, "text": "For a very simple graph containing 4 nodes, these base features may look like this:" }, { "code": null, "e": 3387, "s": 3285, "text": "We then apply logarithmic binning by column on these values. This results in the following embedding:" }, { "code": null, "e": 3527, "s": 3387, "text": "Next we apply a set of operators over this set of features for the (in, out, whole) neighbourhoods of each node. The operators we apply are" }, { "code": null, "e": 3537, "s": 3527, "text": "Hadamard," }, { "code": null, "e": 3543, "s": 3537, "text": "mean," }, { "code": null, "e": 3548, "s": 3543, "text": "sum," }, { "code": null, "e": 3557, "s": 3548, "text": "maximum," }, { "code": null, "e": 3566, "s": 3557, "text": "L1 norm," }, { "code": null, "e": 3575, "s": 3566, "text": "and RBF." }, { "code": null, "e": 3662, "s": 3575, "text": "This means that for, say, the sum operator we will create 9 new columns for each node:" }, { "code": null, "e": 3707, "s": 3662, "text": "sum of the in-degree of our in neighbourhood" }, { "code": null, "e": 3753, "s": 3707, "text": "sum of the out-degree of our in neighbourhood" }, { "code": null, "e": 3800, "s": 3753, "text": "sum of the both-degree of our in neighbourhood" }, { "code": null, "e": 3846, "s": 3800, "text": "sum of the in-degree of our out neighbourhood" }, { "code": null, "e": 3893, "s": 3846, "text": "sum of the out-degree of our out neighbourhood" }, { "code": null, "e": 3941, "s": 3893, "text": "sum of the both-degree of our out neighbourhood" }, { "code": null, "e": 3989, "s": 3941, "text": "sum of the in-degree of our whole neighbourhood" }, { "code": null, "e": 4038, "s": 3989, "text": "sum of the out-degree of our whole neighbourhood" }, { "code": null, "e": 4088, "s": 4038, "text": "sum of the both-degree of our whole neighbourhood" }, { "code": null, "e": 4311, "s": 4088, "text": "Let’s have a look at a what would happen if we just apply the sum operator to the in neighbourhood. We end up with 3 extra columns, summing up the scores of each nodes’ neighbors for in-degree, out-degree, and both-degree." }, { "code": null, "e": 4363, "s": 4311, "text": "Our resulting set of features would look like this:" }, { "code": null, "e": 4510, "s": 4363, "text": "We calculate the same values for our other neighbourhoods and for all the other operators as well which give us a matrix of 57 columns and 4 rows." }, { "code": null, "e": 4713, "s": 4510, "text": "We then apply a diffusion process where each node distributes its score to its neighbours. The way we’ve implemented this is that each node takes the mean value of all of its neighbors for each feature." }, { "code": null, "e": 4840, "s": 4713, "text": "The diffusion process excludes the base features, so in our example we’ll only diffuse sum-in-in, sum-in-out, and sum-in-both." }, { "code": null, "e": 4892, "s": 4840, "text": "Our resulting set of features would look like this:" }, { "code": null, "e": 5005, "s": 4892, "text": "Before we continued to the next stage we apply logarithmic binning again, which results in this set of features:" }, { "code": null, "e": 5208, "s": 5005, "text": "After that step, we apply feature pruning, which involves running the weakly connected components algorithm over a feature similarity graph and then keeping only a single column per connected component." }, { "code": null, "e": 5532, "s": 5208, "text": "We work out the similarity of features by doing an item wise comparison of values in each column. If all values across two columns are identical then we’d have a similarity score of 1 for that column. This is the case for diffused-sum-in-out and diffused-sum-in-both in our example, as well as a few other pairs of columns." }, { "code": null, "e": 5650, "s": 5532, "text": "Assuming a pruning lambda of 0.7 to remove lower ranked relationships, this is the feature graph that we end up with:" }, { "code": null, "e": 5712, "s": 5650, "text": "The connected component algorithm would give us 3 components:" }, { "code": null, "e": 5722, "s": 5712, "text": "sum-in-in" }, { "code": null, "e": 5757, "s": 5722, "text": "sum-in-both, in-degree, sum-in-out" }, { "code": null, "e": 5844, "s": 5757, "text": "both-degree, diffused-sum-in-both, diffused-sum-in-out, out-degree, diffused-sum-in-in" }, { "code": null, "e": 6037, "s": 5844, "text": "We bias towards keeping features that we had from an earlier iteration, which in this case means the base features. We keep one feature per component, which in this example means that we keep:" }, { "code": null, "e": 6047, "s": 6037, "text": "sum-in-in" }, { "code": null, "e": 6057, "s": 6047, "text": "in-degree" }, { "code": null, "e": 6118, "s": 6057, "text": "out-degree or both-degree (we randomly choose between these)" }, { "code": null, "e": 6356, "s": 6118, "text": "We repeat this process for as many iterations as we want. On the 2nd and subsequent iterations, we’ll apply the operators to the features that we have left from the previous iteration rather than applying them to the base features again." }, { "code": null, "e": 6452, "s": 6356, "text": "Once the algorithm has completed we’ll have vectors of equal length for each node in our graph." }, { "code": null, "e": 6491, "s": 6452, "text": "In our example these vectors would be:" }, { "code": null, "e": 6605, "s": 6491, "text": "So the vector for node 0 is [0,0,0], for node 1 it’s [1,1,0], for node 2 it’s [2,0,2] and for node 3 it’s [0,2,1]" }, { "code": null, "e": 6846, "s": 6605, "text": "Over the last couple of months Pete Meltzer, who works at BrainTree as a Research Associate and is s`tudying for a PhD at UCL, and I have been implementing this algorithm as a Neo4j procedure and now have a version ready for you to try out!" }, { "code": null, "e": 6953, "s": 6846, "text": "The DeepGL algorithm is available as part of the ml-models library. You’ll want to grab the 1.0.2 release." }, { "code": null, "e": 7077, "s": 6953, "text": "Once you’ve got that installed (instructions in the repository) you’ll find two versions of the algorithm that you can use:" }, { "code": null, "e": 7150, "s": 7077, "text": "embedding.deepgl — this stores the embeddings as a property on each node" }, { "code": null, "e": 7217, "s": 7150, "text": "embedding.deepgl.stream — this returns a stream of node, embedding" }, { "code": null, "e": 7385, "s": 7217, "text": "While you’re playing around with the algorithm the streaming probably makes sense, but once you want to use it on a proper dataset I’d suggest using the first version." }, { "code": null, "e": 7425, "s": 7385, "text": "This is the signature of the algorithm:" }, { "code": null, "e": 7600, "s": 7425, "text": "CALL embedding.deepgl(\"NodeLabel\" ,\"RelationshipType\", { nodeFeatures: [string] pruningLambda: double, diffusions: integer, iterations: integer, writeProperty: string})" }, { "code": null, "e": 7740, "s": 7600, "text": "nodeFeatures — contains an array of additional property names that you want to use as part of the algorithms base features (defaults to [])" }, { "code": null, "e": 7878, "s": 7740, "text": "pruningLambda — how strict the algorithm should be when removing similar features. Lower means prune morse aggressively (defaults to 0.7)" }, { "code": null, "e": 7958, "s": 7878, "text": "diffusions — how many diffusions the algorithm should execute (defaults to 10)s" }, { "code": null, "e": 8037, "s": 7958, "text": "iterations — how many iterations the algorithm should run for (defaults to 10)" }, { "code": null, "e": 8145, "s": 8037, "text": "writeProperty — the name of the property in which the embedding array will be stored (defaults to “deepgl”)" }, { "code": null, "e": 8349, "s": 8145, "text": "You can also utilize Graph projections (views) by passing the graph: “cypher” config parameter and providing Cypher queries for node-id- and relationship-lists, instead of NodeLabel and RelationshipType." }, { "code": null, "e": 8499, "s": 8349, "text": "The defaults we’ve set seemed to work well on the datasets we’ve tested against, but they are different than the ones suggested in the paper so YMMV." }, { "code": null, "e": 8690, "s": 8499, "text": "We’ve tried the algorithm out on the Enzyme and EU network datasets referenced in the paper and it seems to work reasonably well when compared with embeddings created using other algorithms." }, { "code": null, "e": 8781, "s": 8690, "text": "We hope this algorithm is useful and that you’re able to use it against your own datasets." }, { "code": null, "e": 8982, "s": 8781, "text": "If you have any questions or suggestions on what we should do next let us know in the comments or send us an email to [email protected]. You can also ask any questions in our new Neo4j community forum." } ]
Introduction to Regular Expressions (Regex) in R | Towards Data Science
We live in a data-centric age. Data has been described as the new oil. But just like oil, data isn’t always useful in its raw form. One form of data that is particularly hard to use in its raw form is unstructured data. A lot of data is unstructured data. Unstructured data doesn’t fit nicely into a format for analysis, like an Excel spreadsheet or a data frame. Text data is a common type of unstructured data and this makes it difficult to work with. Enter regular expressions, or regex for short. They may look a little intimidating at first, but once you get started, using them will be a picnic! More comfortable with python? Try my tutorial for using regex with python instead: towardsdatascience.com We’ll use the stringr library. The stringr library is built off a C library, so all of its functions are very fast. To install and load the stringr library in R, use the following commands: See how easy that is? To make things even easier, most function names in the stringr package start with str. Let’s take a look at a couple of the functions we have available to us in this module: str_extract_all(string, pattern): This function returns a list with a vector containing all instances of pattern in stringstr_replace_all(string, pattern, replacement): This function returns string with instances of pattern in string replaced with replacement str_extract_all(string, pattern): This function returns a list with a vector containing all instances of pattern in string str_replace_all(string, pattern, replacement): This function returns string with instances of pattern in string replaced with replacement You may have already used these functions. They have pretty straightforward applications without adding regex. Think back to the times before social distancing and imagine a nice picnic in the park, like the image above. Here’s an example string with what everyone is bringing to the picnic. We can use it to demonstrate the basic usage of the regex functions: basicString <- "Drew has 3 watermelons, Alex has 4 hamburgers, Karina has 12 tamales, and Anna has 6 soft pretzels" If I want to pull every instance of one person’s name from this string, I would simply pass the name and basic_string to str_extract_all(): The result will be a list with all occurrences of the pattern. Using this example, basicExtractAll will have the following list with 1 vector as output: [[1]][1] "Drew" Now let’s imagine that Alex left his 4 hamburgers unattended at the picnic and they were stolen by Shawn. str_replace_all can replace any instances of Alex with Shawn: The resulting string will show that Shawn now has 4 hamburgers. What a lucky guy 🍔. "Drew has 3 watermelons, Shawn has 4 hamburgers, Karina has 12 tamales, and Anna has 6 soft pretzels" The examples so far are pretty basic. There is a time and place for them, but what if we want to know how many total food items there are at the picnic? Who are all the people with items? What if we need this data in a data frame for further analysis? This is where you will start to see the benefits of regex. There are several concepts that drive regex: Character setsMeta charactersQuantifiersCapture Groups Character sets Meta characters Quantifiers Capture Groups This is not an exhaustive list, but is plenty to help us hit the ground running. Character sets represent options inside of brackets, with regex matching only one of the options. There are multiple things we can do with character sets: Match a group of characters: We can find all of the vowels in our string by putting every vowel in brackets, for example,[aeiou] [[1]] [1] "e" "a" "a" "e" "e" "o" "e" "a" "a" "u" "e" "a" "i" "a"[15] "a" "a" "a" "e" "a" "a" "a" "o" "e" "e" Match a range of characters: We can find any capital letter from “A” to “F,” by using a hyphen, [A-F]. Character sets are case sensitive, so [A-F] is not the same as [a-f] [[1]][1] "D" "A" "K" "A" Match a range of numbers: We can find numbers between a range by adding numbers to our character set, [0-9] to find any number. Notice that the numbers are extracted as strings, not converted to numbers [[1]][1] "3" "4" "1" "2" "6" Character sets can contain everything from this section simultaneously, so something like [A-Ct-z7-9] is still valid. It will match every character from capital “A” to capital “C,” lowercase “t” to lowercase “z,” and 7 through 9. So far we can’t answer any of the questions posed earlier with just bracket groups. Let’s add some more weapons to our regex arsenal. Meta characters represent a type of character. They will typically begin with a backslash \. Since the backslash \ is a special character in R, it needs to be escaped each time it is used with another backslash. In other words, R requires 2 backslashes when using meta characters. Each meta character will match to a single character. Here are some of the most important ones in action: \\s: This meta character represents spaces. This will match to each space, tab, and newline character. You may also specify \\t and \\n for tab and newline characters respectively. Side note: our example string does not have any tabs, but be cautious when looking for them. Many integrated development environments, or IDE’s, have a setting that will replace all tabs with spaces while you are typing. In the example string, \\s returns a list of a vector of 17 spaces, the exact number of spaces in our example string! [[1]] [1] " " " " " " " " " " " " " " " " " " " " " " " " " " " "[15] " " " " " " \\w: This meta character represents alphanumeric characters. This includes all the letters a-z, capital and lowercase, and the numbers 0–9. This would be the equivalent of the bracket group [A-Za-z0-9], just much quicker to write. Take caution in remembering that the \\w meta character on its own only captures a single character, not entire words or numbers. You’ll see that in the example. Don’t worry, we’ll handle that in the next section. [[1]] [1] "D" "r" "e" "w" "h" "a" "s" "3" "w" "a" "t" "e" "r" "m"[15] "e" "l" "o" "n" "s" "A" "l" "e" "x" "h" "a" "s" "4" "h"[29] "a" "m" "b" "u" "r" "g" "e" "r" "s" "K" "a" "r" "i" "n"[43] "a" "h" "a" "s" "1" "2" "t" "a" "m" "a" "l" "e" "s" "a"[57] "n" "d" "A" "n" "n" "a" "h" "a" "s" "6" "s" "o" "f" "t"[71] "p" "r" "e" "t" "z" "e" "l" "s" \\d: This meta character represents numeric digits. Using our picnic example, see how it only finds the digits in the string. You’ll notice that like bracket groups, it picks up 5 numbers instead of the 4 we expect. This is because it is looking for each individual digit, not groups of digits. We’ll see how to fix that with quantifiers next. [[1]][1] "3" "4" "1" "2" "6" As we saw in the previous section, a single meta character can have somewhat limited functionality. When it comes to words or numbers, we usually want to find more than 1 character at a time. This is where quantifiers come in. They allow you to quantify how many of a character you are expecting. They always come after the character they are quantifying and come in a few flavors: + quantifies 1 or more matches. Let’s look at a new example to develop some intuition about what each quantifier will return: quantExample When we use the + quantifier on quantExample, it will return 4 matches. This is a good point to mention that regex looks for non-overlapping matches. In this case, it looks at each B and the character that follows it. Since we used the + quantifier, it continues to match until it reaches the end of a group of B’s. [[1]][1] "B" "BB" "BBB" "BBBB" {} quantifies a specific number or range of matches. When written like {2} it will match exactly 2 of the preceding character. We’ll see some interesting results. It picked up 4 matches. This is because it is looking for each non-overlapping group of 2 B’s. There is a match in the 1st group, only 1 non-overlapping match in the 2nd group, and 2 non-overlapping matches in the 4th. [[1]][1] "BB" "BB" "BB" "BB" When written like {2,4}, it will match any number of B’s from 2 to 4 occurrences. Note that putting a space in your regex will NOT work. It will return an empty list. [[1]][1] "BB" "BBB" "BBBB" We can also write this quantifier and omit the upper bound like {2,}. This will match 2 or more instances. For quantExample, it will return the exact same result as {2,4}. * quantifies zero or more matches. This can be helpful when we are looking for something that may or may not be in our string. The * quantifier returns some strange matches when used by itself, so we can omit an example with quantExample. We will see in a following example how it can be applied when someone at our picnic is bringing a food item with a multiple word name. Without it, we wouldn’t correctly capture that Anna is bringing soft pretzels! Let’s combine what we know so far about character sets, meta characters, and quantifiers to answer some questions about our picnic string. We want to know all of the words that are in the string and also the numbers in the string. For words, we can use a character set with all upper and lower case letters, adding a + quantifier to it. This will find any length of alpha characters grouped together. Said another way, it finds all of the words. Regex is starting to look much more helpful. [[1]] [1] "Drew" "has" "watermelons" "Alex" [5] "has" "hamburgers" "Karina" "has" [9] "tamales" "and" "Anna" "has" [13] "soft" "pretzels" To find the quantity of each food item, we can use the \\d meta character and the quantifier {1,2}. This will find the groups of digits that are 1 or 2 characters long. This is a much more useful output as we have the same number of quantities as we have food items and people! [[1]][1] "3" "4" "12" "6" To find the quantity and name of each food item, we can combine quantifiers with meta characters. We know that each number has a food item directly after it, so we can just add on to the previous example. We know there is a space and a word (\\s\\w+) that could be followed by another word like how “soft pretzel” appears. To specify the second word might not be there, we can use the * quantifier with the second word. Just like that we have a list containing the quantity and name of every good at our picnic. [[1]][1] "3 watermelons" "4 hamburgers" "12 tamales" [4] "6 soft pretzels" Capture groups allow you to look for entire phrases and only return parts of them. With our example, I want each person’s name, what they are bringing, and how much of it they are bringing. Up until this point we have been using str_extract_all. It has a clean output that is easy to read for our examples, but it doesn’t actually work with capture groups. Helpfully, stringr provides str_match_all which does work with capture groups. It does however output the results in a list containing a matrix as opposed to a list containing a vector. [[1]] [,1][1,] "Drew has 3 watermelons"[2,] "Alex has 4 hamburgers"[3,] "Karina has 12 tamales"[4,] "Anna has 6 soft pretzels" The regex we used in captureGroup1 is looking for a name, which starts with a capital letter and has any amount of lowercase letters after it ([A-Z][a-z]+). Then after a space it matches the pattern space, word, space \\s\\w+\\s. Next we are looking for a 1 to 2 digit number followed by a space and a word (\\d{1,2}\\s\\w+). You can see in the output each row of the matrix is a character string with the details for each person. Now this is a big step up from where we started, but we don’t really care about the word “has”, and we want to be able to make a data frame out of the quantities. Let’s add in capture groups. By using capture groups, we can return a matrix where each column contains a specific piece of information. We’ll create capture groups containing each name, quantity, and item. Capture groups are simply sections of the regex that you wrap in parenthesis. [[1]] [,1] [,2] [,3] [,4][1,] "Drew has 3 watermelons" "Drew" "3" "watermelons"[2,] "Alex has 4 hamburgers" "Alex" "4" "hamburgers"[3,] "Karina has 12 tamales" "Karina" "12" "tamales"[4,] "Anna has 6 soft pretzels" "Anna" "6" "soft pretzels" The first column in the matrix has the entire regex, ignoring the capture groups. The remaining columns of the matrix each correspond to the capture groups we defined for name, quantity, and item. When doing data analysis, one of the most useful R data structures is a data frame. No doubt you already knew this if you clicked on this article. Data frames enable things like calculating column statistics and plotting data. Since we have a matrix with all of the information we want, turning it into a data frame isn’t too hard. We will use the data.frame function on everything except for the first column of the matrix. data.frame gives default columns names, so we will change those to match up to what is in each column. A quick note on the notation: the first set of brackets after captureGroup2 ([[1]]) accesses the first element of the list, our matrix. The second set of brackets ( [,-1]) selects all rows and every column except the first one. | | Name | Quantity | Item || - | ------ | -------- | ------------- || 1 | Drew | 3 | watermelons || 2 | Alex | 4 | hamburgers || 3 | Karina | 12 | tamales || 4 | Anna | 6 | soft pretzels | We only covered a small subset of how regex can help handle unstructured text data. This is a good foundation to get started, but before long you will need to know concepts like how to find everything BUT a character (negation) or find something immediately before or after something else (lookarounds). You can learn all about those in my followup post here: medium.com Here are some more resources to help you learn more about these other concepts in regex: The official stringr page on the tidyverse site: The folks over at RStudio have compiled resources to help learn packages like stringr. They even included a stringr cheat sheet that you can print out and reference. R for Data Science: Written by Hadley Wickham, author of the stringr package, this book is a good reference for anything in R. There is even a chapter that covers more advanced regex in R. It is available online for free here, or you can purchase a hardcopy here. Disclaimer: I receive a commission of your purchase through this link. Datacamp Courses: An online learning community dedicated to data science, machine learning, and data visualization. Check out their course “String Manipulation with stringr in R.” The first chapter of every course on the site is free! Disclaimer: You will receive a discount on your subscription and I receive a commission if you sign up for a monthly Datacamp subscription using this link. Support my writing while you learn!
[ { "code": null, "e": 391, "s": 171, "text": "We live in a data-centric age. Data has been described as the new oil. But just like oil, data isn’t always useful in its raw form. One form of data that is particularly hard to use in its raw form is unstructured data." }, { "code": null, "e": 773, "s": 391, "text": "A lot of data is unstructured data. Unstructured data doesn’t fit nicely into a format for analysis, like an Excel spreadsheet or a data frame. Text data is a common type of unstructured data and this makes it difficult to work with. Enter regular expressions, or regex for short. They may look a little intimidating at first, but once you get started, using them will be a picnic!" }, { "code": null, "e": 856, "s": 773, "text": "More comfortable with python? Try my tutorial for using regex with python instead:" }, { "code": null, "e": 879, "s": 856, "text": "towardsdatascience.com" }, { "code": null, "e": 995, "s": 879, "text": "We’ll use the stringr library. The stringr library is built off a C library, so all of its functions are very fast." }, { "code": null, "e": 1069, "s": 995, "text": "To install and load the stringr library in R, use the following commands:" }, { "code": null, "e": 1265, "s": 1069, "text": "See how easy that is? To make things even easier, most function names in the stringr package start with str. Let’s take a look at a couple of the functions we have available to us in this module:" }, { "code": null, "e": 1525, "s": 1265, "text": "str_extract_all(string, pattern): This function returns a list with a vector containing all instances of pattern in stringstr_replace_all(string, pattern, replacement): This function returns string with instances of pattern in string replaced with replacement" }, { "code": null, "e": 1648, "s": 1525, "text": "str_extract_all(string, pattern): This function returns a list with a vector containing all instances of pattern in string" }, { "code": null, "e": 1786, "s": 1648, "text": "str_replace_all(string, pattern, replacement): This function returns string with instances of pattern in string replaced with replacement" }, { "code": null, "e": 2147, "s": 1786, "text": "You may have already used these functions. They have pretty straightforward applications without adding regex. Think back to the times before social distancing and imagine a nice picnic in the park, like the image above. Here’s an example string with what everyone is bringing to the picnic. We can use it to demonstrate the basic usage of the regex functions:" }, { "code": null, "e": 2263, "s": 2147, "text": "basicString <- \"Drew has 3 watermelons, Alex has 4 hamburgers, Karina has 12 tamales, and Anna has 6 soft pretzels\"" }, { "code": null, "e": 2403, "s": 2263, "text": "If I want to pull every instance of one person’s name from this string, I would simply pass the name and basic_string to str_extract_all():" }, { "code": null, "e": 2556, "s": 2403, "text": "The result will be a list with all occurrences of the pattern. Using this example, basicExtractAll will have the following list with 1 vector as output:" }, { "code": null, "e": 2572, "s": 2556, "text": "[[1]][1] \"Drew\"" }, { "code": null, "e": 2740, "s": 2572, "text": "Now let’s imagine that Alex left his 4 hamburgers unattended at the picnic and they were stolen by Shawn. str_replace_all can replace any instances of Alex with Shawn:" }, { "code": null, "e": 2824, "s": 2740, "text": "The resulting string will show that Shawn now has 4 hamburgers. What a lucky guy 🍔." }, { "code": null, "e": 2926, "s": 2824, "text": "\"Drew has 3 watermelons, Shawn has 4 hamburgers, Karina has 12 tamales, and Anna has 6 soft pretzels\"" }, { "code": null, "e": 3237, "s": 2926, "text": "The examples so far are pretty basic. There is a time and place for them, but what if we want to know how many total food items there are at the picnic? Who are all the people with items? What if we need this data in a data frame for further analysis? This is where you will start to see the benefits of regex." }, { "code": null, "e": 3282, "s": 3237, "text": "There are several concepts that drive regex:" }, { "code": null, "e": 3337, "s": 3282, "text": "Character setsMeta charactersQuantifiersCapture Groups" }, { "code": null, "e": 3352, "s": 3337, "text": "Character sets" }, { "code": null, "e": 3368, "s": 3352, "text": "Meta characters" }, { "code": null, "e": 3380, "s": 3368, "text": "Quantifiers" }, { "code": null, "e": 3395, "s": 3380, "text": "Capture Groups" }, { "code": null, "e": 3476, "s": 3395, "text": "This is not an exhaustive list, but is plenty to help us hit the ground running." }, { "code": null, "e": 3631, "s": 3476, "text": "Character sets represent options inside of brackets, with regex matching only one of the options. There are multiple things we can do with character sets:" }, { "code": null, "e": 3760, "s": 3631, "text": "Match a group of characters: We can find all of the vowels in our string by putting every vowel in brackets, for example,[aeiou]" }, { "code": null, "e": 3870, "s": 3760, "text": "[[1]] [1] \"e\" \"a\" \"a\" \"e\" \"e\" \"o\" \"e\" \"a\" \"a\" \"u\" \"e\" \"a\" \"i\" \"a\"[15] \"a\" \"a\" \"a\" \"e\" \"a\" \"a\" \"a\" \"o\" \"e\" \"e\"" }, { "code": null, "e": 4042, "s": 3870, "text": "Match a range of characters: We can find any capital letter from “A” to “F,” by using a hyphen, [A-F]. Character sets are case sensitive, so [A-F] is not the same as [a-f]" }, { "code": null, "e": 4067, "s": 4042, "text": "[[1]][1] \"D\" \"A\" \"K\" \"A\"" }, { "code": null, "e": 4270, "s": 4067, "text": "Match a range of numbers: We can find numbers between a range by adding numbers to our character set, [0-9] to find any number. Notice that the numbers are extracted as strings, not converted to numbers" }, { "code": null, "e": 4299, "s": 4270, "text": "[[1]][1] \"3\" \"4\" \"1\" \"2\" \"6\"" }, { "code": null, "e": 4529, "s": 4299, "text": "Character sets can contain everything from this section simultaneously, so something like [A-Ct-z7-9] is still valid. It will match every character from capital “A” to capital “C,” lowercase “t” to lowercase “z,” and 7 through 9." }, { "code": null, "e": 4663, "s": 4529, "text": "So far we can’t answer any of the questions posed earlier with just bracket groups. Let’s add some more weapons to our regex arsenal." }, { "code": null, "e": 5050, "s": 4663, "text": "Meta characters represent a type of character. They will typically begin with a backslash \\. Since the backslash \\ is a special character in R, it needs to be escaped each time it is used with another backslash. In other words, R requires 2 backslashes when using meta characters. Each meta character will match to a single character. Here are some of the most important ones in action:" }, { "code": null, "e": 5570, "s": 5050, "text": "\\\\s: This meta character represents spaces. This will match to each space, tab, and newline character. You may also specify \\\\t and \\\\n for tab and newline characters respectively. Side note: our example string does not have any tabs, but be cautious when looking for them. Many integrated development environments, or IDE’s, have a setting that will replace all tabs with spaces while you are typing. In the example string, \\\\s returns a list of a vector of 17 spaces, the exact number of spaces in our example string!" }, { "code": null, "e": 5652, "s": 5570, "text": "[[1]] [1] \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \" \"[15] \" \" \" \" \" \"" }, { "code": null, "e": 6097, "s": 5652, "text": "\\\\w: This meta character represents alphanumeric characters. This includes all the letters a-z, capital and lowercase, and the numbers 0–9. This would be the equivalent of the bracket group [A-Za-z0-9], just much quicker to write. Take caution in remembering that the \\\\w meta character on its own only captures a single character, not entire words or numbers. You’ll see that in the example. Don’t worry, we’ll handle that in the next section." }, { "code": null, "e": 6439, "s": 6097, "text": "[[1]] [1] \"D\" \"r\" \"e\" \"w\" \"h\" \"a\" \"s\" \"3\" \"w\" \"a\" \"t\" \"e\" \"r\" \"m\"[15] \"e\" \"l\" \"o\" \"n\" \"s\" \"A\" \"l\" \"e\" \"x\" \"h\" \"a\" \"s\" \"4\" \"h\"[29] \"a\" \"m\" \"b\" \"u\" \"r\" \"g\" \"e\" \"r\" \"s\" \"K\" \"a\" \"r\" \"i\" \"n\"[43] \"a\" \"h\" \"a\" \"s\" \"1\" \"2\" \"t\" \"a\" \"m\" \"a\" \"l\" \"e\" \"s\" \"a\"[57] \"n\" \"d\" \"A\" \"n\" \"n\" \"a\" \"h\" \"a\" \"s\" \"6\" \"s\" \"o\" \"f\" \"t\"[71] \"p\" \"r\" \"e\" \"t\" \"z\" \"e\" \"l\" \"s\"" }, { "code": null, "e": 6783, "s": 6439, "text": "\\\\d: This meta character represents numeric digits. Using our picnic example, see how it only finds the digits in the string. You’ll notice that like bracket groups, it picks up 5 numbers instead of the 4 we expect. This is because it is looking for each individual digit, not groups of digits. We’ll see how to fix that with quantifiers next." }, { "code": null, "e": 6812, "s": 6783, "text": "[[1]][1] \"3\" \"4\" \"1\" \"2\" \"6\"" }, { "code": null, "e": 7194, "s": 6812, "text": "As we saw in the previous section, a single meta character can have somewhat limited functionality. When it comes to words or numbers, we usually want to find more than 1 character at a time. This is where quantifiers come in. They allow you to quantify how many of a character you are expecting. They always come after the character they are quantifying and come in a few flavors:" }, { "code": null, "e": 7333, "s": 7194, "text": "+ quantifies 1 or more matches. Let’s look at a new example to develop some intuition about what each quantifier will return: quantExample" }, { "code": null, "e": 7649, "s": 7333, "text": "When we use the + quantifier on quantExample, it will return 4 matches. This is a good point to mention that regex looks for non-overlapping matches. In this case, it looks at each B and the character that follows it. Since we used the + quantifier, it continues to match until it reaches the end of a group of B’s." }, { "code": null, "e": 7686, "s": 7649, "text": "[[1]][1] \"B\" \"BB\" \"BBB\" \"BBBB\"" }, { "code": null, "e": 8068, "s": 7686, "text": "{} quantifies a specific number or range of matches. When written like {2} it will match exactly 2 of the preceding character. We’ll see some interesting results. It picked up 4 matches. This is because it is looking for each non-overlapping group of 2 B’s. There is a match in the 1st group, only 1 non-overlapping match in the 2nd group, and 2 non-overlapping matches in the 4th." }, { "code": null, "e": 8097, "s": 8068, "text": "[[1]][1] \"BB\" \"BB\" \"BB\" \"BB\"" }, { "code": null, "e": 8264, "s": 8097, "text": "When written like {2,4}, it will match any number of B’s from 2 to 4 occurrences. Note that putting a space in your regex will NOT work. It will return an empty list." }, { "code": null, "e": 8294, "s": 8264, "text": "[[1]][1] \"BB\" \"BBB\" \"BBBB\"" }, { "code": null, "e": 8466, "s": 8294, "text": "We can also write this quantifier and omit the upper bound like {2,}. This will match 2 or more instances. For quantExample, it will return the exact same result as {2,4}." }, { "code": null, "e": 8593, "s": 8466, "text": "* quantifies zero or more matches. This can be helpful when we are looking for something that may or may not be in our string." }, { "code": null, "e": 8919, "s": 8593, "text": "The * quantifier returns some strange matches when used by itself, so we can omit an example with quantExample. We will see in a following example how it can be applied when someone at our picnic is bringing a food item with a multiple word name. Without it, we wouldn’t correctly capture that Anna is bringing soft pretzels!" }, { "code": null, "e": 9150, "s": 8919, "text": "Let’s combine what we know so far about character sets, meta characters, and quantifiers to answer some questions about our picnic string. We want to know all of the words that are in the string and also the numbers in the string." }, { "code": null, "e": 9410, "s": 9150, "text": "For words, we can use a character set with all upper and lower case letters, adding a + quantifier to it. This will find any length of alpha characters grouped together. Said another way, it finds all of the words. Regex is starting to look much more helpful." }, { "code": null, "e": 9625, "s": 9410, "text": "[[1]] [1] \"Drew\" \"has\" \"watermelons\" \"Alex\" [5] \"has\" \"hamburgers\" \"Karina\" \"has\" [9] \"tamales\" \"and\" \"Anna\" \"has\" [13] \"soft\" \"pretzels\"" }, { "code": null, "e": 9903, "s": 9625, "text": "To find the quantity of each food item, we can use the \\\\d meta character and the quantifier {1,2}. This will find the groups of digits that are 1 or 2 characters long. This is a much more useful output as we have the same number of quantities as we have food items and people!" }, { "code": null, "e": 9931, "s": 9903, "text": "[[1]][1] \"3\" \"4\" \"12\" \"6\"" }, { "code": null, "e": 10443, "s": 9931, "text": "To find the quantity and name of each food item, we can combine quantifiers with meta characters. We know that each number has a food item directly after it, so we can just add on to the previous example. We know there is a space and a word (\\\\s\\\\w+) that could be followed by another word like how “soft pretzel” appears. To specify the second word might not be there, we can use the * quantifier with the second word. Just like that we have a list containing the quantity and name of every good at our picnic." }, { "code": null, "e": 10527, "s": 10443, "text": "[[1]][1] \"3 watermelons\" \"4 hamburgers\" \"12 tamales\" [4] \"6 soft pretzels\"" }, { "code": null, "e": 11070, "s": 10527, "text": "Capture groups allow you to look for entire phrases and only return parts of them. With our example, I want each person’s name, what they are bringing, and how much of it they are bringing. Up until this point we have been using str_extract_all. It has a clean output that is easy to read for our examples, but it doesn’t actually work with capture groups. Helpfully, stringr provides str_match_all which does work with capture groups. It does however output the results in a list containing a matrix as opposed to a list containing a vector." }, { "code": null, "e": 11201, "s": 11070, "text": "[[1]] [,1][1,] \"Drew has 3 watermelons\"[2,] \"Alex has 4 hamburgers\"[3,] \"Karina has 12 tamales\"[4,] \"Anna has 6 soft pretzels\"" }, { "code": null, "e": 11632, "s": 11201, "text": "The regex we used in captureGroup1 is looking for a name, which starts with a capital letter and has any amount of lowercase letters after it ([A-Z][a-z]+). Then after a space it matches the pattern space, word, space \\\\s\\\\w+\\\\s. Next we are looking for a 1 to 2 digit number followed by a space and a word (\\\\d{1,2}\\\\s\\\\w+). You can see in the output each row of the matrix is a character string with the details for each person." }, { "code": null, "e": 12080, "s": 11632, "text": "Now this is a big step up from where we started, but we don’t really care about the word “has”, and we want to be able to make a data frame out of the quantities. Let’s add in capture groups. By using capture groups, we can return a matrix where each column contains a specific piece of information. We’ll create capture groups containing each name, quantity, and item. Capture groups are simply sections of the regex that you wrap in parenthesis." }, { "code": null, "e": 12374, "s": 12080, "text": "[[1]] [,1] [,2] [,3] [,4][1,] \"Drew has 3 watermelons\" \"Drew\" \"3\" \"watermelons\"[2,] \"Alex has 4 hamburgers\" \"Alex\" \"4\" \"hamburgers\"[3,] \"Karina has 12 tamales\" \"Karina\" \"12\" \"tamales\"[4,] \"Anna has 6 soft pretzels\" \"Anna\" \"6\" \"soft pretzels\"" }, { "code": null, "e": 12571, "s": 12374, "text": "The first column in the matrix has the entire regex, ignoring the capture groups. The remaining columns of the matrix each correspond to the capture groups we defined for name, quantity, and item." }, { "code": null, "e": 13099, "s": 12571, "text": "When doing data analysis, one of the most useful R data structures is a data frame. No doubt you already knew this if you clicked on this article. Data frames enable things like calculating column statistics and plotting data. Since we have a matrix with all of the information we want, turning it into a data frame isn’t too hard. We will use the data.frame function on everything except for the first column of the matrix. data.frame gives default columns names, so we will change those to match up to what is in each column." }, { "code": null, "e": 13327, "s": 13099, "text": "A quick note on the notation: the first set of brackets after captureGroup2 ([[1]]) accesses the first element of the list, our matrix. The second set of brackets ( [,-1]) selects all rows and every column except the first one." }, { "code": null, "e": 13574, "s": 13327, "text": "| | Name | Quantity | Item || - | ------ | -------- | ------------- || 1 | Drew | 3 | watermelons || 2 | Alex | 4 | hamburgers || 3 | Karina | 12 | tamales || 4 | Anna | 6 | soft pretzels |" }, { "code": null, "e": 13934, "s": 13574, "text": "We only covered a small subset of how regex can help handle unstructured text data. This is a good foundation to get started, but before long you will need to know concepts like how to find everything BUT a character (negation) or find something immediately before or after something else (lookarounds). You can learn all about those in my followup post here:" }, { "code": null, "e": 13945, "s": 13934, "text": "medium.com" }, { "code": null, "e": 14034, "s": 13945, "text": "Here are some more resources to help you learn more about these other concepts in regex:" }, { "code": null, "e": 14249, "s": 14034, "text": "The official stringr page on the tidyverse site: The folks over at RStudio have compiled resources to help learn packages like stringr. They even included a stringr cheat sheet that you can print out and reference." }, { "code": null, "e": 14584, "s": 14249, "text": "R for Data Science: Written by Hadley Wickham, author of the stringr package, this book is a good reference for anything in R. There is even a chapter that covers more advanced regex in R. It is available online for free here, or you can purchase a hardcopy here. Disclaimer: I receive a commission of your purchase through this link." } ]
BigDecimal multiply() Method in Java - GeeksforGeeks
16 Oct, 2019 The java.math.BigDecimal.multiply(BigDecimal multiplicand) is an inbuilt method in java that returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).Syntax:public BigDecimal multiply(BigDecimal multiplicand) Parameters: This method accepts a single parameter multiplicand of BigDecimal type which refers to the Value to be multiplied by this BigDecimal.Return value: This method returns a BigDecimal whose value this * multiplicand.Below program illustrates the working of the above mentioned method:Program 1:// Java program to demonstrate the// multiply() method import java.math.*; public class gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal("54.2"); BigDecimal b2 = new BigDecimal("14.20"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println("Multiplication is " + b3); }}Output:Multiplication is 769.640 Program 2:// Java program to demonstrate the// multiply() method import java.math.*; public class Gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal("-54.2"); BigDecimal b2 = new BigDecimal("14.20"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println("Multiplication is " + b3); }}Output:Multiplication is -769.640 The java.math.BigDecimal.multiply(BigDecimal multiplicand, MathContext mc) is an inbuilt method in Java that returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.Syntax:public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) Parameters: This method accepts two parameters:multiplicand – This is of BigDecimal type and refers to the value to be multiplied by this BigDecimal.mc – This refers to the context of rounding i.e., up to what decimal place the value is to be rounded off.Return value: This method returns a BigDecimal whose value this * multiplicand, rounded as necessary.Program below demonstrates the method:Program 1:// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal("5.99"); BigDecimal b2 = new BigDecimal("4.6"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println("Multiplication is " + b3); }}Output:Multiplication is 27.55 Program 2:// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal("-5.99"); BigDecimal b2 = new BigDecimal("4.6"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println("Multiplication is " + b3); }}Output:Multiplication is -27.55 The java.math.BigDecimal.multiply(BigDecimal multiplicand) is an inbuilt method in java that returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).Syntax:public BigDecimal multiply(BigDecimal multiplicand) Parameters: This method accepts a single parameter multiplicand of BigDecimal type which refers to the Value to be multiplied by this BigDecimal.Return value: This method returns a BigDecimal whose value this * multiplicand.Below program illustrates the working of the above mentioned method:Program 1:// Java program to demonstrate the// multiply() method import java.math.*; public class gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal("54.2"); BigDecimal b2 = new BigDecimal("14.20"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println("Multiplication is " + b3); }}Output:Multiplication is 769.640 Program 2:// Java program to demonstrate the// multiply() method import java.math.*; public class Gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal("-54.2"); BigDecimal b2 = new BigDecimal("14.20"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println("Multiplication is " + b3); }}Output:Multiplication is -769.640 Syntax: public BigDecimal multiply(BigDecimal multiplicand) Parameters: This method accepts a single parameter multiplicand of BigDecimal type which refers to the Value to be multiplied by this BigDecimal. Return value: This method returns a BigDecimal whose value this * multiplicand. Below program illustrates the working of the above mentioned method:Program 1: // Java program to demonstrate the// multiply() method import java.math.*; public class gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal("54.2"); BigDecimal b2 = new BigDecimal("14.20"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println("Multiplication is " + b3); }} Multiplication is 769.640 Program 2: // Java program to demonstrate the// multiply() method import java.math.*; public class Gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal("-54.2"); BigDecimal b2 = new BigDecimal("14.20"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println("Multiplication is " + b3); }} Multiplication is -769.640 The java.math.BigDecimal.multiply(BigDecimal multiplicand, MathContext mc) is an inbuilt method in Java that returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.Syntax:public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) Parameters: This method accepts two parameters:multiplicand – This is of BigDecimal type and refers to the value to be multiplied by this BigDecimal.mc – This refers to the context of rounding i.e., up to what decimal place the value is to be rounded off.Return value: This method returns a BigDecimal whose value this * multiplicand, rounded as necessary.Program below demonstrates the method:Program 1:// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal("5.99"); BigDecimal b2 = new BigDecimal("4.6"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println("Multiplication is " + b3); }}Output:Multiplication is 27.55 Program 2:// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal("-5.99"); BigDecimal b2 = new BigDecimal("4.6"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println("Multiplication is " + b3); }}Output:Multiplication is -27.55 Syntax: public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) Parameters: This method accepts two parameters: multiplicand – This is of BigDecimal type and refers to the value to be multiplied by this BigDecimal. mc – This refers to the context of rounding i.e., up to what decimal place the value is to be rounded off. Return value: This method returns a BigDecimal whose value this * multiplicand, rounded as necessary. Program below demonstrates the method: Program 1: // Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal("5.99"); BigDecimal b2 = new BigDecimal("4.6"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println("Multiplication is " + b3); }} Multiplication is 27.55 Program 2: // Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal("-5.99"); BigDecimal b2 = new BigDecimal("4.6"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println("Multiplication is " + b3); }} Multiplication is -27.55 Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#multiply(java.math.BigDecimal) Akanksha_Rai Java-BigDecimal Java-Functions java-math Java-math-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Overriding in Java LinkedList in Java Collections in Java Queue Interface In Java Multithreading in Java Singleton Class in Java Set in Java Constructors in Java Stream In Java
[ { "code": null, "e": 24027, "s": 23999, "text": "\n16 Oct, 2019" }, { "code": null, "e": 27413, "s": 24027, "text": "The java.math.BigDecimal.multiply(BigDecimal multiplicand) is an inbuilt method in java that returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).Syntax:public BigDecimal multiply(BigDecimal multiplicand)\nParameters: This method accepts a single parameter multiplicand of BigDecimal type which refers to the Value to be multiplied by this BigDecimal.Return value: This method returns a BigDecimal whose value this * multiplicand.Below program illustrates the working of the above mentioned method:Program 1:// Java program to demonstrate the// multiply() method import java.math.*; public class gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal(\"54.2\"); BigDecimal b2 = new BigDecimal(\"14.20\"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}Output:Multiplication is 769.640\nProgram 2:// Java program to demonstrate the// multiply() method import java.math.*; public class Gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal(\"-54.2\"); BigDecimal b2 = new BigDecimal(\"14.20\"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}Output:Multiplication is -769.640\nThe java.math.BigDecimal.multiply(BigDecimal multiplicand, MathContext mc) is an inbuilt method in Java that returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.Syntax:public BigDecimal multiply(BigDecimal multiplicand, MathContext mc)\nParameters: This method accepts two parameters:multiplicand – This is of BigDecimal type and refers to the value to be multiplied by this BigDecimal.mc – This refers to the context of rounding i.e., up to what decimal place the value is to be rounded off.Return value: This method returns a BigDecimal whose value this * multiplicand, rounded as necessary.Program below demonstrates the method:Program 1:// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal(\"5.99\"); BigDecimal b2 = new BigDecimal(\"4.6\"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}Output:Multiplication is 27.55\nProgram 2:// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal(\"-5.99\"); BigDecimal b2 = new BigDecimal(\"4.6\"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}Output:Multiplication is -27.55\n" }, { "code": null, "e": 28990, "s": 27413, "text": "The java.math.BigDecimal.multiply(BigDecimal multiplicand) is an inbuilt method in java that returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).Syntax:public BigDecimal multiply(BigDecimal multiplicand)\nParameters: This method accepts a single parameter multiplicand of BigDecimal type which refers to the Value to be multiplied by this BigDecimal.Return value: This method returns a BigDecimal whose value this * multiplicand.Below program illustrates the working of the above mentioned method:Program 1:// Java program to demonstrate the// multiply() method import java.math.*; public class gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal(\"54.2\"); BigDecimal b2 = new BigDecimal(\"14.20\"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}Output:Multiplication is 769.640\nProgram 2:// Java program to demonstrate the// multiply() method import java.math.*; public class Gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal(\"-54.2\"); BigDecimal b2 = new BigDecimal(\"14.20\"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}Output:Multiplication is -769.640\n" }, { "code": null, "e": 28998, "s": 28990, "text": "Syntax:" }, { "code": null, "e": 29051, "s": 28998, "text": "public BigDecimal multiply(BigDecimal multiplicand)\n" }, { "code": null, "e": 29197, "s": 29051, "text": "Parameters: This method accepts a single parameter multiplicand of BigDecimal type which refers to the Value to be multiplied by this BigDecimal." }, { "code": null, "e": 29277, "s": 29197, "text": "Return value: This method returns a BigDecimal whose value this * multiplicand." }, { "code": null, "e": 29356, "s": 29277, "text": "Below program illustrates the working of the above mentioned method:Program 1:" }, { "code": "// Java program to demonstrate the// multiply() method import java.math.*; public class gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal(\"54.2\"); BigDecimal b2 = new BigDecimal(\"14.20\"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}", "e": 29821, "s": 29356, "text": null }, { "code": null, "e": 29848, "s": 29821, "text": "Multiplication is 769.640\n" }, { "code": null, "e": 29859, "s": 29848, "text": "Program 2:" }, { "code": "// Java program to demonstrate the// multiply() method import java.math.*; public class Gfg { public static void main(String[] args) { // Assign two BigDecimal objects BigDecimal b1 = new BigDecimal(\"-54.2\"); BigDecimal b2 = new BigDecimal(\"14.20\"); // Multiply b1 with b2 and assign result to b3 BigDecimal b3 = b1.multiply(b2); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}", "e": 30325, "s": 29859, "text": null }, { "code": null, "e": 30353, "s": 30325, "text": "Multiplication is -769.640\n" }, { "code": null, "e": 32163, "s": 30353, "text": "The java.math.BigDecimal.multiply(BigDecimal multiplicand, MathContext mc) is an inbuilt method in Java that returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.Syntax:public BigDecimal multiply(BigDecimal multiplicand, MathContext mc)\nParameters: This method accepts two parameters:multiplicand – This is of BigDecimal type and refers to the value to be multiplied by this BigDecimal.mc – This refers to the context of rounding i.e., up to what decimal place the value is to be rounded off.Return value: This method returns a BigDecimal whose value this * multiplicand, rounded as necessary.Program below demonstrates the method:Program 1:// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal(\"5.99\"); BigDecimal b2 = new BigDecimal(\"4.6\"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}Output:Multiplication is 27.55\nProgram 2:// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal(\"-5.99\"); BigDecimal b2 = new BigDecimal(\"4.6\"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}Output:Multiplication is -27.55\n" }, { "code": null, "e": 32171, "s": 32163, "text": "Syntax:" }, { "code": null, "e": 32240, "s": 32171, "text": "public BigDecimal multiply(BigDecimal multiplicand, MathContext mc)\n" }, { "code": null, "e": 32288, "s": 32240, "text": "Parameters: This method accepts two parameters:" }, { "code": null, "e": 32391, "s": 32288, "text": "multiplicand – This is of BigDecimal type and refers to the value to be multiplied by this BigDecimal." }, { "code": null, "e": 32498, "s": 32391, "text": "mc – This refers to the context of rounding i.e., up to what decimal place the value is to be rounded off." }, { "code": null, "e": 32600, "s": 32498, "text": "Return value: This method returns a BigDecimal whose value this * multiplicand, rounded as necessary." }, { "code": null, "e": 32639, "s": 32600, "text": "Program below demonstrates the method:" }, { "code": null, "e": 32650, "s": 32639, "text": "Program 1:" }, { "code": "// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal(\"5.99\"); BigDecimal b2 = new BigDecimal(\"4.6\"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}", "e": 33171, "s": 32650, "text": null }, { "code": null, "e": 33196, "s": 33171, "text": "Multiplication is 27.55\n" }, { "code": null, "e": 33207, "s": 33196, "text": "Program 2:" }, { "code": "// Java program to demonstrate the// multiply() methodimport java.math.*; public class Gfg { public static void main(String[] args) { // 4 precision MathContext m = new MathContext(4); // Assign value to BigDecimal objects BigDecimal b1 = new BigDecimal(\"-5.99\"); BigDecimal b2 = new BigDecimal(\"4.6\"); // Multiply b1 with b2 using m BigDecimal b3 = b1.multiply(b2, m); // Print b3 value System.out.println(\"Multiplication is \" + b3); }}", "e": 33729, "s": 33207, "text": null }, { "code": null, "e": 33755, "s": 33729, "text": "Multiplication is -27.55\n" }, { "code": null, "e": 33864, "s": 33755, "text": "Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#multiply(java.math.BigDecimal)" }, { "code": null, "e": 33877, "s": 33864, "text": "Akanksha_Rai" }, { "code": null, "e": 33893, "s": 33877, "text": "Java-BigDecimal" }, { "code": null, "e": 33908, "s": 33893, "text": "Java-Functions" }, { "code": null, "e": 33918, "s": 33908, "text": "java-math" }, { "code": null, "e": 33936, "s": 33918, "text": "Java-math-package" }, { "code": null, "e": 33941, "s": 33936, "text": "Java" }, { "code": null, "e": 33946, "s": 33941, "text": "Java" }, { "code": null, "e": 34044, "s": 33946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34053, "s": 34044, "text": "Comments" }, { "code": null, "e": 34066, "s": 34053, "text": "Old Comments" }, { "code": null, "e": 34085, "s": 34066, "text": "Interfaces in Java" }, { "code": null, "e": 34104, "s": 34085, "text": "Overriding in Java" }, { "code": null, "e": 34123, "s": 34104, "text": "LinkedList in Java" }, { "code": null, "e": 34143, "s": 34123, "text": "Collections in Java" }, { "code": null, "e": 34167, "s": 34143, "text": "Queue Interface In Java" }, { "code": null, "e": 34190, "s": 34167, "text": "Multithreading in Java" }, { "code": null, "e": 34214, "s": 34190, "text": "Singleton Class in Java" }, { "code": null, "e": 34226, "s": 34214, "text": "Set in Java" }, { "code": null, "e": 34247, "s": 34226, "text": "Constructors in Java" } ]
How to convert a String containing Scientific Notation to correct JavaScript number format?
To convert a string with Scientific Notation, use the Number function. Pass the value to this function. You can try to run the following code to convert a string to correct number format − Live Demo <!DOCTYPE html> <html> <body> <script> document.write("String with Scientific Notation converted below:<br>"); document.write(Number("7.53245683E7")); </script> </body> </html> String with Scientific Notation converted below: 75324568.3
[ { "code": null, "e": 1166, "s": 1062, "text": "To convert a string with Scientific Notation, use the Number function. Pass the value to this function." }, { "code": null, "e": 1251, "s": 1166, "text": "You can try to run the following code to convert a string to correct number format −" }, { "code": null, "e": 1261, "s": 1251, "text": "Live Demo" }, { "code": null, "e": 1474, "s": 1261, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n document.write(\"String with Scientific Notation converted below:<br>\");\n document.write(Number(\"7.53245683E7\"));\n </script>\n </body>\n</html>" }, { "code": null, "e": 1534, "s": 1474, "text": "String with Scientific Notation converted below:\n75324568.3" } ]
5 Tools for Reproducible Data Science | by Rebecca Vickery | Towards Data Science
The definition of reproducibility in science is the “extent to which consistent results are obtained when an experiment is repeated”. Data, in particular where the data is held in a database, can change. Additionally, data science is largely based on random-sampling, probability and experimentation. In this field, it can, therefore, be quite challenging to produce analysis and build models where the results and outcomes can be reproduced either by a colleague or by you at some future point in time. Although it can be challenging to obtain, there are a number of reasons why reproducibility is essential for good data science. Reproducibility supports collaboration. Rarely does a data science project take place in isolation. In most situations, data scientists work together with other data scientists and with other teams to see a project through to integration into a business process. In order to collaborate effectively, it is important that other people can repeat, build on and maintain your work.Reproducibility also supports efficiency. To be able to work most efficiently it is essential that you and your colleagues can build on the work that you produce. If results or processes cannot be accurately repeated then it is very difficult to develop on top of existing work and instead, you will find that you have to start a project all over again.Reproducibility builds trust. As previously stated, data science is a discipline built on probability and experimentation. In this field trust in results is extremely important in order to develop buy-in for projects and to work effectively with other teams. Reproducibility supports collaboration. Rarely does a data science project take place in isolation. In most situations, data scientists work together with other data scientists and with other teams to see a project through to integration into a business process. In order to collaborate effectively, it is important that other people can repeat, build on and maintain your work. Reproducibility also supports efficiency. To be able to work most efficiently it is essential that you and your colleagues can build on the work that you produce. If results or processes cannot be accurately repeated then it is very difficult to develop on top of existing work and instead, you will find that you have to start a project all over again. Reproducibility builds trust. As previously stated, data science is a discipline built on probability and experimentation. In this field trust in results is extremely important in order to develop buy-in for projects and to work effectively with other teams. In the following article, I will share 5 tools that facilitate reproducibility in data science. Each of these tools provides the functionality to solve specific challenges around creating reproducible data science projects, these include: Recording the tools, libraries and versions used in a project. Creating self-contained, consistent environments for data science projects. Developing a consistent, easy to read file structure. Writing tests for your code. Using version control. Watermark is an IPython magic extension that prints information about software versions, hardware and dates and times in any IPython shell or Jupyter Notebook session. Watermark provides a very quick and simple way to keep track of tools, libraries, versions, authors and dates involved in a project. It is particularly useful for ad hoc or one-off pieces of work, rather than larger projects, that take place in notebooks only. It means that if a colleague wants to repeat a piece of work they have a good idea of the tools and libraries they need to install, who created the work and when it was put together. To install watermark run the following in your terminal. pip install watermark To use the extension in a Jupyter notebook or an IPython shell run the following command. %load_ext watermark You can select the information that is printed by specifying a number of flags. The full list of available flags is listed in the documentation. But as an illustration the code below prints the current date, the version of python and IPython I am using, the versions for libraries I have installed and imported, and information about the hardware I am using. The output is shown below the code. %watermark -d -m -v -p numpy,matplotlib,sklearn,seaborn,pandas In data science the environment that a project is created in, that is the tools, libraries and versions installed, has a large impact on reproducing the same results and in many cases being able to run the code at all on another computer. Virtual environments are tools that provide contained environments for individual projects. These environments contain a file often called a requirements file that lists the dependencies (tools, libraries and versions) for a project. When you create a virtual environment you can choose to install all the dependencies from this file and thus reproduce the same environment that the project was originally created in. There are a number of tools for creating virtual environments but if you are using python then pipenv is one of the best. To install pipenv run the following. $ brew install pipenv To create a new environment using a specific version of python. Make a new directory and then run the following command from your new directory. mkdir pip-testcd pip-testpipenv --python 3.7 To activate the environment run pipenv-shell you will now be in a new environment called ‘pip-test’. If we inspect the contents of the directory we will see that pipenv has created a new file called Pipfile. This is the pipenv equivalent of a requirements file. ls Let's inspect the contents of this file. Replace “Sublime Text” with the name of your preferred text editor if necessary. open -a "Sublime Text" Pipfile The new file contains the following. We don’t currently have any packages installed in the environment but if we did we would see them in this file. Let’s install pandas to test this. pipenv install pandas If we open the file again we can see that pandas has now been added to the Pipfile. Now let's suppose a colleague wants to work on your project on a different computer. If they were to clone your repo from Github the Pipfile would be contained within this. They can then simply recreate the exact environment that you have been using simply by running the following. pipenv install --devpipenv shell This will create a pipenv environment in the directory you are working in and install all dependencies from the pip file. If you want to use this environment within a Jupyter notebook session then you need to run this code. You can change the name and display name to something that makes sense for your environment. When you start a Jupyter notebook session this will now appear as an icon to select from the launcher screen (shown below the code). Any new notebooks you create with this kernel will contain all dependencies in your pipenv environment. python -m ipykernel install --user --name myenv --display-name "Python (pipenv test)" Having a defined, consistent project structure for data science can make it much easier to collaborate, share and build on a project. Cookie-cutter-data-science is a tool that, in one line of code, creates a standard skeleton project structure. To install run the following. pip install cookiecutter To create a new project you simply run. cookiecutter https://github.com/drivendata/cookiecutter-data-science The tool will prompt you for a number of details, many of which are optional. This has now created the following project structure which will be sufficient for most data science projects. Pytest is a tool for unit testing your python code. Unit testing is a repeatable action that you can add to your code that checks that the individual units of code work as expected. Unit testing is good practice for adding trust to the code that you write. Pytest can be installed and imported for use as shown below. pipenv install pytestimport pytest A simple test might be to check that the data you are importing has not changed. import pandas as pdfrom sklearn.datasets import load_bostonboston = load_boston()boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)len(boston_df)assert len(boston_df) == 506 You can add a helpful error message to the statement to make it easier to debug the code. assert len(boston_df) == 506, "Len(df) should be 506" If we then change the data the error message will be displayed. import pandas as pdfrom sklearn.datasets import load_wineboston = load_wine()boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)len(boston_df)assert len(boston_df) == 506, "len(df) should be 506" Version control is an important tool for developing repeatable projects, sharing work and to facilitate collaboration. Maintaining both a remote and local version of your project allows others to access and develop on their own local version, rollback and monitor changes to code and to safely merge changes and new features. Github is one of the most well known and widely used platforms for version control. Github uses an application known as Git to apply version control to your code. Files for a project are stored in a central remote location known as a repository. Every time you make a change locally on your machine and push to Github your remote version is updated and a store of that commit is recorded. If you want to rollback to a previous version of your project before you made a commit this record allows you to do this. Additionally, because the project files are stored remotely anyone else with access can download the repo and make changes to the project. The concept of branching, which in essence means you make a temporary copy of the project which is completely separate, means you can make changes there first without fear of breaking anything. For usage guidelines, I have written a guide to Github for data scientists here. Unlike traditional software developments, there are currently minimal standard practices in data science projects. However, the tools described above go a long way towards creating standard practices that in turn will lead to more reproducible data science projects. Thanks for reading!
[ { "code": null, "e": 676, "s": 172, "text": "The definition of reproducibility in science is the “extent to which consistent results are obtained when an experiment is repeated”. Data, in particular where the data is held in a database, can change. Additionally, data science is largely based on random-sampling, probability and experimentation. In this field, it can, therefore, be quite challenging to produce analysis and build models where the results and outcomes can be reproduced either by a colleague or by you at some future point in time." }, { "code": null, "e": 804, "s": 676, "text": "Although it can be challenging to obtain, there are a number of reasons why reproducibility is essential for good data science." }, { "code": null, "e": 1794, "s": 804, "text": "Reproducibility supports collaboration. Rarely does a data science project take place in isolation. In most situations, data scientists work together with other data scientists and with other teams to see a project through to integration into a business process. In order to collaborate effectively, it is important that other people can repeat, build on and maintain your work.Reproducibility also supports efficiency. To be able to work most efficiently it is essential that you and your colleagues can build on the work that you produce. If results or processes cannot be accurately repeated then it is very difficult to develop on top of existing work and instead, you will find that you have to start a project all over again.Reproducibility builds trust. As previously stated, data science is a discipline built on probability and experimentation. In this field trust in results is extremely important in order to develop buy-in for projects and to work effectively with other teams." }, { "code": null, "e": 2173, "s": 1794, "text": "Reproducibility supports collaboration. Rarely does a data science project take place in isolation. In most situations, data scientists work together with other data scientists and with other teams to see a project through to integration into a business process. In order to collaborate effectively, it is important that other people can repeat, build on and maintain your work." }, { "code": null, "e": 2527, "s": 2173, "text": "Reproducibility also supports efficiency. To be able to work most efficiently it is essential that you and your colleagues can build on the work that you produce. If results or processes cannot be accurately repeated then it is very difficult to develop on top of existing work and instead, you will find that you have to start a project all over again." }, { "code": null, "e": 2786, "s": 2527, "text": "Reproducibility builds trust. As previously stated, data science is a discipline built on probability and experimentation. In this field trust in results is extremely important in order to develop buy-in for projects and to work effectively with other teams." }, { "code": null, "e": 3025, "s": 2786, "text": "In the following article, I will share 5 tools that facilitate reproducibility in data science. Each of these tools provides the functionality to solve specific challenges around creating reproducible data science projects, these include:" }, { "code": null, "e": 3088, "s": 3025, "text": "Recording the tools, libraries and versions used in a project." }, { "code": null, "e": 3164, "s": 3088, "text": "Creating self-contained, consistent environments for data science projects." }, { "code": null, "e": 3218, "s": 3164, "text": "Developing a consistent, easy to read file structure." }, { "code": null, "e": 3247, "s": 3218, "text": "Writing tests for your code." }, { "code": null, "e": 3270, "s": 3247, "text": "Using version control." }, { "code": null, "e": 3438, "s": 3270, "text": "Watermark is an IPython magic extension that prints information about software versions, hardware and dates and times in any IPython shell or Jupyter Notebook session." }, { "code": null, "e": 3882, "s": 3438, "text": "Watermark provides a very quick and simple way to keep track of tools, libraries, versions, authors and dates involved in a project. It is particularly useful for ad hoc or one-off pieces of work, rather than larger projects, that take place in notebooks only. It means that if a colleague wants to repeat a piece of work they have a good idea of the tools and libraries they need to install, who created the work and when it was put together." }, { "code": null, "e": 3939, "s": 3882, "text": "To install watermark run the following in your terminal." }, { "code": null, "e": 3961, "s": 3939, "text": "pip install watermark" }, { "code": null, "e": 4051, "s": 3961, "text": "To use the extension in a Jupyter notebook or an IPython shell run the following command." }, { "code": null, "e": 4071, "s": 4051, "text": "%load_ext watermark" }, { "code": null, "e": 4466, "s": 4071, "text": "You can select the information that is printed by specifying a number of flags. The full list of available flags is listed in the documentation. But as an illustration the code below prints the current date, the version of python and IPython I am using, the versions for libraries I have installed and imported, and information about the hardware I am using. The output is shown below the code." }, { "code": null, "e": 4530, "s": 4466, "text": "%watermark -d -m -v -p numpy,matplotlib,sklearn,seaborn,pandas " }, { "code": null, "e": 4769, "s": 4530, "text": "In data science the environment that a project is created in, that is the tools, libraries and versions installed, has a large impact on reproducing the same results and in many cases being able to run the code at all on another computer." }, { "code": null, "e": 5187, "s": 4769, "text": "Virtual environments are tools that provide contained environments for individual projects. These environments contain a file often called a requirements file that lists the dependencies (tools, libraries and versions) for a project. When you create a virtual environment you can choose to install all the dependencies from this file and thus reproduce the same environment that the project was originally created in." }, { "code": null, "e": 5309, "s": 5187, "text": "There are a number of tools for creating virtual environments but if you are using python then pipenv is one of the best." }, { "code": null, "e": 5346, "s": 5309, "text": "To install pipenv run the following." }, { "code": null, "e": 5368, "s": 5346, "text": "$ brew install pipenv" }, { "code": null, "e": 5513, "s": 5368, "text": "To create a new environment using a specific version of python. Make a new directory and then run the following command from your new directory." }, { "code": null, "e": 5558, "s": 5513, "text": "mkdir pip-testcd pip-testpipenv --python 3.7" }, { "code": null, "e": 5659, "s": 5558, "text": "To activate the environment run pipenv-shell you will now be in a new environment called ‘pip-test’." }, { "code": null, "e": 5820, "s": 5659, "text": "If we inspect the contents of the directory we will see that pipenv has created a new file called Pipfile. This is the pipenv equivalent of a requirements file." }, { "code": null, "e": 5823, "s": 5820, "text": "ls" }, { "code": null, "e": 5945, "s": 5823, "text": "Let's inspect the contents of this file. Replace “Sublime Text” with the name of your preferred text editor if necessary." }, { "code": null, "e": 5976, "s": 5945, "text": "open -a \"Sublime Text\" Pipfile" }, { "code": null, "e": 6013, "s": 5976, "text": "The new file contains the following." }, { "code": null, "e": 6160, "s": 6013, "text": "We don’t currently have any packages installed in the environment but if we did we would see them in this file. Let’s install pandas to test this." }, { "code": null, "e": 6182, "s": 6160, "text": "pipenv install pandas" }, { "code": null, "e": 6266, "s": 6182, "text": "If we open the file again we can see that pandas has now been added to the Pipfile." }, { "code": null, "e": 6549, "s": 6266, "text": "Now let's suppose a colleague wants to work on your project on a different computer. If they were to clone your repo from Github the Pipfile would be contained within this. They can then simply recreate the exact environment that you have been using simply by running the following." }, { "code": null, "e": 6582, "s": 6549, "text": "pipenv install --devpipenv shell" }, { "code": null, "e": 6704, "s": 6582, "text": "This will create a pipenv environment in the directory you are working in and install all dependencies from the pip file." }, { "code": null, "e": 7136, "s": 6704, "text": "If you want to use this environment within a Jupyter notebook session then you need to run this code. You can change the name and display name to something that makes sense for your environment. When you start a Jupyter notebook session this will now appear as an icon to select from the launcher screen (shown below the code). Any new notebooks you create with this kernel will contain all dependencies in your pipenv environment." }, { "code": null, "e": 7222, "s": 7136, "text": "python -m ipykernel install --user --name myenv --display-name \"Python (pipenv test)\"" }, { "code": null, "e": 7467, "s": 7222, "text": "Having a defined, consistent project structure for data science can make it much easier to collaborate, share and build on a project. Cookie-cutter-data-science is a tool that, in one line of code, creates a standard skeleton project structure." }, { "code": null, "e": 7497, "s": 7467, "text": "To install run the following." }, { "code": null, "e": 7522, "s": 7497, "text": "pip install cookiecutter" }, { "code": null, "e": 7562, "s": 7522, "text": "To create a new project you simply run." }, { "code": null, "e": 7631, "s": 7562, "text": "cookiecutter https://github.com/drivendata/cookiecutter-data-science" }, { "code": null, "e": 7709, "s": 7631, "text": "The tool will prompt you for a number of details, many of which are optional." }, { "code": null, "e": 7819, "s": 7709, "text": "This has now created the following project structure which will be sufficient for most data science projects." }, { "code": null, "e": 8076, "s": 7819, "text": "Pytest is a tool for unit testing your python code. Unit testing is a repeatable action that you can add to your code that checks that the individual units of code work as expected. Unit testing is good practice for adding trust to the code that you write." }, { "code": null, "e": 8137, "s": 8076, "text": "Pytest can be installed and imported for use as shown below." }, { "code": null, "e": 8172, "s": 8137, "text": "pipenv install pytestimport pytest" }, { "code": null, "e": 8253, "s": 8172, "text": "A simple test might be to check that the data you are importing has not changed." }, { "code": null, "e": 8444, "s": 8253, "text": "import pandas as pdfrom sklearn.datasets import load_bostonboston = load_boston()boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)len(boston_df)assert len(boston_df) == 506" }, { "code": null, "e": 8534, "s": 8444, "text": "You can add a helpful error message to the statement to make it easier to debug the code." }, { "code": null, "e": 8588, "s": 8534, "text": "assert len(boston_df) == 506, \"Len(df) should be 506\"" }, { "code": null, "e": 8652, "s": 8588, "text": "If we then change the data the error message will be displayed." }, { "code": null, "e": 8864, "s": 8652, "text": "import pandas as pdfrom sklearn.datasets import load_wineboston = load_wine()boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)len(boston_df)assert len(boston_df) == 506, \"len(df) should be 506\"" }, { "code": null, "e": 9190, "s": 8864, "text": "Version control is an important tool for developing repeatable projects, sharing work and to facilitate collaboration. Maintaining both a remote and local version of your project allows others to access and develop on their own local version, rollback and monitor changes to code and to safely merge changes and new features." }, { "code": null, "e": 9701, "s": 9190, "text": "Github is one of the most well known and widely used platforms for version control. Github uses an application known as Git to apply version control to your code. Files for a project are stored in a central remote location known as a repository. Every time you make a change locally on your machine and push to Github your remote version is updated and a store of that commit is recorded. If you want to rollback to a previous version of your project before you made a commit this record allows you to do this." }, { "code": null, "e": 10034, "s": 9701, "text": "Additionally, because the project files are stored remotely anyone else with access can download the repo and make changes to the project. The concept of branching, which in essence means you make a temporary copy of the project which is completely separate, means you can make changes there first without fear of breaking anything." }, { "code": null, "e": 10115, "s": 10034, "text": "For usage guidelines, I have written a guide to Github for data scientists here." }, { "code": null, "e": 10382, "s": 10115, "text": "Unlike traditional software developments, there are currently minimal standard practices in data science projects. However, the tools described above go a long way towards creating standard practices that in turn will lead to more reproducible data science projects." } ]
Sum of bitwise OR of all subarrays
22 Jun, 2021 Give an array of positive integers, find the total sum after performing the bit wise OR operation on all the sub arrays of a given array.Examples: Input : 1 2 3 4 5 Output : 71 Input : 6 5 4 3 2 Output : 84 First initialize the two variable sum=0, sum1=0, variable sum will store the total sum and, with sum1 we will perform bitwise OR operation for each jth element, and add sum1 with sum. 1:- Traverse the from 0th position to n-1. 2:- For each ith variable we will perform bit wise OR operation on all the sub arrays to find the total sum. Repeat step until the whole array is traverse. C++ C Java Python3 C# PHP Javascript // C++ program to find sum of// bitwise ors of all subarrays.#include <iostream>using namespace std; int totalSum(int a[], int n){ int i, sum = 0, sum1 = 0, j; for (i = 0; i < n; i++) { sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for (j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after performing // the Bitwise OR operation sum = sum + sum1; } } return sum;} // Driver codeint main(){ int a[] = { 1, 2, 3, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); cout << totalSum(a, n) << endl; return 0;} // This code is contributed// by Shivi_Aggarwal // C program to find sum of bitwise ors// of all subarrays.#include <stdio.h> int totalSum(int a[], int n){ int i, sum = 0, sum1 = 0, j; for (i = 0; i < n; i++) { sum1 = 0; // perform Bitwise OR operation // on all the subarray present in array for (j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after performing the // Bitwise OR operation sum = sum + sum1; } } return sum;} // Driver codeint main(){ int a[] = { 1, 2, 3, 4, 5 }; int n = sizeof(a)/sizeof(a[0]); printf("%d ", totalSum(a, n)); return 0;} // Java program to find sum// of bitwise ors of all subarrays.import java.util.*;import java.lang.*;import java.io.*; class GFG{static int totalSum(int a[], int n){ int i, sum = 0, sum1 = 0, j; for (i = 0; i < n; i++) { sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for (j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after // performing the Bitwise // OR operation sum = sum + sum1; } } return sum;} // Driver codepublic static void main(String args[]){ int a[] = { 1, 2, 3, 4, 5 }; int n = a.length; System.out.println(totalSum(a,n));}} // This code is contributed// by Subhadeep # Python3 program to find sum of# bitwise ors of all subarrays.def totalSum(a, n): sum = 0; for i in range(n): sum1 = 0; # perform Bitwise OR operation # on all the subarray present # in array for j in range(i, n): # OR operation sum1 = (sum1 | a[j]); # now add the sum after # performing the # Bitwise OR operation sum = sum + sum1; return sum; # Driver codea = [1, 2, 3, 4, 5];n = len(a);print(totalSum(a, n)); # This code is contributed by mits // C# program to find sum// of bitwise ors of all// subarrays.using System; class GFG{static int totalSum(int[] a, int n){ int sum = 0; for(int i = 0; i < n; i++) { int sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for (int j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after // performing the Bitwise // OR operation sum = sum + sum1; } } return sum;} // Driver codestatic void Main(){ int[] a = { 1, 2, 3, 4, 5 }; int n = a.Length; Console.WriteLine(totalSum(a,n));}} // This code is contributed// by mits <?php// PHP program to find// sum of bitwise ors// of all subarrays.function totalSum($a,$n){$sum = 0;for ($i = 0; $i < $n; $i++){ $sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for ($j = $i; $j < $n; $j++) { // OR operation $sum1 = ($sum1 | $a[$j]); // now add the sum after // performing the // Bitwise OR operation $sum = $sum + $sum1; }}return $sum;} // Driver code$a = array(1, 2, 3, 4, 5);$n = sizeof($a);echo totalSum($a, $n); // This code is contributed by mits?> <script> // Java program to find sum// of bitwise ors of all subarrays.function totalSum(a, n){ let i, sum = 0, sum1 = 0, j; for (i = 0; i < n; i++) { sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for (j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after // performing the Bitwise // OR operation sum = sum + sum1; } } return sum;} // Driver code let a = [ 1, 2, 3, 4, 5 ]; let n = a.length; document.write(totalSum(a,n)); // This code is contributed shivanisinghss2110</script> 71 tufan_gupta2000 Mithun Kumar Shivi_Aggarwal shivanisinghss2110 Bitwise-OR Arrays Bit Magic Arrays Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) How to swap two numbers without using a temporary variable? Program to find whether a given number is power of 2
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2021" }, { "code": null, "e": 201, "s": 52, "text": "Give an array of positive integers, find the total sum after performing the bit wise OR operation on all the sub arrays of a given array.Examples: " }, { "code": null, "e": 262, "s": 201, "text": "Input : 1 2 3 4 5\nOutput : 71\n\nInput : 6 5 4 3 2\nOutput : 84" }, { "code": null, "e": 651, "s": 266, "text": "First initialize the two variable sum=0, sum1=0, variable sum will store the total sum and, with sum1 we will perform bitwise OR operation for each jth element, and add sum1 with sum. 1:- Traverse the from 0th position to n-1. 2:- For each ith variable we will perform bit wise OR operation on all the sub arrays to find the total sum. Repeat step until the whole array is traverse. " }, { "code": null, "e": 655, "s": 651, "text": "C++" }, { "code": null, "e": 657, "s": 655, "text": "C" }, { "code": null, "e": 662, "s": 657, "text": "Java" }, { "code": null, "e": 670, "s": 662, "text": "Python3" }, { "code": null, "e": 673, "s": 670, "text": "C#" }, { "code": null, "e": 677, "s": 673, "text": "PHP" }, { "code": null, "e": 688, "s": 677, "text": "Javascript" }, { "code": "// C++ program to find sum of// bitwise ors of all subarrays.#include <iostream>using namespace std; int totalSum(int a[], int n){ int i, sum = 0, sum1 = 0, j; for (i = 0; i < n; i++) { sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for (j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after performing // the Bitwise OR operation sum = sum + sum1; } } return sum;} // Driver codeint main(){ int a[] = { 1, 2, 3, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); cout << totalSum(a, n) << endl; return 0;} // This code is contributed// by Shivi_Aggarwal", "e": 1439, "s": 688, "text": null }, { "code": "// C program to find sum of bitwise ors// of all subarrays.#include <stdio.h> int totalSum(int a[], int n){ int i, sum = 0, sum1 = 0, j; for (i = 0; i < n; i++) { sum1 = 0; // perform Bitwise OR operation // on all the subarray present in array for (j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after performing the // Bitwise OR operation sum = sum + sum1; } } return sum;} // Driver codeint main(){ int a[] = { 1, 2, 3, 4, 5 }; int n = sizeof(a)/sizeof(a[0]); printf(\"%d \", totalSum(a, n)); return 0;}", "e": 2096, "s": 1439, "text": null }, { "code": "// Java program to find sum// of bitwise ors of all subarrays.import java.util.*;import java.lang.*;import java.io.*; class GFG{static int totalSum(int a[], int n){ int i, sum = 0, sum1 = 0, j; for (i = 0; i < n; i++) { sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for (j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after // performing the Bitwise // OR operation sum = sum + sum1; } } return sum;} // Driver codepublic static void main(String args[]){ int a[] = { 1, 2, 3, 4, 5 }; int n = a.length; System.out.println(totalSum(a,n));}} // This code is contributed// by Subhadeep", "e": 2892, "s": 2096, "text": null }, { "code": "# Python3 program to find sum of# bitwise ors of all subarrays.def totalSum(a, n): sum = 0; for i in range(n): sum1 = 0; # perform Bitwise OR operation # on all the subarray present # in array for j in range(i, n): # OR operation sum1 = (sum1 | a[j]); # now add the sum after # performing the # Bitwise OR operation sum = sum + sum1; return sum; # Driver codea = [1, 2, 3, 4, 5];n = len(a);print(totalSum(a, n)); # This code is contributed by mits", "e": 3485, "s": 2892, "text": null }, { "code": "// C# program to find sum// of bitwise ors of all// subarrays.using System; class GFG{static int totalSum(int[] a, int n){ int sum = 0; for(int i = 0; i < n; i++) { int sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for (int j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after // performing the Bitwise // OR operation sum = sum + sum1; } } return sum;} // Driver codestatic void Main(){ int[] a = { 1, 2, 3, 4, 5 }; int n = a.Length; Console.WriteLine(totalSum(a,n));}} // This code is contributed// by mits", "e": 4207, "s": 3485, "text": null }, { "code": "<?php// PHP program to find// sum of bitwise ors// of all subarrays.function totalSum($a,$n){$sum = 0;for ($i = 0; $i < $n; $i++){ $sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for ($j = $i; $j < $n; $j++) { // OR operation $sum1 = ($sum1 | $a[$j]); // now add the sum after // performing the // Bitwise OR operation $sum = $sum + $sum1; }}return $sum;} // Driver code$a = array(1, 2, 3, 4, 5);$n = sizeof($a);echo totalSum($a, $n); // This code is contributed by mits?>", "e": 4784, "s": 4207, "text": null }, { "code": "<script> // Java program to find sum// of bitwise ors of all subarrays.function totalSum(a, n){ let i, sum = 0, sum1 = 0, j; for (i = 0; i < n; i++) { sum1 = 0; // perform Bitwise OR operation // on all the subarray present // in array for (j = i; j < n; j++) { // OR operation sum1 = (sum1 | a[j]); // now add the sum after // performing the Bitwise // OR operation sum = sum + sum1; } } return sum;} // Driver code let a = [ 1, 2, 3, 4, 5 ]; let n = a.length; document.write(totalSum(a,n)); // This code is contributed shivanisinghss2110</script>", "e": 5476, "s": 4784, "text": null }, { "code": null, "e": 5479, "s": 5476, "text": "71" }, { "code": null, "e": 5497, "s": 5481, "text": "tufan_gupta2000" }, { "code": null, "e": 5510, "s": 5497, "text": "Mithun Kumar" }, { "code": null, "e": 5525, "s": 5510, "text": "Shivi_Aggarwal" }, { "code": null, "e": 5544, "s": 5525, "text": "shivanisinghss2110" }, { "code": null, "e": 5555, "s": 5544, "text": "Bitwise-OR" }, { "code": null, "e": 5562, "s": 5555, "text": "Arrays" }, { "code": null, "e": 5572, "s": 5562, "text": "Bit Magic" }, { "code": null, "e": 5579, "s": 5572, "text": "Arrays" }, { "code": null, "e": 5589, "s": 5579, "text": "Bit Magic" }, { "code": null, "e": 5687, "s": 5589, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5755, "s": 5687, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 5799, "s": 5755, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 5831, "s": 5799, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5879, "s": 5831, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 5893, "s": 5879, "text": "Linear Search" }, { "code": null, "e": 5920, "s": 5893, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 5966, "s": 5920, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 6034, "s": 5966, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 6094, "s": 6034, "text": "How to swap two numbers without using a temporary variable?" } ]
HISTTIMEFORMAT variable in Linux with Example
24 Dec, 2020 The bash shell in Linux allows us to access the command history i.e, the list of previously executed commands in sequence using the history command. The history command is used to keep track of all commands that were executed. It is very important during troubleshooting or for auditing. History command without setting the HISTTIMEFORMAT displays only command# and command but it does not display the time when the command was executed. So, to display the time stamp information associated with each history entry the HISTTIMEFORMAT has to be set. By default, the display of the history command is only the serial number and the command. The Syntax for the history command: $ history The output of the command can be seen in the image below: The above command does not display the time when the command was executed and hence we use HISTTIMEFORMAT variable. Syntax: HISTTIMEFORMAT='%d/%m/%y %T' or, HISTTIMEFORMAT="%F %T " After using any of the above commands both date and time will be displayed along with the commands. Output: 1 2020-12-14 14:09:17 whoami 2 2020-12-14 14:09:17 pwd 3 2020-12-14 14:09:17 echo "abc" 4 2020-12-14 14:09:17 pwd 5 2020-12-14 14:09:17 whoami 6 2020-12-14 14:09:17 clear 7 2020-12-14 14:09:17 man bash 8 2020-12-14 14:09:17 history Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2020" }, { "code": null, "e": 578, "s": 28, "text": "The bash shell in Linux allows us to access the command history i.e, the list of previously executed commands in sequence using the history command. The history command is used to keep track of all commands that were executed. It is very important during troubleshooting or for auditing. History command without setting the HISTTIMEFORMAT displays only command# and command but it does not display the time when the command was executed. So, to display the time stamp information associated with each history entry the HISTTIMEFORMAT has to be set. " }, { "code": null, "e": 704, "s": 578, "text": "By default, the display of the history command is only the serial number and the command. The Syntax for the history command:" }, { "code": null, "e": 714, "s": 704, "text": "$ history" }, { "code": null, "e": 772, "s": 714, "text": "The output of the command can be seen in the image below:" }, { "code": null, "e": 888, "s": 772, "text": "The above command does not display the time when the command was executed and hence we use HISTTIMEFORMAT variable." }, { "code": null, "e": 896, "s": 888, "text": "Syntax:" }, { "code": null, "e": 953, "s": 896, "text": "HISTTIMEFORMAT='%d/%m/%y %T'\nor,\nHISTTIMEFORMAT=\"%F %T \"" }, { "code": null, "e": 1053, "s": 953, "text": "After using any of the above commands both date and time will be displayed along with the commands." }, { "code": null, "e": 1061, "s": 1053, "text": "Output:" }, { "code": null, "e": 1301, "s": 1061, "text": "1 2020-12-14 14:09:17 whoami\n2 2020-12-14 14:09:17 pwd\n3 2020-12-14 14:09:17 echo \"abc\"\n4 2020-12-14 14:09:17 pwd\n5 2020-12-14 14:09:17 whoami\n6 2020-12-14 14:09:17 clear\n7 2020-12-14 14:09:17 man bash\n8 2020-12-14 14:09:17 history" }, { "code": null, "e": 1312, "s": 1301, "text": "Linux-Unix" }, { "code": null, "e": 1410, "s": 1312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1436, "s": 1410, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1471, "s": 1436, "text": "scp command in Linux with Examples" }, { "code": null, "e": 1508, "s": 1471, "text": "chown command in Linux with Examples" }, { "code": null, "e": 1537, "s": 1508, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 1574, "s": 1537, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 1608, "s": 1574, "text": "mv command in Linux with examples" }, { "code": null, "e": 1645, "s": 1608, "text": "chmod command in Linux with examples" }, { "code": null, "e": 1685, "s": 1645, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 1724, "s": 1685, "text": "Introduction to Linux Operating System" } ]
Insertion Sort for Doubly Linked List
22 Jun, 2022 Sort the doubly linked list using the insertion sort technique. Initial doubly linked list Doubly Linked List after applying insertion sort Algorithm: Below is a simple insertion sort algorithm for doubly-linked lists.1) Create an empty sorted (or result) doubly linked list. 2) Traverse the given doubly linked list, and do the following for every node. a) Insert the current node in a sorted way in the sorted(or result) doubly linked list. 3) Change the head of the given linked list to the head of the sorted (or result) list.The main step is (2. a), which has been covered in the post below. Sorted Insert for Doubly Linked List C++ Java Python3 C# Javascript // C++ implementation for insertion Sort// on a doubly linked list#include <bits/stdc++.h> using namespace std; // Node of a doubly linked liststruct Node { int data; struct Node* prev, *next;}; // function to create and return a new node// of a doubly linked liststruct Node* getNode(int data){ // allocate node struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // put in the data newNode->data = data; newNode->prev = newNode->next = NULL; return newNode;} // function to insert a new node in sorted way in// a sorted doubly linked listvoid sortedInsert(struct Node** head_ref, struct Node* newNode){ struct Node* current; // if list is empty if (*head_ref == NULL) *head_ref = newNode; // if the node is to be inserted at the beginning // of the doubly linked list else if ((*head_ref)->data >= newNode->data) { newNode->next = *head_ref; newNode->next->prev = newNode; *head_ref = newNode; } else { current = *head_ref; // locate the node after which the new node // is to be inserted while (current->next != NULL && current->next->data < newNode->data) current = current->next; /*Make the appropriate links */ newNode->next = current->next; // if the new node is not inserted // at the end of the list if (current->next != NULL) newNode->next->prev = newNode; current->next = newNode; newNode->prev = current; }} // function to sort a doubly linked list using insertion sortvoid insertionSort(struct Node** head_ref){ // Initialize 'sorted' - a sorted doubly linked list struct Node* sorted = NULL; // Traverse the given doubly linked list and // insert every node to 'sorted' struct Node* current = *head_ref; while (current != NULL) { // Store next for next iteration struct Node* next = current->next; // removing all the links so as to create 'current' // as a new node for insertion current->prev = current->next = NULL; // insert current in 'sorted' doubly linked list sortedInsert(&sorted, current); // Update current current = next; } // Update head_ref to point to sorted doubly linked list *head_ref = sorted;} // function to print the doubly linked listvoid printList(struct Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // function to insert a node at the beginning of// the doubly linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* Make next of new node as head and previous as NULL */ new_node->next = (*head_ref); new_node->prev = NULL; /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver program to test aboveint main(){ /* start with the empty doubly linked list */ struct Node* head = NULL; // insert the following data push(&head, 9); push(&head, 3); push(&head, 5); push(&head, 10); push(&head, 12); push(&head, 8); cout << "Doubly Linked List Before Sortingn"; printList(head); insertionSort(&head); cout << "nDoubly Linked List After Sortingn"; printList(head); return 0;} // Java implementation for insertion Sort// on a doubly linked listclass Solution{ // Node of a doubly linked liststatic class Node{ int data; Node prev, next;}; // function to create and return a new node// of a doubly linked liststatic Node getNode(int data){ // allocate node Node newNode = new Node(); // put in the data newNode.data = data; newNode.prev = newNode.next = null; return newNode;} // function to insert a new node in sorted way in// a sorted doubly linked liststatic Node sortedInsert(Node head_ref, Node newNode){ Node current; // if list is empty if (head_ref == null) head_ref = newNode; // if the node is to be inserted at the beginning // of the doubly linked list else if ((head_ref).data >= newNode.data) { newNode.next = head_ref; newNode.next.prev = newNode; head_ref = newNode; } else { current = head_ref; // locate the node after which the new node // is to be inserted while (current.next != null && current.next.data < newNode.data) current = current.next; //Make the appropriate links / newNode.next = current.next; // if the new node is not inserted // at the end of the list if (current.next != null) newNode.next.prev = newNode; current.next = newNode; newNode.prev = current; } return head_ref;} // function to sort a doubly linked list using insertion sortstatic Node insertionSort(Node head_ref){ // Initialize 'sorted' - a sorted doubly linked list Node sorted = null; // Traverse the given doubly linked list and // insert every node to 'sorted' Node current = head_ref; while (current != null) { // Store next for next iteration Node next = current.next; // removing all the links so as to create 'current' // as a new node for insertion current.prev = current.next = null; // insert current in 'sorted' doubly linked list sorted=sortedInsert(sorted, current); // Update current current = next; } // Update head_ref to point to sorted doubly linked list head_ref = sorted; return head_ref;} // function to print the doubly linked liststatic void printList(Node head){ while (head != null) { System.out.print(head.data + " "); head = head.next; }} // function to insert a node at the beginning of// the doubly linked liststatic Node push(Node head_ref, int new_data){ // allocate node / Node new_node = new Node(); // put in the data / new_node.data = new_data; // Make next of new node as head and previous as null / new_node.next = (head_ref); new_node.prev = null; // change prev of head node to new node / if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node / (head_ref) = new_node; return head_ref;} // Driver codepublic static void main(String args[]){ // start with the empty doubly linked list / Node head = null; // insert the following data head=push(head, 9); head=push(head, 3); head=push(head, 5); head=push(head, 10); head=push(head, 12); head=push(head, 8); System.out.println( "Doubly Linked List Before Sorting\n"); printList(head); head=insertionSort(head); System.out.println("\nDoubly Linked List After Sorting\n"); printList(head); }} // This code is contributed by Arnab Kundu # Python3 implementation for insertion Sort# on a doubly linked list # Node of a doubly linked listclass Node: def __init__(self, data): self.data = data self.prev = None self.next = None # function to create and return a new node# of a doubly linked listdef getNode(data): # allocate node newNode = Node(0) # put in the data newNode.data = data newNode.prev = newNode.next = None return newNode # function to insert a new node in sorted way in# a sorted doubly linked listdef sortedInsert(head_ref, newNode): current = None # if list is empty if (head_ref == None): head_ref = newNode # if the node is to be inserted at the beginning # of the doubly linked list elif ((head_ref).data >= newNode.data) : newNode.next = head_ref newNode.next.prev = newNode head_ref = newNode else : current = head_ref # locate the node after which the new node # is to be inserted while (current.next != None and current.next.data < newNode.data): current = current.next """Make the appropriate links """ newNode.next = current.next # if the new node is not inserted # at the end of the list if (current.next != None): newNode.next.prev = newNode current.next = newNode newNode.prev = current return head_ref; # function to sort a doubly linked list# using insertion sortdef insertionSort( head_ref): # Initialize 'sorted' - a sorted # doubly linked list sorted = None # Traverse the given doubly linked list # and insert every node to 'sorted' current = head_ref while (current != None) : # Store next for next iteration next = current.next # removing all the links so as to create # 'current' as a new node for insertion current.prev = current.next = None # insert current in 'sorted' doubly linked list sorted = sortedInsert(sorted, current) # Update current current = next # Update head_ref to point to # sorted doubly linked list head_ref = sorted return head_ref # function to print the doubly linked listdef printList(head): while (head != None) : print( head.data, end = " ") head = head.next # function to insert a node at the# beginning of the doubly linked listdef push(head_ref, new_data): """ allocate node """ new_node = Node(0) """ put in the data """ new_node.data = new_data """ Make next of new node as head and previous as None """ new_node.next = (head_ref) new_node.prev = None """ change prev of head node to new node """ if ((head_ref) != None): (head_ref).prev = new_node """ move the head to point to the new node """ (head_ref) = new_node return head_ref # Driver Codeif __name__ == "__main__": """ start with the empty doubly linked list """ head = None # insert the following data head = push(head, 9) head = push(head, 3) head = push(head, 5) head = push(head, 10) head = push(head, 12) head = push(head, 8) print( "Doubly Linked List Before Sorting") printList(head) head = insertionSort(head) print("\nDoubly Linked List After Sorting") printList(head) # This code is contributed by Arnab Kundu // C# implementation for insertion Sort// on a doubly linked listusing System; class GFG{ // Node of a doubly linked listpublic class Node{ public int data; public Node prev, next;}; // function to create and return a new node// of a doubly linked liststatic Node getNode(int data){ // allocate node Node newNode = new Node(); // put in the data newNode.data = data; newNode.prev = newNode.next = null; return newNode;} // function to insert a new node in sorted way// in a sorted doubly linked liststatic Node sortedInsert(Node head_ref, Node newNode){ Node current; // if list is empty if (head_ref == null) head_ref = newNode; // if the node is to be inserted at the beginning // of the doubly linked list else if ((head_ref).data >= newNode.data) { newNode.next = head_ref; newNode.next.prev = newNode; head_ref = newNode; } else { current = head_ref; // locate the node after which // the new node is to be inserted while (current.next != null && current.next.data < newNode.data) current = current.next; //Make the appropriate links newNode.next = current.next; // if the new node is not inserted // at the end of the list if (current.next != null) newNode.next.prev = newNode; current.next = newNode; newNode.prev = current; } return head_ref;} // function to sort a doubly linked list// using insertion sortstatic Node insertionSort(Node head_ref){ // Initialize 'sorted' - a sorted doubly linked list Node sorted = null; // Traverse the given doubly linked list and // insert every node to 'sorted' Node current = head_ref; while (current != null) { // Store next for next iteration Node next = current.next; // removing all the links so as to create // 'current' as a new node for insertion current.prev = current.next = null; // insert current in 'sorted' doubly linked list sorted = sortedInsert(sorted, current); // Update current current = next; } // Update head_ref to point to // sorted doubly linked list head_ref = sorted; return head_ref;} // function to print the doubly linked liststatic void printList(Node head){ while (head != null) { Console.Write(head.data + " "); head = head.next; }} // function to insert a node at the beginning of// the doubly linked liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // Make next of new node as head // and previous as null new_node.next = (head_ref); new_node.prev = null; // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // Driver codepublic static void Main(String []args){ // start with the empty doubly linked list Node head = null; // insert the following data head = push(head, 9); head = push(head, 3); head = push(head, 5); head = push(head, 10); head = push(head, 12); head = push(head, 8); Console.WriteLine("Doubly Linked List Before Sorting"); printList(head); head = insertionSort(head); Console.WriteLine("\nDoubly Linked List After Sorting"); printList(head);}} // This code is contributed by Princi Singh <script> // javascript implementation for insertion Sort // on a doubly linked list // Node of a doubly linked list class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } // function to create and return a new node // of a doubly linked list function getNode(data) { // allocate node var newNode = new Node(); // put in the data newNode.data = data; newNode.prev = newNode.next = null; return newNode; } // function to insert a new node in sorted way in // a sorted doubly linked list function sortedInsert(head_ref, newNode) { var current; // if list is empty if (head_ref == null) head_ref = newNode; // if the node is to be inserted at the beginning // of the doubly linked list else if ((head_ref).data >= newNode.data) { newNode.next = head_ref; newNode.next.prev = newNode; head_ref = newNode; } else { current = head_ref; // locate the node after which the new node // is to be inserted while (current.next != null && current.next.data < newNode.data) current = current.next; // Make the appropriate links / newNode.next = current.next; // if the new node is not inserted // at the end of the list if (current.next != null) newNode.next.prev = newNode; current.next = newNode; newNode.prev = current; } return head_ref; } // function to sort a doubly linked list using insertion sort function insertionSort(head_ref) { // Initialize 'sorted' - a sorted doubly linked list var sorted = null; // Traverse the given doubly linked list and // insert every node to 'sorted' var current = head_ref; while (current != null) { // Store next for next iteration var next = current.next; // removing all the links so as to create 'current' // as a new node for insertion current.prev = current.next = null; // insert current in 'sorted' doubly linked list sorted = sortedInsert(sorted, current); // Update current current = next; } // Update head_ref to point to sorted doubly linked list head_ref = sorted; return head_ref; } // function to print the doubly linked list function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } } // function to insert a node at the beginning of // the doubly linked list function push(head_ref , new_data) { // allocate node / var new_node = new Node(); // put in the data / new_node.data = new_data; // Make next of new node as head and previous as null / new_node.next = (head_ref); new_node.prev = null; // change prev of head node to new node / if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node / (head_ref) = new_node; return head_ref; } // Driver code // start with the empty doubly linked list / var head = null; // insert the following data head = push(head, 9); head = push(head, 3); head = push(head, 5); head = push(head, 10); head = push(head, 12); head = push(head, 8); document.write("Doubly Linked List Before Sorting<br/>"); printList(head); head = insertionSort(head); document.write("<br/>Doubly Linked List After Sorting<br/>"); printList(head); // This code contributed by umadevi9616</script> Output: Doubly Linked List Before Sorting 8 12 10 5 3 9 Doubly Linked List After Sorting 3 5 8 9 10 12 Time Complexity: O(n*n), as we are using a loop to traverse n times and in each traversal, we are calling the function sortedInsert which costs O(n) time (as we are traversing n time to insert the node). Where n is the number of nodes in the linked list. Auxiliary Space: O(1), as we are not using any extra space. 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 if you want to share more information about the topic discussed above. andrew1234 princi singh umadevi9616 simranarora5sos rohan07 doubly linked list Insertion Sort Linked-List-Sorting Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HeapSort std::sort() in C++ STL Time Complexities of all Sorting Algorithms Merge two sorted arrays Count Inversions in an array | Set 1 (Using Merge Sort) Sort an array of 0s, 1s and 2s | Dutch National Flag problem Radix Sort Chocolate Distribution Problem Find a triplet that sum to a given value k largest(or smallest) elements in an array
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Jun, 2022" }, { "code": null, "e": 117, "s": 53, "text": "Sort the doubly linked list using the insertion sort technique." }, { "code": null, "e": 145, "s": 117, "text": "Initial doubly linked list " }, { "code": null, "e": 195, "s": 145, "text": "Doubly Linked List after applying insertion sort " }, { "code": null, "e": 695, "s": 195, "text": "Algorithm: Below is a simple insertion sort algorithm for doubly-linked lists.1) Create an empty sorted (or result) doubly linked list. 2) Traverse the given doubly linked list, and do the following for every node. a) Insert the current node in a sorted way in the sorted(or result) doubly linked list. 3) Change the head of the given linked list to the head of the sorted (or result) list.The main step is (2. a), which has been covered in the post below. Sorted Insert for Doubly Linked List " }, { "code": null, "e": 699, "s": 695, "text": "C++" }, { "code": null, "e": 704, "s": 699, "text": "Java" }, { "code": null, "e": 712, "s": 704, "text": "Python3" }, { "code": null, "e": 715, "s": 712, "text": "C#" }, { "code": null, "e": 726, "s": 715, "text": "Javascript" }, { "code": "// C++ implementation for insertion Sort// on a doubly linked list#include <bits/stdc++.h> using namespace std; // Node of a doubly linked liststruct Node { int data; struct Node* prev, *next;}; // function to create and return a new node// of a doubly linked liststruct Node* getNode(int data){ // allocate node struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // put in the data newNode->data = data; newNode->prev = newNode->next = NULL; return newNode;} // function to insert a new node in sorted way in// a sorted doubly linked listvoid sortedInsert(struct Node** head_ref, struct Node* newNode){ struct Node* current; // if list is empty if (*head_ref == NULL) *head_ref = newNode; // if the node is to be inserted at the beginning // of the doubly linked list else if ((*head_ref)->data >= newNode->data) { newNode->next = *head_ref; newNode->next->prev = newNode; *head_ref = newNode; } else { current = *head_ref; // locate the node after which the new node // is to be inserted while (current->next != NULL && current->next->data < newNode->data) current = current->next; /*Make the appropriate links */ newNode->next = current->next; // if the new node is not inserted // at the end of the list if (current->next != NULL) newNode->next->prev = newNode; current->next = newNode; newNode->prev = current; }} // function to sort a doubly linked list using insertion sortvoid insertionSort(struct Node** head_ref){ // Initialize 'sorted' - a sorted doubly linked list struct Node* sorted = NULL; // Traverse the given doubly linked list and // insert every node to 'sorted' struct Node* current = *head_ref; while (current != NULL) { // Store next for next iteration struct Node* next = current->next; // removing all the links so as to create 'current' // as a new node for insertion current->prev = current->next = NULL; // insert current in 'sorted' doubly linked list sortedInsert(&sorted, current); // Update current current = next; } // Update head_ref to point to sorted doubly linked list *head_ref = sorted;} // function to print the doubly linked listvoid printList(struct Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // function to insert a node at the beginning of// the doubly linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* Make next of new node as head and previous as NULL */ new_node->next = (*head_ref); new_node->prev = NULL; /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver program to test aboveint main(){ /* start with the empty doubly linked list */ struct Node* head = NULL; // insert the following data push(&head, 9); push(&head, 3); push(&head, 5); push(&head, 10); push(&head, 12); push(&head, 8); cout << \"Doubly Linked List Before Sortingn\"; printList(head); insertionSort(&head); cout << \"nDoubly Linked List After Sortingn\"; printList(head); return 0;}", "e": 4284, "s": 726, "text": null }, { "code": "// Java implementation for insertion Sort// on a doubly linked listclass Solution{ // Node of a doubly linked liststatic class Node{ int data; Node prev, next;}; // function to create and return a new node// of a doubly linked liststatic Node getNode(int data){ // allocate node Node newNode = new Node(); // put in the data newNode.data = data; newNode.prev = newNode.next = null; return newNode;} // function to insert a new node in sorted way in// a sorted doubly linked liststatic Node sortedInsert(Node head_ref, Node newNode){ Node current; // if list is empty if (head_ref == null) head_ref = newNode; // if the node is to be inserted at the beginning // of the doubly linked list else if ((head_ref).data >= newNode.data) { newNode.next = head_ref; newNode.next.prev = newNode; head_ref = newNode; } else { current = head_ref; // locate the node after which the new node // is to be inserted while (current.next != null && current.next.data < newNode.data) current = current.next; //Make the appropriate links / newNode.next = current.next; // if the new node is not inserted // at the end of the list if (current.next != null) newNode.next.prev = newNode; current.next = newNode; newNode.prev = current; } return head_ref;} // function to sort a doubly linked list using insertion sortstatic Node insertionSort(Node head_ref){ // Initialize 'sorted' - a sorted doubly linked list Node sorted = null; // Traverse the given doubly linked list and // insert every node to 'sorted' Node current = head_ref; while (current != null) { // Store next for next iteration Node next = current.next; // removing all the links so as to create 'current' // as a new node for insertion current.prev = current.next = null; // insert current in 'sorted' doubly linked list sorted=sortedInsert(sorted, current); // Update current current = next; } // Update head_ref to point to sorted doubly linked list head_ref = sorted; return head_ref;} // function to print the doubly linked liststatic void printList(Node head){ while (head != null) { System.out.print(head.data + \" \"); head = head.next; }} // function to insert a node at the beginning of// the doubly linked liststatic Node push(Node head_ref, int new_data){ // allocate node / Node new_node = new Node(); // put in the data / new_node.data = new_data; // Make next of new node as head and previous as null / new_node.next = (head_ref); new_node.prev = null; // change prev of head node to new node / if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node / (head_ref) = new_node; return head_ref;} // Driver codepublic static void main(String args[]){ // start with the empty doubly linked list / Node head = null; // insert the following data head=push(head, 9); head=push(head, 3); head=push(head, 5); head=push(head, 10); head=push(head, 12); head=push(head, 8); System.out.println( \"Doubly Linked List Before Sorting\\n\"); printList(head); head=insertionSort(head); System.out.println(\"\\nDoubly Linked List After Sorting\\n\"); printList(head); }} // This code is contributed by Arnab Kundu", "e": 7801, "s": 4284, "text": null }, { "code": "# Python3 implementation for insertion Sort# on a doubly linked list # Node of a doubly linked listclass Node: def __init__(self, data): self.data = data self.prev = None self.next = None # function to create and return a new node# of a doubly linked listdef getNode(data): # allocate node newNode = Node(0) # put in the data newNode.data = data newNode.prev = newNode.next = None return newNode # function to insert a new node in sorted way in# a sorted doubly linked listdef sortedInsert(head_ref, newNode): current = None # if list is empty if (head_ref == None): head_ref = newNode # if the node is to be inserted at the beginning # of the doubly linked list elif ((head_ref).data >= newNode.data) : newNode.next = head_ref newNode.next.prev = newNode head_ref = newNode else : current = head_ref # locate the node after which the new node # is to be inserted while (current.next != None and current.next.data < newNode.data): current = current.next \"\"\"Make the appropriate links \"\"\" newNode.next = current.next # if the new node is not inserted # at the end of the list if (current.next != None): newNode.next.prev = newNode current.next = newNode newNode.prev = current return head_ref; # function to sort a doubly linked list# using insertion sortdef insertionSort( head_ref): # Initialize 'sorted' - a sorted # doubly linked list sorted = None # Traverse the given doubly linked list # and insert every node to 'sorted' current = head_ref while (current != None) : # Store next for next iteration next = current.next # removing all the links so as to create # 'current' as a new node for insertion current.prev = current.next = None # insert current in 'sorted' doubly linked list sorted = sortedInsert(sorted, current) # Update current current = next # Update head_ref to point to # sorted doubly linked list head_ref = sorted return head_ref # function to print the doubly linked listdef printList(head): while (head != None) : print( head.data, end = \" \") head = head.next # function to insert a node at the# beginning of the doubly linked listdef push(head_ref, new_data): \"\"\" allocate node \"\"\" new_node = Node(0) \"\"\" put in the data \"\"\" new_node.data = new_data \"\"\" Make next of new node as head and previous as None \"\"\" new_node.next = (head_ref) new_node.prev = None \"\"\" change prev of head node to new node \"\"\" if ((head_ref) != None): (head_ref).prev = new_node \"\"\" move the head to point to the new node \"\"\" (head_ref) = new_node return head_ref # Driver Codeif __name__ == \"__main__\": \"\"\" start with the empty doubly linked list \"\"\" head = None # insert the following data head = push(head, 9) head = push(head, 3) head = push(head, 5) head = push(head, 10) head = push(head, 12) head = push(head, 8) print( \"Doubly Linked List Before Sorting\") printList(head) head = insertionSort(head) print(\"\\nDoubly Linked List After Sorting\") printList(head) # This code is contributed by Arnab Kundu", "e": 11179, "s": 7801, "text": null }, { "code": "// C# implementation for insertion Sort// on a doubly linked listusing System; class GFG{ // Node of a doubly linked listpublic class Node{ public int data; public Node prev, next;}; // function to create and return a new node// of a doubly linked liststatic Node getNode(int data){ // allocate node Node newNode = new Node(); // put in the data newNode.data = data; newNode.prev = newNode.next = null; return newNode;} // function to insert a new node in sorted way// in a sorted doubly linked liststatic Node sortedInsert(Node head_ref, Node newNode){ Node current; // if list is empty if (head_ref == null) head_ref = newNode; // if the node is to be inserted at the beginning // of the doubly linked list else if ((head_ref).data >= newNode.data) { newNode.next = head_ref; newNode.next.prev = newNode; head_ref = newNode; } else { current = head_ref; // locate the node after which // the new node is to be inserted while (current.next != null && current.next.data < newNode.data) current = current.next; //Make the appropriate links newNode.next = current.next; // if the new node is not inserted // at the end of the list if (current.next != null) newNode.next.prev = newNode; current.next = newNode; newNode.prev = current; } return head_ref;} // function to sort a doubly linked list// using insertion sortstatic Node insertionSort(Node head_ref){ // Initialize 'sorted' - a sorted doubly linked list Node sorted = null; // Traverse the given doubly linked list and // insert every node to 'sorted' Node current = head_ref; while (current != null) { // Store next for next iteration Node next = current.next; // removing all the links so as to create // 'current' as a new node for insertion current.prev = current.next = null; // insert current in 'sorted' doubly linked list sorted = sortedInsert(sorted, current); // Update current current = next; } // Update head_ref to point to // sorted doubly linked list head_ref = sorted; return head_ref;} // function to print the doubly linked liststatic void printList(Node head){ while (head != null) { Console.Write(head.data + \" \"); head = head.next; }} // function to insert a node at the beginning of// the doubly linked liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // Make next of new node as head // and previous as null new_node.next = (head_ref); new_node.prev = null; // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // Driver codepublic static void Main(String []args){ // start with the empty doubly linked list Node head = null; // insert the following data head = push(head, 9); head = push(head, 3); head = push(head, 5); head = push(head, 10); head = push(head, 12); head = push(head, 8); Console.WriteLine(\"Doubly Linked List Before Sorting\"); printList(head); head = insertionSort(head); Console.WriteLine(\"\\nDoubly Linked List After Sorting\"); printList(head);}} // This code is contributed by Princi Singh", "e": 14755, "s": 11179, "text": null }, { "code": "<script> // javascript implementation for insertion Sort // on a doubly linked list // Node of a doubly linked list class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } // function to create and return a new node // of a doubly linked list function getNode(data) { // allocate node var newNode = new Node(); // put in the data newNode.data = data; newNode.prev = newNode.next = null; return newNode; } // function to insert a new node in sorted way in // a sorted doubly linked list function sortedInsert(head_ref, newNode) { var current; // if list is empty if (head_ref == null) head_ref = newNode; // if the node is to be inserted at the beginning // of the doubly linked list else if ((head_ref).data >= newNode.data) { newNode.next = head_ref; newNode.next.prev = newNode; head_ref = newNode; } else { current = head_ref; // locate the node after which the new node // is to be inserted while (current.next != null && current.next.data < newNode.data) current = current.next; // Make the appropriate links / newNode.next = current.next; // if the new node is not inserted // at the end of the list if (current.next != null) newNode.next.prev = newNode; current.next = newNode; newNode.prev = current; } return head_ref; } // function to sort a doubly linked list using insertion sort function insertionSort(head_ref) { // Initialize 'sorted' - a sorted doubly linked list var sorted = null; // Traverse the given doubly linked list and // insert every node to 'sorted' var current = head_ref; while (current != null) { // Store next for next iteration var next = current.next; // removing all the links so as to create 'current' // as a new node for insertion current.prev = current.next = null; // insert current in 'sorted' doubly linked list sorted = sortedInsert(sorted, current); // Update current current = next; } // Update head_ref to point to sorted doubly linked list head_ref = sorted; return head_ref; } // function to print the doubly linked list function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } } // function to insert a node at the beginning of // the doubly linked list function push(head_ref , new_data) { // allocate node / var new_node = new Node(); // put in the data / new_node.data = new_data; // Make next of new node as head and previous as null / new_node.next = (head_ref); new_node.prev = null; // change prev of head node to new node / if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node / (head_ref) = new_node; return head_ref; } // Driver code // start with the empty doubly linked list / var head = null; // insert the following data head = push(head, 9); head = push(head, 3); head = push(head, 5); head = push(head, 10); head = push(head, 12); head = push(head, 8); document.write(\"Doubly Linked List Before Sorting<br/>\"); printList(head); head = insertionSort(head); document.write(\"<br/>Doubly Linked List After Sorting<br/>\"); printList(head); // This code contributed by umadevi9616</script>", "e": 18629, "s": 14755, "text": null }, { "code": null, "e": 18638, "s": 18629, "text": "Output: " }, { "code": null, "e": 18733, "s": 18638, "text": "Doubly Linked List Before Sorting\n8 12 10 5 3 9\nDoubly Linked List After Sorting\n3 5 8 9 10 12" }, { "code": null, "e": 18988, "s": 18733, "text": "Time Complexity: O(n*n), as we are using a loop to traverse n times and in each traversal, we are calling the function sortedInsert which costs O(n) time (as we are traversing n time to insert the node). Where n is the number of nodes in the linked list." }, { "code": null, "e": 19048, "s": 18988, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 19473, "s": 19048, "text": "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 if you want to share more information about the topic discussed above. " }, { "code": null, "e": 19484, "s": 19473, "text": "andrew1234" }, { "code": null, "e": 19497, "s": 19484, "text": "princi singh" }, { "code": null, "e": 19509, "s": 19497, "text": "umadevi9616" }, { "code": null, "e": 19525, "s": 19509, "text": "simranarora5sos" }, { "code": null, "e": 19533, "s": 19525, "text": "rohan07" }, { "code": null, "e": 19552, "s": 19533, "text": "doubly linked list" }, { "code": null, "e": 19567, "s": 19552, "text": "Insertion Sort" }, { "code": null, "e": 19587, "s": 19567, "text": "Linked-List-Sorting" }, { "code": null, "e": 19595, "s": 19587, "text": "Sorting" }, { "code": null, "e": 19603, "s": 19595, "text": "Sorting" }, { "code": null, "e": 19701, "s": 19603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19710, "s": 19701, "text": "HeapSort" }, { "code": null, "e": 19733, "s": 19710, "text": "std::sort() in C++ STL" }, { "code": null, "e": 19777, "s": 19733, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 19801, "s": 19777, "text": "Merge two sorted arrays" }, { "code": null, "e": 19857, "s": 19801, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 19918, "s": 19857, "text": "Sort an array of 0s, 1s and 2s | Dutch National Flag problem" }, { "code": null, "e": 19929, "s": 19918, "text": "Radix Sort" }, { "code": null, "e": 19960, "s": 19929, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 20001, "s": 19960, "text": "Find a triplet that sum to a given value" } ]
How to dynamically add or remove items from a list in Vue.js ?
19 Feb, 2021 Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. Using Vue.js one can easily add or remove items in a list dynamically using the v-model directive. This directive binds all the possibilities to a single channel. When the user selects an option from the list of available ones, it adds it to the list of values. Similarly, if the user deselects any option, it removes it from the list of values. Example: index.html <html><head> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"> </script></head><body> <div id='parent'> <h1 style="color: green;"> GeeksforGeeks </h1> <p><strong>Favourite Sports:</strong> </p> <input type="checkbox" id="cricket" value="cricket" v-model="sports"> <label for="cricket">Cricket</label> <input type="checkbox" id="football" value="football" v-model="sports"> <label for="football">Football</label> <input type="checkbox" id="hockey" value="hockey" v-model="sports"> <label for="hockey">Hockey</label> <input type="checkbox" id="badminton" value="badminton" v-model="sports"> <label for="badminton">Badminton</label> <input type="checkbox" id="arching" value="arching" v-model="sports"> <label for="arching">Arching</label> <p><strong>Sports You Like:</strong> {{ sports }} </p> </div> <script src='app.js'></script></body></html> app.js const parent = new Vue({ el : '#parent', data : { sports : [] }}) Output: Vue.JS 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 Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Feb, 2021" }, { "code": null, "e": 368, "s": 54, "text": "Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. " }, { "code": null, "e": 714, "s": 368, "text": "Using Vue.js one can easily add or remove items in a list dynamically using the v-model directive. This directive binds all the possibilities to a single channel. When the user selects an option from the list of available ones, it adds it to the list of values. Similarly, if the user deselects any option, it removes it from the list of values." }, { "code": null, "e": 723, "s": 714, "text": "Example:" }, { "code": null, "e": 734, "s": 723, "text": "index.html" }, { "code": "<html><head> <script src=\"https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js\"> </script></head><body> <div id='parent'> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p><strong>Favourite Sports:</strong> </p> <input type=\"checkbox\" id=\"cricket\" value=\"cricket\" v-model=\"sports\"> <label for=\"cricket\">Cricket</label> <input type=\"checkbox\" id=\"football\" value=\"football\" v-model=\"sports\"> <label for=\"football\">Football</label> <input type=\"checkbox\" id=\"hockey\" value=\"hockey\" v-model=\"sports\"> <label for=\"hockey\">Hockey</label> <input type=\"checkbox\" id=\"badminton\" value=\"badminton\" v-model=\"sports\"> <label for=\"badminton\">Badminton</label> <input type=\"checkbox\" id=\"arching\" value=\"arching\" v-model=\"sports\"> <label for=\"arching\">Arching</label> <p><strong>Sports You Like:</strong> {{ sports }} </p> </div> <script src='app.js'></script></body></html>", "e": 1834, "s": 734, "text": null }, { "code": null, "e": 1841, "s": 1834, "text": "app.js" }, { "code": "const parent = new Vue({ el : '#parent', data : { sports : [] }})", "e": 1923, "s": 1841, "text": null }, { "code": null, "e": 1931, "s": 1923, "text": "Output:" }, { "code": null, "e": 1938, "s": 1931, "text": "Vue.JS" }, { "code": null, "e": 1949, "s": 1938, "text": "JavaScript" }, { "code": null, "e": 1966, "s": 1949, "text": "Web Technologies" }, { "code": null, "e": 2064, "s": 1966, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2125, "s": 2064, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2165, "s": 2125, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2206, "s": 2165, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2248, "s": 2206, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2270, "s": 2248, "text": "JavaScript | Promises" }, { "code": null, "e": 2332, "s": 2270, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2365, "s": 2332, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2426, "s": 2365, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2476, "s": 2426, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Sorting of a Vector in R Programming – sort() Function
05 Jun, 2020 sort() function in R Language is used to sort a vector by its values. It takes Boolean value as argument to sort in ascending or descending order. Syntax:sort(x, decreasing, na.last) Parameters:x: Vector to be sorteddecreasing: Boolean value to sort in descending orderna.last: Boolean value to put NA at the end Example 1: # R program to sort a vector # Creating a vectorx <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA) # Calling sort() functionsort(x) Output: [1] -8.0 -5.0 -4.0 1.2 3.0 4.0 6.0 7.0 9.0 Example 2: # R program to sort a vector # Creating a vectorx <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA) # Calling sort() function# to print in decreasing ordersort(x, decreasing = TRUE) # Calling sort() function# to print NA at the endsort(x, na.last = TRUE) Output: [1] 9.0 7.0 6.0 4.0 3.0 1.2 -4.0 -5.0 -8.0 [1] -8.0 -5.0 -4.0 1.2 3.0 4.0 6.0 7.0 9.0 NA R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? R Programming Language - Introduction How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 175, "s": 28, "text": "sort() function in R Language is used to sort a vector by its values. It takes Boolean value as argument to sort in ascending or descending order." }, { "code": null, "e": 211, "s": 175, "text": "Syntax:sort(x, decreasing, na.last)" }, { "code": null, "e": 341, "s": 211, "text": "Parameters:x: Vector to be sorteddecreasing: Boolean value to sort in descending orderna.last: Boolean value to put NA at the end" }, { "code": null, "e": 352, "s": 341, "text": "Example 1:" }, { "code": "# R program to sort a vector # Creating a vectorx <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA) # Calling sort() functionsort(x)", "e": 478, "s": 352, "text": null }, { "code": null, "e": 486, "s": 478, "text": "Output:" }, { "code": null, "e": 536, "s": 486, "text": "[1] -8.0 -5.0 -4.0 1.2 3.0 4.0 6.0 7.0 9.0\n" }, { "code": null, "e": 547, "s": 536, "text": "Example 2:" }, { "code": "# R program to sort a vector # Creating a vectorx <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA) # Calling sort() function# to print in decreasing ordersort(x, decreasing = TRUE) # Calling sort() function# to print NA at the endsort(x, na.last = TRUE)", "e": 796, "s": 547, "text": null }, { "code": null, "e": 804, "s": 796, "text": "Output:" }, { "code": null, "e": 908, "s": 804, "text": "[1] 9.0 7.0 6.0 4.0 3.0 1.2 -4.0 -5.0 -8.0\n[1] -8.0 -5.0 -4.0 1.2 3.0 4.0 6.0 7.0 9.0 NA\n" }, { "code": null, "e": 926, "s": 908, "text": "R Vector-Function" }, { "code": null, "e": 937, "s": 926, "text": "R Language" }, { "code": null, "e": 1035, "s": 937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1087, "s": 1035, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 1145, "s": 1087, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 1197, "s": 1145, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1255, "s": 1197, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1287, "s": 1255, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 1322, "s": 1287, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1366, "s": 1322, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 1404, "s": 1366, "text": "R Programming Language - Introduction" }, { "code": null, "e": 1442, "s": 1404, "text": "How to Change Axis Scales in R Plots?" } ]
Python OpenCV – Bicubic Interpolation for Resizing Image
08 May, 2021 Image resizing is a crucial concept that wishes to augment or reduce the number of pixels in a picture. Applications of image resizing can occur under a wider form of scenarios: transliteration of the image, correcting for lens distortion, changing perspective, and rotating a picture. The results of resizing greatly vary looking on the kind of interpolation algorithm used. Note: While applying interpolation algorithms, some information is certain to be lost as these are approximation algorithms. Interpolation works by using known data to estimate values at unknown points. For example: if you wanted to understand the pixel intensity of a picture at a selected location within the grid (say coordinate (x, y), but only (x-1,y-1) and (x+1,y+1) are known, you’ll estimate the value at (x, y) using linear interpolation. The greater the quantity of already known values, the higher would be the accuracy of the estimated pixel value. Different interpolation algorithms include the nearest neighbor, bilinear, bicubic, and others. Betting on their complexity, these use anywhere from 0 to 256 (or more) adjacent pixels when interpolating. The accuracy of those algorithms is increased significantly by increasing the number of neighboring pixels considered while evaluation of the new pixel value. Interpolation algorithms are predominantly used for resizing and distorting a high-resolution image to an occasional resolution image. There are various interpolation algorithms one of them is Bicubic Interpolation. In addition to going 2×2 neighborhood of known pixel values, Bicubic goes one step beyond bilinear by considering the closest 4×4 neighborhood of known pixels — for a complete of 16 pixels. The pixels that are closer to the one that’s to be estimated are given higher weights as compared to those that are further away. Therefore, the farthest pixels have the smallest amount of weight. The results of Bicubic interpolation are far better as compared to NN or bilinear algorithms. This can be because a greater number of known pixel values are considered while estimating the desired value. Thus, making it one of all the foremost standard interpolation methods. Importing the necessary modules: We import all dependencies like cv2 (OpenCV), NumPy, and math. Python # Import modulesimport cv2import numpy as npimport mathimport sys, time Writing the Interpolation Kernel Function for Bicubic Interpolation: The interpolation kernel for bicubic is of the form: Kernel equation Here the value of coefficient a determines the performance of the kernel and it lies mostly between -0.5 to -0.75 for optimum performance. Python # Interpolation kerneldef u(s, a): if (abs(s) >= 0) & (abs(s) <= 1): return (a+2)*(abs(s)**3)-(a+3)*(abs(s)**2)+1 elif (abs(s) > 1) & (abs(s) <= 2): return a*(abs(s)**3)-(5*a)*(abs(s)**2)+(8*a)*abs(s)-4*a return 0 Adding padding to the input image: Define padding function to add borders to your image. OpenCV has various padding functions. When interpolations require padding the source, the boundary of the source image needs to be extended because it needs to have information such that it can compute the pixel values of all destination pixels that lie along the boundaries. Python # Paddingdef padding(img, H, W, C): zimg = np.zeros((H+4, W+4, C)) zimg[2:H+2, 2:W+2, :C] = img # Pad the first/last two col and row zimg[2:H+2, 0:2, :C] = img[:, 0:1, :C] zimg[H+2:H+4, 2:W+2, :] = img[H-1:H, :, :] zimg[2:H+2, W+2:W+4, :] = img[:, W-1:W, :] zimg[0:2, 2:W+2, :C] = img[0:1, :, :C] # Pad the missing eight points zimg[0:2, 0:2, :C] = img[0, 0, :C] zimg[H+2:H+4, 0:2, :C] = img[H-1, 0, :C] zimg[H+2:H+4, W+2:W+4, :C] = img[H-1, W-1, :C] zimg[0:2, W+2:W+4, :C] = img[0, W-1, :C] return zimg Writing the bicubic interpolation function: Define bicubic function and pass the image as an input. (You can vary the scaling factor as x2 or x4 based on the requirement.) Python # Bicubic operationdef bicubic(img, ratio, a): # Get image size H, W, C = img.shape # Here H = Height, W = weight, # C = Number of channels if the # image is coloured. img = padding(img, H, W, C) # Create new image dH = math.floor(H*ratio) dW = math.floor(W*ratio) # Converting into matrix dst = np.zeros((dH, dW, 3)) # np.zeroes generates a matrix # consisting only of zeroes # Here we initialize our answer # (dst) as zero h = 1/ratio print('Start bicubic interpolation') print('It will take a little while...') inc = 0 for c in range(C): for j in range(dH): for i in range(dW): # Getting the coordinates of the # nearby values x, y = i * h + 2, j * h + 2 x1 = 1 + x - math.floor(x) x2 = x - math.floor(x) x3 = math.floor(x) + 1 - x x4 = math.floor(x) + 2 - x y1 = 1 + y - math.floor(y) y2 = y - math.floor(y) y3 = math.floor(y) + 1 - y y4 = math.floor(y) + 2 - y # Considering all nearby 16 values mat_l = np.matrix([[u(x1, a), u(x2, a), u(x3, a), u(x4, a)]]) mat_m = np.matrix([[img[int(y-y1), int(x-x1), c], img[int(y-y2), int(x-x1), c], img[int(y+y3), int(x-x1), c], img[int(y+y4), int(x-x1), c]], [img[int(y-y1), int(x-x2), c], img[int(y-y2), int(x-x2), c], img[int(y+y3), int(x-x2), c], img[int(y+y4), int(x-x2), c]], [img[int(y-y1), int(x+x3), c], img[int(y-y2), int(x+x3), c], img[int(y+y3), int(x+x3), c], img[int(y+y4), int(x+x3), c]], [img[int(y-y1), int(x+x4), c], img[int(y-y2), int(x+x4), c], img[int(y+y3), int(x+x4), c], img[int(y+y4), int(x+x4), c]]]) mat_r = np.matrix( [[u(y1, a)], [u(y2, a)], [u(y3, a)], [u(y4, a)]]) # Here the dot function is used to get the dot # product of 2 matrices dst[j, i, c] = np.dot(np.dot(mat_l, mat_m), mat_r) # If there is an error message, it # directly goes to stderr sys.stderr.write('\n') # Flushing the buffer sys.stderr.flush() return dst Taking input from the user and passing the input to the bicubic function to generate the resized image: Passing the desired image to the bicubic function and saving the output as a separate file in the directory. Python3 # Read image# You can put your input image over here # to run bicubic interpolation# The read function of Open CV is used # for this taskimg = cv2.imread('gfg.png') # Scale factorratio = 2 # Coefficienta = -1/2 # Passing the input image in the # bicubic functiondst = bicubic(img, ratio, a) print('Completed!') # Saving the output imagecv2.imwrite('bicubic.png', dst) bicubicImg=cv2.imread('bicubic.png') Compare the generated image with the input image: Use the shape() method to compare the height, width, and color mode of both images. Python3 # display shapes of both imagesprint('Original Image Shape:',img.shape)print('Generated Bicubic Image Shape:',bicubicImg.shape) Complete Code: Input Image: gfg.png Python3 # import modulesimport cv2import numpy as npimport mathimport sysimport time # Interpolation kerneldef u(s, a): if (abs(s) >= 0) & (abs(s) <= 1): return (a+2)*(abs(s)**3)-(a+3)*(abs(s)**2)+1 elif (abs(s) > 1) & (abs(s) <= 2): return a*(abs(s)**3)-(5*a)*(abs(s)**2)+(8*a)*abs(s)-4*a return 0 # Paddingdef padding(img, H, W, C): zimg = np.zeros((H+4, W+4, C)) zimg[2:H+2, 2:W+2, :C] = img # Pad the first/last two col and row zimg[2:H+2, 0:2, :C] = img[:, 0:1, :C] zimg[H+2:H+4, 2:W+2, :] = img[H-1:H, :, :] zimg[2:H+2, W+2:W+4, :] = img[:, W-1:W, :] zimg[0:2, 2:W+2, :C] = img[0:1, :, :C] # Pad the missing eight points zimg[0:2, 0:2, :C] = img[0, 0, :C] zimg[H+2:H+4, 0:2, :C] = img[H-1, 0, :C] zimg[H+2:H+4, W+2:W+4, :C] = img[H-1, W-1, :C] zimg[0:2, W+2:W+4, :C] = img[0, W-1, :C] return zimg # Bicubic operationdef bicubic(img, ratio, a): # Get image size H, W, C = img.shape # Here H = Height, W = weight, # C = Number of channels if the # image is coloured. img = padding(img, H, W, C) # Create new image dH = math.floor(H*ratio) dW = math.floor(W*ratio) # Converting into matrix dst = np.zeros((dH, dW, 3)) # np.zeroes generates a matrix # consisting only of zeroes # Here we initialize our answer # (dst) as zero h = 1/ratio print('Start bicubic interpolation') print('It will take a little while...') inc = 0 for c in range(C): for j in range(dH): for i in range(dW): # Getting the coordinates of the # nearby values x, y = i * h + 2, j * h + 2 x1 = 1 + x - math.floor(x) x2 = x - math.floor(x) x3 = math.floor(x) + 1 - x x4 = math.floor(x) + 2 - x y1 = 1 + y - math.floor(y) y2 = y - math.floor(y) y3 = math.floor(y) + 1 - y y4 = math.floor(y) + 2 - y # Considering all nearby 16 values mat_l = np.matrix([[u(x1, a), u(x2, a), u(x3, a), u(x4, a)]]) mat_m = np.matrix([[img[int(y-y1), int(x-x1), c], img[int(y-y2), int(x-x1), c], img[int(y+y3), int(x-x1), c], img[int(y+y4), int(x-x1), c]], [img[int(y-y1), int(x-x2), c], img[int(y-y2), int(x-x2), c], img[int(y+y3), int(x-x2), c], img[int(y+y4), int(x-x2), c]], [img[int(y-y1), int(x+x3), c], img[int(y-y2), int(x+x3), c], img[int(y+y3), int(x+x3), c], img[int(y+y4), int(x+x3), c]], [img[int(y-y1), int(x+x4), c], img[int(y-y2), int(x+x4), c], img[int(y+y3), int(x+x4), c], img[int(y+y4), int(x+x4), c]]]) mat_r = np.matrix( [[u(y1, a)], [u(y2, a)], [u(y3, a)], [u(y4, a)]]) # Here the dot function is used to get # the dot product of 2 matrices dst[j, i, c] = np.dot(np.dot(mat_l, mat_m), mat_r) # If there is an error message, it # directly goes to stderr sys.stderr.write('\n') # Flushing the buffer sys.stderr.flush() return dst # Read image# You can put your input image over # here to run bicubic interpolation# The read function of Open CV is used# for this taskimg = cv2.imread('gfg.png') # Scale factorratio = 2# Coefficienta = -1/2 # Passing the input image in the # bicubic functiondst = bicubic(img, ratio, a)print('Completed!') # Saving the output imagecv2.imwrite('bicubic.png', dst)bicubicImg = cv2.imread('bicubic.png') # display shapes of both imagesprint('Original Image Shape:', img.shape)print('Generated Bicubic Image Shape:', bicubicImg.shape) Output: Output Image: bicubic.png Explanation: Thus, from the above code, we can see that the input image has been resized using bicubic interpolation technique. The image given below has been compressed for publishing reasons. You can run the above code to see the implementation of increasing the size of the image smoothly using bicubic interpolation. The unknown pixel values here are filled by considering the 16 nearest known values. Image-Processing Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n08 May, 2021" }, { "code": null, "e": 428, "s": 52, "text": "Image resizing is a crucial concept that wishes to augment or reduce the number of pixels in a picture. Applications of image resizing can occur under a wider form of scenarios: transliteration of the image, correcting for lens distortion, changing perspective, and rotating a picture. The results of resizing greatly vary looking on the kind of interpolation algorithm used." }, { "code": null, "e": 554, "s": 428, "text": "Note: While applying interpolation algorithms, some information is certain to be lost as these are approximation algorithms. " }, { "code": null, "e": 990, "s": 554, "text": "Interpolation works by using known data to estimate values at unknown points. For example: if you wanted to understand the pixel intensity of a picture at a selected location within the grid (say coordinate (x, y), but only (x-1,y-1) and (x+1,y+1) are known, you’ll estimate the value at (x, y) using linear interpolation. The greater the quantity of already known values, the higher would be the accuracy of the estimated pixel value." }, { "code": null, "e": 1569, "s": 990, "text": "Different interpolation algorithms include the nearest neighbor, bilinear, bicubic, and others. Betting on their complexity, these use anywhere from 0 to 256 (or more) adjacent pixels when interpolating. The accuracy of those algorithms is increased significantly by increasing the number of neighboring pixels considered while evaluation of the new pixel value. Interpolation algorithms are predominantly used for resizing and distorting a high-resolution image to an occasional resolution image. There are various interpolation algorithms one of them is Bicubic Interpolation." }, { "code": null, "e": 2232, "s": 1569, "text": "In addition to going 2×2 neighborhood of known pixel values, Bicubic goes one step beyond bilinear by considering the closest 4×4 neighborhood of known pixels — for a complete of 16 pixels. The pixels that are closer to the one that’s to be estimated are given higher weights as compared to those that are further away. Therefore, the farthest pixels have the smallest amount of weight. The results of Bicubic interpolation are far better as compared to NN or bilinear algorithms. This can be because a greater number of known pixel values are considered while estimating the desired value. Thus, making it one of all the foremost standard interpolation methods." }, { "code": null, "e": 2328, "s": 2232, "text": "Importing the necessary modules: We import all dependencies like cv2 (OpenCV), NumPy, and math." }, { "code": null, "e": 2335, "s": 2328, "text": "Python" }, { "code": "# Import modulesimport cv2import numpy as npimport mathimport sys, time", "e": 2407, "s": 2335, "text": null }, { "code": null, "e": 2529, "s": 2407, "text": "Writing the Interpolation Kernel Function for Bicubic Interpolation: The interpolation kernel for bicubic is of the form:" }, { "code": null, "e": 2545, "s": 2529, "text": "Kernel equation" }, { "code": null, "e": 2684, "s": 2545, "text": "Here the value of coefficient a determines the performance of the kernel and it lies mostly between -0.5 to -0.75 for optimum performance." }, { "code": null, "e": 2691, "s": 2684, "text": "Python" }, { "code": "# Interpolation kerneldef u(s, a): if (abs(s) >= 0) & (abs(s) <= 1): return (a+2)*(abs(s)**3)-(a+3)*(abs(s)**2)+1 elif (abs(s) > 1) & (abs(s) <= 2): return a*(abs(s)**3)-(5*a)*(abs(s)**2)+(8*a)*abs(s)-4*a return 0", "e": 2940, "s": 2691, "text": null }, { "code": null, "e": 3305, "s": 2940, "text": "Adding padding to the input image: Define padding function to add borders to your image. OpenCV has various padding functions. When interpolations require padding the source, the boundary of the source image needs to be extended because it needs to have information such that it can compute the pixel values of all destination pixels that lie along the boundaries." }, { "code": null, "e": 3312, "s": 3305, "text": "Python" }, { "code": "# Paddingdef padding(img, H, W, C): zimg = np.zeros((H+4, W+4, C)) zimg[2:H+2, 2:W+2, :C] = img # Pad the first/last two col and row zimg[2:H+2, 0:2, :C] = img[:, 0:1, :C] zimg[H+2:H+4, 2:W+2, :] = img[H-1:H, :, :] zimg[2:H+2, W+2:W+4, :] = img[:, W-1:W, :] zimg[0:2, 2:W+2, :C] = img[0:1, :, :C] # Pad the missing eight points zimg[0:2, 0:2, :C] = img[0, 0, :C] zimg[H+2:H+4, 0:2, :C] = img[H-1, 0, :C] zimg[H+2:H+4, W+2:W+4, :C] = img[H-1, W-1, :C] zimg[0:2, W+2:W+4, :C] = img[0, W-1, :C] return zimg", "e": 3873, "s": 3312, "text": null }, { "code": null, "e": 4045, "s": 3873, "text": "Writing the bicubic interpolation function: Define bicubic function and pass the image as an input. (You can vary the scaling factor as x2 or x4 based on the requirement.)" }, { "code": null, "e": 4052, "s": 4045, "text": "Python" }, { "code": "# Bicubic operationdef bicubic(img, ratio, a): # Get image size H, W, C = img.shape # Here H = Height, W = weight, # C = Number of channels if the # image is coloured. img = padding(img, H, W, C) # Create new image dH = math.floor(H*ratio) dW = math.floor(W*ratio) # Converting into matrix dst = np.zeros((dH, dW, 3)) # np.zeroes generates a matrix # consisting only of zeroes # Here we initialize our answer # (dst) as zero h = 1/ratio print('Start bicubic interpolation') print('It will take a little while...') inc = 0 for c in range(C): for j in range(dH): for i in range(dW): # Getting the coordinates of the # nearby values x, y = i * h + 2, j * h + 2 x1 = 1 + x - math.floor(x) x2 = x - math.floor(x) x3 = math.floor(x) + 1 - x x4 = math.floor(x) + 2 - x y1 = 1 + y - math.floor(y) y2 = y - math.floor(y) y3 = math.floor(y) + 1 - y y4 = math.floor(y) + 2 - y # Considering all nearby 16 values mat_l = np.matrix([[u(x1, a), u(x2, a), u(x3, a), u(x4, a)]]) mat_m = np.matrix([[img[int(y-y1), int(x-x1), c], img[int(y-y2), int(x-x1), c], img[int(y+y3), int(x-x1), c], img[int(y+y4), int(x-x1), c]], [img[int(y-y1), int(x-x2), c], img[int(y-y2), int(x-x2), c], img[int(y+y3), int(x-x2), c], img[int(y+y4), int(x-x2), c]], [img[int(y-y1), int(x+x3), c], img[int(y-y2), int(x+x3), c], img[int(y+y3), int(x+x3), c], img[int(y+y4), int(x+x3), c]], [img[int(y-y1), int(x+x4), c], img[int(y-y2), int(x+x4), c], img[int(y+y3), int(x+x4), c], img[int(y+y4), int(x+x4), c]]]) mat_r = np.matrix( [[u(y1, a)], [u(y2, a)], [u(y3, a)], [u(y4, a)]]) # Here the dot function is used to get the dot # product of 2 matrices dst[j, i, c] = np.dot(np.dot(mat_l, mat_m), mat_r) # If there is an error message, it # directly goes to stderr sys.stderr.write('\\n') # Flushing the buffer sys.stderr.flush() return dst", "e": 6808, "s": 4052, "text": null }, { "code": null, "e": 7021, "s": 6808, "text": "Taking input from the user and passing the input to the bicubic function to generate the resized image: Passing the desired image to the bicubic function and saving the output as a separate file in the directory." }, { "code": null, "e": 7029, "s": 7021, "text": "Python3" }, { "code": "# Read image# You can put your input image over here # to run bicubic interpolation# The read function of Open CV is used # for this taskimg = cv2.imread('gfg.png') # Scale factorratio = 2 # Coefficienta = -1/2 # Passing the input image in the # bicubic functiondst = bicubic(img, ratio, a) print('Completed!') # Saving the output imagecv2.imwrite('bicubic.png', dst) bicubicImg=cv2.imread('bicubic.png')", "e": 7439, "s": 7029, "text": null }, { "code": null, "e": 7573, "s": 7439, "text": "Compare the generated image with the input image: Use the shape() method to compare the height, width, and color mode of both images." }, { "code": null, "e": 7581, "s": 7573, "text": "Python3" }, { "code": "# display shapes of both imagesprint('Original Image Shape:',img.shape)print('Generated Bicubic Image Shape:',bicubicImg.shape)", "e": 7709, "s": 7581, "text": null }, { "code": null, "e": 7724, "s": 7709, "text": "Complete Code:" }, { "code": null, "e": 7737, "s": 7724, "text": "Input Image:" }, { "code": null, "e": 7745, "s": 7737, "text": "gfg.png" }, { "code": null, "e": 7753, "s": 7745, "text": "Python3" }, { "code": "# import modulesimport cv2import numpy as npimport mathimport sysimport time # Interpolation kerneldef u(s, a): if (abs(s) >= 0) & (abs(s) <= 1): return (a+2)*(abs(s)**3)-(a+3)*(abs(s)**2)+1 elif (abs(s) > 1) & (abs(s) <= 2): return a*(abs(s)**3)-(5*a)*(abs(s)**2)+(8*a)*abs(s)-4*a return 0 # Paddingdef padding(img, H, W, C): zimg = np.zeros((H+4, W+4, C)) zimg[2:H+2, 2:W+2, :C] = img # Pad the first/last two col and row zimg[2:H+2, 0:2, :C] = img[:, 0:1, :C] zimg[H+2:H+4, 2:W+2, :] = img[H-1:H, :, :] zimg[2:H+2, W+2:W+4, :] = img[:, W-1:W, :] zimg[0:2, 2:W+2, :C] = img[0:1, :, :C] # Pad the missing eight points zimg[0:2, 0:2, :C] = img[0, 0, :C] zimg[H+2:H+4, 0:2, :C] = img[H-1, 0, :C] zimg[H+2:H+4, W+2:W+4, :C] = img[H-1, W-1, :C] zimg[0:2, W+2:W+4, :C] = img[0, W-1, :C] return zimg # Bicubic operationdef bicubic(img, ratio, a): # Get image size H, W, C = img.shape # Here H = Height, W = weight, # C = Number of channels if the # image is coloured. img = padding(img, H, W, C) # Create new image dH = math.floor(H*ratio) dW = math.floor(W*ratio) # Converting into matrix dst = np.zeros((dH, dW, 3)) # np.zeroes generates a matrix # consisting only of zeroes # Here we initialize our answer # (dst) as zero h = 1/ratio print('Start bicubic interpolation') print('It will take a little while...') inc = 0 for c in range(C): for j in range(dH): for i in range(dW): # Getting the coordinates of the # nearby values x, y = i * h + 2, j * h + 2 x1 = 1 + x - math.floor(x) x2 = x - math.floor(x) x3 = math.floor(x) + 1 - x x4 = math.floor(x) + 2 - x y1 = 1 + y - math.floor(y) y2 = y - math.floor(y) y3 = math.floor(y) + 1 - y y4 = math.floor(y) + 2 - y # Considering all nearby 16 values mat_l = np.matrix([[u(x1, a), u(x2, a), u(x3, a), u(x4, a)]]) mat_m = np.matrix([[img[int(y-y1), int(x-x1), c], img[int(y-y2), int(x-x1), c], img[int(y+y3), int(x-x1), c], img[int(y+y4), int(x-x1), c]], [img[int(y-y1), int(x-x2), c], img[int(y-y2), int(x-x2), c], img[int(y+y3), int(x-x2), c], img[int(y+y4), int(x-x2), c]], [img[int(y-y1), int(x+x3), c], img[int(y-y2), int(x+x3), c], img[int(y+y3), int(x+x3), c], img[int(y+y4), int(x+x3), c]], [img[int(y-y1), int(x+x4), c], img[int(y-y2), int(x+x4), c], img[int(y+y3), int(x+x4), c], img[int(y+y4), int(x+x4), c]]]) mat_r = np.matrix( [[u(y1, a)], [u(y2, a)], [u(y3, a)], [u(y4, a)]]) # Here the dot function is used to get # the dot product of 2 matrices dst[j, i, c] = np.dot(np.dot(mat_l, mat_m), mat_r) # If there is an error message, it # directly goes to stderr sys.stderr.write('\\n') # Flushing the buffer sys.stderr.flush() return dst # Read image# You can put your input image over # here to run bicubic interpolation# The read function of Open CV is used# for this taskimg = cv2.imread('gfg.png') # Scale factorratio = 2# Coefficienta = -1/2 # Passing the input image in the # bicubic functiondst = bicubic(img, ratio, a)print('Completed!') # Saving the output imagecv2.imwrite('bicubic.png', dst)bicubicImg = cv2.imread('bicubic.png') # display shapes of both imagesprint('Original Image Shape:', img.shape)print('Generated Bicubic Image Shape:', bicubicImg.shape)", "e": 11974, "s": 7753, "text": null }, { "code": null, "e": 11982, "s": 11974, "text": "Output:" }, { "code": null, "e": 11996, "s": 11982, "text": "Output Image:" }, { "code": null, "e": 12008, "s": 11996, "text": "bicubic.png" }, { "code": null, "e": 12022, "s": 12008, "text": "Explanation: " }, { "code": null, "e": 12415, "s": 12022, "text": "Thus, from the above code, we can see that the input image has been resized using bicubic interpolation technique. The image given below has been compressed for publishing reasons. You can run the above code to see the implementation of increasing the size of the image smoothly using bicubic interpolation. The unknown pixel values here are filled by considering the 16 nearest known values." }, { "code": null, "e": 12432, "s": 12415, "text": "Image-Processing" }, { "code": null, "e": 12439, "s": 12432, "text": "Picked" }, { "code": null, "e": 12453, "s": 12439, "text": "Python-OpenCV" }, { "code": null, "e": 12460, "s": 12453, "text": "Python" }, { "code": null, "e": 12558, "s": 12460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12590, "s": 12558, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 12617, "s": 12590, "text": "Python Classes and Objects" }, { "code": null, "e": 12638, "s": 12617, "text": "Python OOPs Concepts" }, { "code": null, "e": 12661, "s": 12638, "text": "Introduction To PYTHON" }, { "code": null, "e": 12692, "s": 12661, "text": "Python | os.path.join() method" }, { "code": null, "e": 12748, "s": 12692, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 12790, "s": 12748, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 12832, "s": 12790, "text": "Check if element exists in list in Python" }, { "code": null, "e": 12871, "s": 12832, "text": "Python | Get unique values from a list" } ]
HTML <q> Tag
17 Mar, 2022 The <q> tag is a standard quotation tag and used for short quotation. The browser normally inserts a quotation mark around the quotation. For longer quotations, the <blockquote> tag must be used since it is a block-level element. The <q> tag requires a starting as well as end tag.Syntax: <q> Contents... </q> Attributes cite: It contains the value i.e URL which specify the source URL of the Quote.Below examples illustrate the <q> tag in HTML:Example 1: HTML <html> <body> <p> <!-- html q tag is used here --> <q>GeeksforGeeks</q> A computer science portal for geeks </p> </body></html> Output: Example 2(Use CSS in q tag): HTML <html> <head> <title>q tag</title> <style> q { color: #00cc00; font-style: italic; } </style> </head> <body> <p> <!-- html q tag is used here --> <q>GeeksforGeeks</q> A computer science portal for geeks </p> </body></html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari shubhamyadav4 ManasChhabra2 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? How to Upload Image into Database and Display it using PHP ? How to position a div at the bottom of its container using CSS? How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Mar, 2022" }, { "code": null, "e": 344, "s": 53, "text": "The <q> tag is a standard quotation tag and used for short quotation. The browser normally inserts a quotation mark around the quotation. For longer quotations, the <blockquote> tag must be used since it is a block-level element. The <q> tag requires a starting as well as end tag.Syntax: " }, { "code": null, "e": 365, "s": 344, "text": "<q> Contents... </q>" }, { "code": null, "e": 377, "s": 365, "text": "Attributes " }, { "code": null, "e": 514, "s": 377, "text": "cite: It contains the value i.e URL which specify the source URL of the Quote.Below examples illustrate the <q> tag in HTML:Example 1: " }, { "code": null, "e": 519, "s": 514, "text": "HTML" }, { "code": "<html> <body> <p> <!-- html q tag is used here --> <q>GeeksforGeeks</q> A computer science portal for geeks </p> </body></html> ", "e": 719, "s": 519, "text": null }, { "code": null, "e": 729, "s": 719, "text": "Output: " }, { "code": null, "e": 760, "s": 729, "text": "Example 2(Use CSS in q tag): " }, { "code": null, "e": 765, "s": 760, "text": "HTML" }, { "code": "<html> <head> <title>q tag</title> <style> q { color: #00cc00; font-style: italic; } </style> </head> <body> <p> <!-- html q tag is used here --> <q>GeeksforGeeks</q> A computer science portal for geeks </p> </body></html>", "e": 1097, "s": 765, "text": null }, { "code": null, "e": 1107, "s": 1097, "text": "Output: " }, { "code": null, "e": 1129, "s": 1107, "text": "Supported Browsers: " }, { "code": null, "e": 1143, "s": 1129, "text": "Google Chrome" }, { "code": null, "e": 1161, "s": 1143, "text": "Internet Explorer" }, { "code": null, "e": 1169, "s": 1161, "text": "Firefox" }, { "code": null, "e": 1175, "s": 1169, "text": "Opera" }, { "code": null, "e": 1182, "s": 1175, "text": "Safari" }, { "code": null, "e": 1198, "s": 1184, "text": "shubhamyadav4" }, { "code": null, "e": 1212, "s": 1198, "text": "ManasChhabra2" }, { "code": null, "e": 1222, "s": 1212, "text": "HTML-Tags" }, { "code": null, "e": 1227, "s": 1222, "text": "HTML" }, { "code": null, "e": 1232, "s": 1227, "text": "HTML" }, { "code": null, "e": 1330, "s": 1232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1378, "s": 1330, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1415, "s": 1378, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1465, "s": 1415, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1527, "s": 1465, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1587, "s": 1527, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 1640, "s": 1587, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1701, "s": 1640, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 1762, "s": 1701, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 1826, "s": 1762, "text": "How to position a div at the bottom of its container using CSS?" } ]
PHP | decbin( ) Function
09 Mar, 2018 While working with numbers, many times we need to convert the bases of number and one of the most frequent used conversion is decimal to binary conversion. PHP provides us with a built-in function, decbin() for this purpose.The decbin() function in PHP is used to return a string containing a binary representation of the given decimal number argument.decbin stands for decimal to binary. Syntax: string decbin(value) Parameters: This function accepts a single parameter value. It is the decimal number which you want to convert in binary representation. Return Value: It returns a string that represent the binary value of the decimal number passed to the function as argument. Examples: Input : decbin(12) Output : 1100 Input : decbin(26) Output : 11010 Input : decbin(2147483647) Output : 1111111111111111111111111111111 (31 1's) Below programs illustrate the decbin() function in PHP: Passing 12 as a parameter<?php echo decbin(12); ?> Output:1100 <?php echo decbin(12); ?> Output: 1100 Passing 26 as a parameter:<?php echo decbin(26); ?> Output:11010 <?php echo decbin(26); ?> Output: 11010 When the largest signed integer is passed as a parameter:<?php echo decbin(2147483647); ?> Output: 1111111111111111111111111111111 <?php echo decbin(2147483647); ?> Output: 1111111111111111111111111111111 Reference:http://php.net/manual/en/function.decbin.php PHP-function PHP-math PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2018" }, { "code": null, "e": 417, "s": 28, "text": "While working with numbers, many times we need to convert the bases of number and one of the most frequent used conversion is decimal to binary conversion. PHP provides us with a built-in function, decbin() for this purpose.The decbin() function in PHP is used to return a string containing a binary representation of the given decimal number argument.decbin stands for decimal to binary." }, { "code": null, "e": 425, "s": 417, "text": "Syntax:" }, { "code": null, "e": 446, "s": 425, "text": "string decbin(value)" }, { "code": null, "e": 583, "s": 446, "text": "Parameters: This function accepts a single parameter value. It is the decimal number which you want to convert in binary representation." }, { "code": null, "e": 707, "s": 583, "text": "Return Value: It returns a string that represent the binary value of the decimal number passed to the function as argument." }, { "code": null, "e": 717, "s": 707, "text": "Examples:" }, { "code": null, "e": 864, "s": 717, "text": "Input : decbin(12)\nOutput : 1100\n\nInput : decbin(26)\nOutput : 11010\n\nInput : decbin(2147483647)\nOutput : 1111111111111111111111111111111 (31 1's)\n" }, { "code": null, "e": 920, "s": 864, "text": "Below programs illustrate the decbin() function in PHP:" }, { "code": null, "e": 988, "s": 920, "text": "Passing 12 as a parameter<?php echo decbin(12); ?> Output:1100" }, { "code": "<?php echo decbin(12); ?> ", "e": 1020, "s": 988, "text": null }, { "code": null, "e": 1028, "s": 1020, "text": "Output:" }, { "code": null, "e": 1033, "s": 1028, "text": "1100" }, { "code": null, "e": 1102, "s": 1033, "text": "Passing 26 as a parameter:<?php echo decbin(26); ?> Output:11010" }, { "code": "<?php echo decbin(26); ?> ", "e": 1133, "s": 1102, "text": null }, { "code": null, "e": 1141, "s": 1133, "text": "Output:" }, { "code": null, "e": 1147, "s": 1141, "text": "11010" }, { "code": null, "e": 1287, "s": 1147, "text": "When the largest signed integer is passed as a parameter:<?php echo decbin(2147483647); ?> Output: 1111111111111111111111111111111 " }, { "code": "<?php echo decbin(2147483647); ?> ", "e": 1329, "s": 1287, "text": null }, { "code": null, "e": 1337, "s": 1329, "text": "Output:" }, { "code": null, "e": 1372, "s": 1337, "text": " 1111111111111111111111111111111 " }, { "code": null, "e": 1427, "s": 1372, "text": "Reference:http://php.net/manual/en/function.decbin.php" }, { "code": null, "e": 1440, "s": 1427, "text": "PHP-function" }, { "code": null, "e": 1449, "s": 1440, "text": "PHP-math" }, { "code": null, "e": 1453, "s": 1449, "text": "PHP" }, { "code": null, "e": 1470, "s": 1453, "text": "Web Technologies" }, { "code": null, "e": 1474, "s": 1470, "text": "PHP" } ]
Python | Convert Tuples to Dictionary
20 Aug, 2020 Conversions among datatypes are quite popular utility and hence having knowledge of it always proves out to be quite handy. The conversion of a list of tuples into a dictionary had been discussed earlier, sometimes, we might have a key and a value tuple to be converted to a dictionary. Let’s discuss certain ways in which this can be performed. Method #1 : Using Dictionary ComprehensionThis task can be performed using the dictionary comprehension in which we can iterate through the key and value tuple simultaneously using enumerate() and construct the desired dictionary. # Python3 code to demonstrate working of# Convert Tuples to Dictionary# Using Dictionary Comprehension# Note: For conversion of two tuples into a dictionary, we've to have the same length of tuples. Otherwise, we can not match all the key-value pairs # initializing tuplestest_tup1 = ('GFG', 'is', 'best')test_tup2 = (1, 2, 3) # printing original tuplesprint("The original key tuple is : " + str(test_tup1))print("The original value tuple is : " + str(test_tup2)) # Using Dictionary Comprehension# Convert Tuples to Dictionaryif len(test_tup1) == len(test_tup2): res = {test_tup1[i] : test_tup2[i] for i, _ in enumerate(test_tup2)} # printing result print("Dictionary constructed from tuples : " + str(res)) The original key tuple is : ('GFG', 'is', 'best') The original value tuple is : (1, 2, 3) Dictionary constructed from tuples : {'best': 3, 'is': 2, 'GFG': 1} Method #2 : Using zip() + dict()This is yet another method in which this task can be performed in which a combination of zip function and dict function achieve this task. The zip function is responsible for conversion of tuple to key-value pair with corresponding indices. The dict function performs the task of conversion to dictionary. # Python3 code to demonstrate working of# Convert Tuples to Dictionary# Using zip() + dict() # initializing tuplestest_tup1 = ('GFG', 'is', 'best')test_tup2 = (1, 2, 3) # printing original tuplesprint("The original key tuple is : " + str(test_tup1))print("The original value tuple is : " + str(test_tup2)) # Using zip() + dict()# Convert Tuples to Dictionaryif len(test_tup1) == len(test_tup2): res = dict(zip(test_tup1, test_tup2)) # printing result print("Dictionary constructed from tuples : " + str(res)) The original key tuple is : ('GFG', 'is', 'best') The original value tuple is : (1, 2, 3) Dictionary constructed from tuples : {'GFG': 1, 'is': 2, 'best': 3} parthsankhavara29 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Aug, 2020" }, { "code": null, "e": 400, "s": 54, "text": "Conversions among datatypes are quite popular utility and hence having knowledge of it always proves out to be quite handy. The conversion of a list of tuples into a dictionary had been discussed earlier, sometimes, we might have a key and a value tuple to be converted to a dictionary. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 631, "s": 400, "text": "Method #1 : Using Dictionary ComprehensionThis task can be performed using the dictionary comprehension in which we can iterate through the key and value tuple simultaneously using enumerate() and construct the desired dictionary." }, { "code": "# Python3 code to demonstrate working of# Convert Tuples to Dictionary# Using Dictionary Comprehension# Note: For conversion of two tuples into a dictionary, we've to have the same length of tuples. Otherwise, we can not match all the key-value pairs # initializing tuplestest_tup1 = ('GFG', 'is', 'best')test_tup2 = (1, 2, 3) # printing original tuplesprint(\"The original key tuple is : \" + str(test_tup1))print(\"The original value tuple is : \" + str(test_tup2)) # Using Dictionary Comprehension# Convert Tuples to Dictionaryif len(test_tup1) == len(test_tup2): res = {test_tup1[i] : test_tup2[i] for i, _ in enumerate(test_tup2)} # printing result print(\"Dictionary constructed from tuples : \" + str(res))", "e": 1346, "s": 631, "text": null }, { "code": null, "e": 1505, "s": 1346, "text": "The original key tuple is : ('GFG', 'is', 'best')\nThe original value tuple is : (1, 2, 3)\nDictionary constructed from tuples : {'best': 3, 'is': 2, 'GFG': 1}\n" }, { "code": null, "e": 1845, "s": 1507, "text": "Method #2 : Using zip() + dict()This is yet another method in which this task can be performed in which a combination of zip function and dict function achieve this task. The zip function is responsible for conversion of tuple to key-value pair with corresponding indices. The dict function performs the task of conversion to dictionary." }, { "code": "# Python3 code to demonstrate working of# Convert Tuples to Dictionary# Using zip() + dict() # initializing tuplestest_tup1 = ('GFG', 'is', 'best')test_tup2 = (1, 2, 3) # printing original tuplesprint(\"The original key tuple is : \" + str(test_tup1))print(\"The original value tuple is : \" + str(test_tup2)) # Using zip() + dict()# Convert Tuples to Dictionaryif len(test_tup1) == len(test_tup2): res = dict(zip(test_tup1, test_tup2)) # printing result print(\"Dictionary constructed from tuples : \" + str(res))", "e": 2361, "s": 1845, "text": null }, { "code": null, "e": 2520, "s": 2361, "text": "The original key tuple is : ('GFG', 'is', 'best')\nThe original value tuple is : (1, 2, 3)\nDictionary constructed from tuples : {'GFG': 1, 'is': 2, 'best': 3}\n" }, { "code": null, "e": 2538, "s": 2520, "text": "parthsankhavara29" }, { "code": null, "e": 2565, "s": 2538, "text": "Python dictionary-programs" }, { "code": null, "e": 2572, "s": 2565, "text": "Python" }, { "code": null, "e": 2588, "s": 2572, "text": "Python Programs" } ]
How to create a PHP form that submit to self ?
17 Jan, 2022 Forms can be submitted to the web page itself using PHP. The main purpose of submitting forms to self is for data validation. Data validation means checking for the required data to be entered in the form fields. PHP_SELF is a variable that returns the current script being executed. You can use this variable in the action field of the form. The action field of the form instructs where to submit the form data when the user presses the submit button. Most PHP pages maintain data validation on the same page as the form itself. An advantage of doing this is in case of a change in the website structure, the data validation code for the form, and the form remain together.Code Snippet: <form name=”form1′′ method=”post” action=”<?php echo htmlspecialchars($_SERVER[‘PHP_SELF’]); ?>” > Explanation: $_SERVER[‘PHP_SELF’]: The $_SERVER[“PHP_SELF”] is a super global variable that returns the filename of the currently executing script. It sends the submitted form data to the same page, instead of jumping on a different page. htmlspecialcharacters(): The htmlspecialchars() function converts special characters to HTML entities. It will replace HTML characters like with < and >. This prevents scripting attacks by attackers who exploit the code by inserting HTML or Javascript code in the form fields. Note: The $_SERVER[‘PHP_SELF’] can be easily exploited by hackers using cross-site scripting by inserting a ‘/’ in the URL and then a vulnerable script, but htmlspecialcharacters() is the solution, it converts the HTML characters from the site into harmless redundant code.Below example illustrate the above approach:Example: php <!DOCTYPE html><html> <head></head> <body> <?php // Defining variables $name = $email = $level = $review = ""; // Checking for a POST request if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $review = test_input($_POST["review"]); $level = test_input($_POST["level"]); } // Removing the redundant HTML characters if any exist. function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP Form Example: GFG Review</h2> <form method="post" action= "<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>"> Name: <input type="text" name="name"> <br> <br> E-mail: <input type="text" name="email"> <br> <br> Review For GFG: <textarea name="review" rows="5" cols="40"> </textarea> <br> <br> Satisfaction Level: <input type="radio" name="level" value="Bad">Bad <input type="radio" name="level" value="Average">Average <input type="radio" name="level" value="Good">Good <br> <br> <input type="submit" name="submit" value="Submit"> </form> <?php echo "<h2>Your Input:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $review; echo "<br>"; echo $level; ?></body> </html> Output: Before submitting: After submitting: You can also insert functions to check the values entered as per the requirements and display validation accordingly. PHP forms submitting to self find a lot of application in data validation and database input formatting. surindertarika1234 adnanirshad158 HTML-Misc PHP-Misc Picked HTML PHP PHP Programs Web Technologies Web technologies Questions Write From Home HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type Design a Tribute Page using HTML & CSS 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 ?
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2022" }, { "code": null, "e": 718, "s": 28, "text": "Forms can be submitted to the web page itself using PHP. The main purpose of submitting forms to self is for data validation. Data validation means checking for the required data to be entered in the form fields. PHP_SELF is a variable that returns the current script being executed. You can use this variable in the action field of the form. The action field of the form instructs where to submit the form data when the user presses the submit button. Most PHP pages maintain data validation on the same page as the form itself. An advantage of doing this is in case of a change in the website structure, the data validation code for the form, and the form remain together.Code Snippet: " }, { "code": null, "e": 819, "s": 718, "text": "<form name=”form1′′ method=”post” action=”<?php echo htmlspecialchars($_SERVER[‘PHP_SELF’]); ?>” > " }, { "code": null, "e": 834, "s": 819, "text": "Explanation: " }, { "code": null, "e": 1060, "s": 834, "text": "$_SERVER[‘PHP_SELF’]: The $_SERVER[“PHP_SELF”] is a super global variable that returns the filename of the currently executing script. It sends the submitted form data to the same page, instead of jumping on a different page." }, { "code": null, "e": 1337, "s": 1060, "text": "htmlspecialcharacters(): The htmlspecialchars() function converts special characters to HTML entities. It will replace HTML characters like with < and >. This prevents scripting attacks by attackers who exploit the code by inserting HTML or Javascript code in the form fields." }, { "code": null, "e": 1665, "s": 1337, "text": "Note: The $_SERVER[‘PHP_SELF’] can be easily exploited by hackers using cross-site scripting by inserting a ‘/’ in the URL and then a vulnerable script, but htmlspecialcharacters() is the solution, it converts the HTML characters from the site into harmless redundant code.Below example illustrate the above approach:Example: " }, { "code": null, "e": 1669, "s": 1665, "text": "php" }, { "code": "<!DOCTYPE html><html> <head></head> <body> <?php // Defining variables $name = $email = $level = $review = \"\"; // Checking for a POST request if ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") { $name = test_input($_POST[\"name\"]); $email = test_input($_POST[\"email\"]); $review = test_input($_POST[\"review\"]); $level = test_input($_POST[\"level\"]); } // Removing the redundant HTML characters if any exist. function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP Form Example: GFG Review</h2> <form method=\"post\" action= \"<?php echo htmlspecialchars($_SERVER[\" PHP_SELF \"]);?>\"> Name: <input type=\"text\" name=\"name\"> <br> <br> E-mail: <input type=\"text\" name=\"email\"> <br> <br> Review For GFG: <textarea name=\"review\" rows=\"5\" cols=\"40\"> </textarea> <br> <br> Satisfaction Level: <input type=\"radio\" name=\"level\" value=\"Bad\">Bad <input type=\"radio\" name=\"level\" value=\"Average\">Average <input type=\"radio\" name=\"level\" value=\"Good\">Good <br> <br> <input type=\"submit\" name=\"submit\" value=\"Submit\"> </form> <?php echo \"<h2>Your Input:</h2>\"; echo $name; echo \"<br>\"; echo $email; echo \"<br>\"; echo $review; echo \"<br>\"; echo $level; ?></body> </html>", "e": 3480, "s": 1669, "text": null }, { "code": null, "e": 3490, "s": 3480, "text": "Output: " }, { "code": null, "e": 3511, "s": 3490, "text": "Before submitting: " }, { "code": null, "e": 3531, "s": 3511, "text": "After submitting: " }, { "code": null, "e": 3755, "s": 3531, "text": "You can also insert functions to check the values entered as per the requirements and display validation accordingly. PHP forms submitting to self find a lot of application in data validation and database input formatting. " }, { "code": null, "e": 3774, "s": 3755, "text": "surindertarika1234" }, { "code": null, "e": 3789, "s": 3774, "text": "adnanirshad158" }, { "code": null, "e": 3799, "s": 3789, "text": "HTML-Misc" }, { "code": null, "e": 3808, "s": 3799, "text": "PHP-Misc" }, { "code": null, "e": 3815, "s": 3808, "text": "Picked" }, { "code": null, "e": 3820, "s": 3815, "text": "HTML" }, { "code": null, "e": 3824, "s": 3820, "text": "PHP" }, { "code": null, "e": 3837, "s": 3824, "text": "PHP Programs" }, { "code": null, "e": 3854, "s": 3837, "text": "Web Technologies" }, { "code": null, "e": 3881, "s": 3854, "text": "Web technologies Questions" }, { "code": null, "e": 3897, "s": 3881, "text": "Write From Home" }, { "code": null, "e": 3902, "s": 3897, "text": "HTML" }, { "code": null, "e": 3906, "s": 3902, "text": "PHP" }, { "code": null, "e": 4004, "s": 3906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4052, "s": 4004, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4076, "s": 4052, "text": "REST API (Introduction)" }, { "code": null, "e": 4113, "s": 4076, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 4141, "s": 4113, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 4180, "s": 4141, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4225, "s": 4180, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 4249, "s": 4225, "text": "PHP in_array() Function" }, { "code": null, "e": 4301, "s": 4249, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 4351, "s": 4301, "text": "How to Insert Form Data into Database using PHP ?" } ]
How to Parse Data From JSON into Python?
05 Jul, 2021 JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data from JSON and work with it. Before starting the details of parsing data, We should know about ‘json’ module in Python. It provides an API that is similar to pickle for converting in-memory objects in Python to a serialized representation as well as makes it easy to parse JSON data and files. Here are some ways to parse data from JSON using Python below: Python JSON to Dictionary: With the help of json.loads() function, we can parse JSON objects to dictionary. Python3 # importing json libraryimport json geek = '{"Name": "nightfury1", "Languages": ["Python", "C++", "PHP"]}'geek_dict = json.loads(geek) # printing all elements of dictionaryprint("Dictionary after parsing: ", geek_dict) # printing the values using keyprint("\nValues in Languages: ", geek_dict['Languages']) Output: Dictionary after parsing: {‘Name’: ‘nightfury1’, ‘Languages’: [‘Python’, ‘C++’, ‘PHP’]} Values in Languages: [‘Python’, ‘C++’, ‘PHP’] Python JSON to Ordered Dictionary: We have to use same json.loads() function for parsing the objects, but for getting in ordered, we have to add keyword ‘object_pairs_hook=OrderedDict‘ from collections module. Python3 import jsonfrom collections import OrderedDict #create Ordered Dictionary using keyword# 'object_pairs_hook=OrderDict'data = json.loads('{"GeeksforGeeks":1, "Gulshan": 2, "nightfury_1": 3, "Geek": 4}', object_pairs_hook=OrderedDict)print("Ordered Dictionary: ", data) Output: Ordered Dictionary: OrderedDict([(‘GeeksforGeeks’, 1), (‘Gulshan’, 2), (‘nightfury_1’, 3), (‘Geek’, 4)]) Parse using JSON file: With the help of json.load() method, we can parse JSON objects to dictionary format by opening the required JSON file. Python3 # importing json libraryimport json with open('data.json') as f: data = json.load(f) # printing data after loading the json fileprint(data) Output: {‘Name’: ‘nightfury1’, ‘Language’: [‘Python’, ‘C++’, ‘PHP’]} anikakapoor Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jul, 2021" }, { "code": null, "e": 355, "s": 28, "text": "JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data from JSON and work with it." }, { "code": null, "e": 683, "s": 355, "text": "Before starting the details of parsing data, We should know about ‘json’ module in Python. It provides an API that is similar to pickle for converting in-memory objects in Python to a serialized representation as well as makes it easy to parse JSON data and files. Here are some ways to parse data from JSON using Python below:" }, { "code": null, "e": 793, "s": 685, "text": "Python JSON to Dictionary: With the help of json.loads() function, we can parse JSON objects to dictionary." }, { "code": null, "e": 801, "s": 793, "text": "Python3" }, { "code": "# importing json libraryimport json geek = '{\"Name\": \"nightfury1\", \"Languages\": [\"Python\", \"C++\", \"PHP\"]}'geek_dict = json.loads(geek) # printing all elements of dictionaryprint(\"Dictionary after parsing: \", geek_dict) # printing the values using keyprint(\"\\nValues in Languages: \", geek_dict['Languages'])", "e": 1108, "s": 801, "text": null }, { "code": null, "e": 1116, "s": 1108, "text": "Output:" }, { "code": null, "e": 1205, "s": 1116, "text": "Dictionary after parsing: {‘Name’: ‘nightfury1’, ‘Languages’: [‘Python’, ‘C++’, ‘PHP’]}" }, { "code": null, "e": 1252, "s": 1205, "text": "Values in Languages: [‘Python’, ‘C++’, ‘PHP’]" }, { "code": null, "e": 1462, "s": 1252, "text": "Python JSON to Ordered Dictionary: We have to use same json.loads() function for parsing the objects, but for getting in ordered, we have to add keyword ‘object_pairs_hook=OrderedDict‘ from collections module." }, { "code": null, "e": 1470, "s": 1462, "text": "Python3" }, { "code": "import jsonfrom collections import OrderedDict #create Ordered Dictionary using keyword# 'object_pairs_hook=OrderDict'data = json.loads('{\"GeeksforGeeks\":1, \"Gulshan\": 2, \"nightfury_1\": 3, \"Geek\": 4}', object_pairs_hook=OrderedDict)print(\"Ordered Dictionary: \", data)", "e": 1756, "s": 1470, "text": null }, { "code": null, "e": 1764, "s": 1756, "text": "Output:" }, { "code": null, "e": 1870, "s": 1764, "text": "Ordered Dictionary: OrderedDict([(‘GeeksforGeeks’, 1), (‘Gulshan’, 2), (‘nightfury_1’, 3), (‘Geek’, 4)])" }, { "code": null, "e": 2012, "s": 1870, "text": "Parse using JSON file: With the help of json.load() method, we can parse JSON objects to dictionary format by opening the required JSON file." }, { "code": null, "e": 2020, "s": 2012, "text": "Python3" }, { "code": "# importing json libraryimport json with open('data.json') as f: data = json.load(f) # printing data after loading the json fileprint(data)", "e": 2161, "s": 2020, "text": null }, { "code": null, "e": 2169, "s": 2161, "text": "Output:" }, { "code": null, "e": 2230, "s": 2169, "text": "{‘Name’: ‘nightfury1’, ‘Language’: [‘Python’, ‘C++’, ‘PHP’]}" }, { "code": null, "e": 2242, "s": 2230, "text": "anikakapoor" }, { "code": null, "e": 2254, "s": 2242, "text": "Python-json" }, { "code": null, "e": 2261, "s": 2254, "text": "Python" }, { "code": null, "e": 2359, "s": 2261, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2391, "s": 2359, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2418, "s": 2391, "text": "Python Classes and Objects" }, { "code": null, "e": 2439, "s": 2418, "text": "Python OOPs Concepts" }, { "code": null, "e": 2462, "s": 2439, "text": "Introduction To PYTHON" }, { "code": null, "e": 2518, "s": 2462, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2549, "s": 2518, "text": "Python | os.path.join() method" }, { "code": null, "e": 2591, "s": 2549, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2633, "s": 2591, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2672, "s": 2633, "text": "Python | Get unique values from a list" } ]
Struts 2 - Actions
Actions are the core of the Struts2 framework, as they are for any MVC (Model View Controller) framework. Each URL is mapped to a specific action, which provides the processing logic which is necessary to service the request from the user. But the action also serves in two other important capacities. Firstly, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result. Secondly, the action must assist the framework in determining which result should render the view that will be returned in the response to the request. The only requirement for actions in Struts2 is that there must be one noargument method that returns either a String or Result object and must be a POJO. If the no-argument method is not specified, the default behavior is to use the execute() method. Optionally you can extend the ActionSupport class which implements six interfaces including Action interface. The Action interface is as follows − public interface Action { public static final String SUCCESS = "success"; public static final String NONE = "none"; public static final String ERROR = "error"; public static final String INPUT = "input"; public static final String LOGIN = "login"; public String execute() throws Exception; } Let us take a look at the action method in the Hello World example − package com.tutorialspoint.struts2; public class HelloWorldAction { private String name; public String execute() throws Exception { return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } } To illustrate the point that the action method controls the view, let us make the following change to the execute method and extend the class ActionSupport as follows − package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport { private String name; public String execute() throws Exception { if ("SECRET".equals(name)) { return SUCCESS; } else { return ERROR; } } public String getName() { return name; } public void setName(String name) { this.name = name; } } In this example, we have some logic in the execute method to look at the name attribute. If the attribute equals to the string "SECRET", we return SUCCESS as the result otherwise we return ERROR as the result. Because we have extended ActionSupport, so we can use String constants SUCCESS and ERROR. Now, let us modify our struts.xml file as follows − <?xml version = "1.0" Encoding = "UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name = "struts.devMode" value = "true" /> <package name = "helloworld" extends = "struts-default"> <action name = "hello" class = "com.tutorialspoint.struts2.HelloWorldAction" method = "execute"> <result name = "success">/HelloWorld.jsp</result> <result name = "error">/AccessDenied.jsp</result> </action> </package> </struts> Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. To do this, right click on the WebContent folder in the project explorer and select New >JSP File. This file will be called in case return result is SUCCESS which is a String constant "success" as defined in Action interface − <%@ page contentType = "text/html; charset = UTF-8" %> <%@ taglib prefix = "s" uri = "/struts-tags" %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value = "name"/> </body> </html> Following is the file which will be invoked by the framework in case action result is ERROR which is equal to String constant "error". Following is the content of AccessDenied.jsp <%@ page contentType = "text/html; charset = UTF-8" %> <%@ taglib prefix = "s" uri = "/struts-tags" %> <html> <head> <title>Access Denied</title> </head> <body> You are not authorized to view this page. </body> </html> We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where the user can click to tell the Struts 2 framework to call the executemethod of the HelloWorldAction class and render the HelloWorld.jsp view. <%@ page language = "java" contentType = "text/html; charset = ISO-8859-1" pageEncoding = "ISO-8859-1"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action = "hello"> <label for = "name">Please enter your name</label><br/> <input type = "text" name = "name"/> <input type = "submit" value = "Say Hello"/> </form> </body> </html> That's it, there is no change required for web.xml file, so let us use the same web.xml which we had created in Examples chapter. Now, we are ready to run our Hello World application using Struts 2 framework. Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you following screen − Let us enter a word as "SECRET" and you should see the following page − Now enter any word other than "SECRET" and you should see the following page − You will frequently define more than one actions to handle different requests and to provide different URLs to the users, accordingly you will define different classes as defined below − package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; class MyAction extends ActionSupport { public static String GOOD = SUCCESS; public static String BAD = ERROR; } public class HelloWorld extends ActionSupport { ... public String execute() { if ("SECRET".equals(name)) return MyAction.GOOD; return MyAction.BAD; } ... } public class SomeOtherClass extends ActionSupport { ... public String execute() { return MyAction.GOOD; } ... } You will configure these actions in struts.xml file as follows − <?xml version = "1.0" Encoding = "UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name = "struts.devMode" value = "true" /> <package name = "helloworld" extends = "struts-default"> <action name = "hello" class = "com.tutorialspoint.struts2.HelloWorld" method = "execute"> <result name = "success">/HelloWorld.jsp</result> <result name = "error">/AccessDenied.jsp</result> </action> <action name = "something" class = "com.tutorialspoint.struts2.SomeOtherClass" method = "execute"> <result name = "success">/Something.jsp</result> <result name = "error">/AccessDenied.jsp</result> </action> </package> </struts> As you can see in the above hypothetical example, the action results SUCCESS and ERROR’s are duplicated. To get around this issue, it is suggested that you create a class which contains the result outcomes.
[ { "code": null, "e": 2620, "s": 2380, "text": "Actions are the core of the Struts2 framework, as they are for any MVC (Model View Controller) framework. Each URL is mapped to a specific action, which provides the processing logic which is necessary to service the request from the user." }, { "code": null, "e": 2983, "s": 2620, "text": "But the action also serves in two other important capacities. Firstly, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result. Secondly, the action must assist the framework in determining which result should render the view that will be returned in the response to the request." }, { "code": null, "e": 3234, "s": 2983, "text": "The only requirement for actions in Struts2 is that there must be one noargument method that returns either a String or Result object and must be a POJO. If the no-argument method is not specified, the default behavior is to use the execute() method." }, { "code": null, "e": 3381, "s": 3234, "text": "Optionally you can extend the ActionSupport class which implements six interfaces including Action interface. The Action interface is as follows −" }, { "code": null, "e": 3691, "s": 3381, "text": "public interface Action {\n public static final String SUCCESS = \"success\";\n public static final String NONE = \"none\";\n public static final String ERROR = \"error\";\n public static final String INPUT = \"input\";\n public static final String LOGIN = \"login\";\n public String execute() throws Exception;\n}" }, { "code": null, "e": 3760, "s": 3691, "text": "Let us take a look at the action method in the Hello World example −" }, { "code": null, "e": 4056, "s": 3760, "text": "package com.tutorialspoint.struts2;\n\npublic class HelloWorldAction {\n private String name;\n\n public String execute() throws Exception {\n return \"success\";\n }\n \n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 4225, "s": 4056, "text": "To illustrate the point that the action method controls the view, let us make the following change to the execute method and extend the class ActionSupport as follows −" }, { "code": null, "e": 4674, "s": 4225, "text": "package com.tutorialspoint.struts2;\n\nimport com.opensymphony.xwork2.ActionSupport;\n\npublic class HelloWorldAction extends ActionSupport {\n private String name;\n\n public String execute() throws Exception {\n if (\"SECRET\".equals(name)) {\n return SUCCESS;\n } else {\n return ERROR; \n }\n }\n \n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 5026, "s": 4674, "text": "In this example, we have some logic in the execute method to look at the name attribute. If the attribute equals to the string \"SECRET\", we return SUCCESS as the result otherwise we return ERROR as the result. Because we have extended ActionSupport, so we can use String constants SUCCESS and ERROR. Now, let us modify our struts.xml file as follows −" }, { "code": null, "e": 5618, "s": 5026, "text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE struts PUBLIC\n \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n\n<struts>\n <constant name = \"struts.devMode\" value = \"true\" />\n <package name = \"helloworld\" extends = \"struts-default\">\n <action name = \"hello\" \n class = \"com.tutorialspoint.struts2.HelloWorldAction\"\n method = \"execute\">\n <result name = \"success\">/HelloWorld.jsp</result>\n <result name = \"error\">/AccessDenied.jsp</result>\n </action>\n </package>\n</struts>" }, { "code": null, "e": 5943, "s": 5618, "text": "Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. To do this, right click on the WebContent folder in the project explorer and select New >JSP File. This file will be called in case return result is SUCCESS which is a String constant \"success\" as defined in Action interface −" }, { "code": null, "e": 6189, "s": 5943, "text": "<%@ page contentType = \"text/html; charset = UTF-8\" %>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\" %>\n\n<html>\n <head>\n <title>Hello World</title>\n </head>\n \n <body>\n Hello World, <s:property value = \"name\"/>\n </body>\n</html>" }, { "code": null, "e": 6369, "s": 6189, "text": "Following is the file which will be invoked by the framework in case action result is ERROR which is equal to String constant \"error\". Following is the content of AccessDenied.jsp" }, { "code": null, "e": 6619, "s": 6369, "text": "<%@ page contentType = \"text/html; charset = UTF-8\" %>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\" %>\n\n<html> \n <head>\n <title>Access Denied</title>\n </head>\n \n <body>\n You are not authorized to view this page.\n </body>\n</html>" }, { "code": null, "e": 6873, "s": 6619, "text": "We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where the user can click to tell the Struts 2 framework to call the executemethod of the HelloWorldAction class and render the HelloWorld.jsp view." }, { "code": null, "e": 7484, "s": 6873, "text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n pageEncoding = \"ISO-8859-1\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html> \n <head>\n <title>Hello World</title>\n </head>\n \n <body>\n <h1>Hello World From Struts2</h1>\n <form action = \"hello\">\n <label for = \"name\">Please enter your name</label><br/>\n <input type = \"text\" name = \"name\"/>\n <input type = \"submit\" value = \"Say Hello\"/>\n </form>\n </body>\n</html>" }, { "code": null, "e": 7693, "s": 7484, "text": "That's it, there is no change required for web.xml file, so let us use the same web.xml which we had created in Examples chapter. Now, we are ready to run our Hello World application using Struts 2 framework." }, { "code": null, "e": 7971, "s": 7693, "text": "Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you following screen −" }, { "code": null, "e": 8043, "s": 7971, "text": "Let us enter a word as \"SECRET\" and you should see the following page −" }, { "code": null, "e": 8122, "s": 8043, "text": "Now enter any word other than \"SECRET\" and you should see the following page −" }, { "code": null, "e": 8309, "s": 8122, "text": "You will frequently define more than one actions to handle different requests and to provide different URLs to the users, accordingly you will define different classes as defined below −" }, { "code": null, "e": 8822, "s": 8309, "text": "package com.tutorialspoint.struts2;\nimport com.opensymphony.xwork2.ActionSupport;\n\nclass MyAction extends ActionSupport {\n public static String GOOD = SUCCESS;\n public static String BAD = ERROR;\n}\n\npublic class HelloWorld extends ActionSupport {\n ...\n public String execute() {\n if (\"SECRET\".equals(name)) return MyAction.GOOD;\n return MyAction.BAD;\n }\n ...\n}\n\npublic class SomeOtherClass extends ActionSupport {\n ...\n public String execute() {\n return MyAction.GOOD;\n }\n ...\n}" }, { "code": null, "e": 8887, "s": 8822, "text": "You will configure these actions in struts.xml file as follows −" }, { "code": null, "e": 9743, "s": 8887, "text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE struts PUBLIC\n \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n\n<struts>\n <constant name = \"struts.devMode\" value = \"true\" />\n \n <package name = \"helloworld\" extends = \"struts-default\">\n <action name = \"hello\" \n class = \"com.tutorialspoint.struts2.HelloWorld\" \n method = \"execute\">\n <result name = \"success\">/HelloWorld.jsp</result>\n <result name = \"error\">/AccessDenied.jsp</result>\n </action>\n \n <action name = \"something\" \n class = \"com.tutorialspoint.struts2.SomeOtherClass\" \n method = \"execute\">\n <result name = \"success\">/Something.jsp</result>\n <result name = \"error\">/AccessDenied.jsp</result>\n </action>\n </package>\n</struts>" }, { "code": null, "e": 9848, "s": 9743, "text": "As you can see in the above hypothetical example, the action results SUCCESS and ERROR’s are duplicated." } ]
Matplotlib.axes.Axes.hlines() in Python
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.hlines() function in axes module of matplotlib library is used to Plot vertical lines at each y from xmin to xmax. Syntax: Axes.hlines(self, y, xmin, xmax, colors=’k’, linestyles=’solid’, label=”, *, data=None, **kwargs) Parameters: This method accept the following parameters that are described below: y: This parameter is the sequence of y-indexes where to plot the lines. xmin, xmax: These parameter contains an array.And they represents the beginning and end of each line. colors: This parameter is an optional parameter. And it is the color of the lines with default value k. linetsyle: This parameter is also an optional parameter. And it is used to represent the linestyle{‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}. label: This parameter is also an optional parameter.It is the label of the plot. Returns: This returns the LineCollection. Below examples illustrate the matplotlib.axes.Axes.hlines() function in matplotlib.axes: Example #1: # Implementation of matplotlib function import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.hlines([1, 3, 5], -3, 5, color ="green")ax.set_title('matplotlib.axes.Axes.hlines Example') plt.show() Output: Example #2: # Implementation of matplotlib function import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt t = np.arange(0.0, 5.0, 0.1)s = np.exp(-t) + np.cos(3 * np.pi * t) + np.sin(np.pi * t)nse = np.random.normal(0.0, 0.8, t.shape) * s fig, ax = plt.subplots() ax.hlines(t, [0], s)ax.set_xlabel('time (s)')ax.hlines([1, 3, 5], -3, 5, color ="lightgreen")ax.set_title('matplotlib.axes.Axes.hlines 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": "\n13 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 452, "s": 328, "text": "The Axes.hlines() function in axes module of matplotlib library is used to Plot vertical lines at each y from xmin to xmax." }, { "code": null, "e": 558, "s": 452, "text": "Syntax: Axes.hlines(self, y, xmin, xmax, colors=’k’, linestyles=’solid’, label=”, *, data=None, **kwargs)" }, { "code": null, "e": 640, "s": 558, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 712, "s": 640, "text": "y: This parameter is the sequence of y-indexes where to plot the lines." }, { "code": null, "e": 814, "s": 712, "text": "xmin, xmax: These parameter contains an array.And they represents the beginning and end of each line." }, { "code": null, "e": 918, "s": 814, "text": "colors: This parameter is an optional parameter. And it is the color of the lines with default value k." }, { "code": null, "e": 1058, "s": 918, "text": "linetsyle: This parameter is also an optional parameter. And it is used to represent the linestyle{‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}." }, { "code": null, "e": 1139, "s": 1058, "text": "label: This parameter is also an optional parameter.It is the label of the plot." }, { "code": null, "e": 1181, "s": 1139, "text": "Returns: This returns the LineCollection." }, { "code": null, "e": 1270, "s": 1181, "text": "Below examples illustrate the matplotlib.axes.Axes.hlines() function in matplotlib.axes:" }, { "code": null, "e": 1282, "s": 1270, "text": "Example #1:" }, { "code": "# Implementation of matplotlib function import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.hlines([1, 3, 5], -3, 5, color =\"green\")ax.set_title('matplotlib.axes.Axes.hlines Example') plt.show()", "e": 1541, "s": 1282, "text": null }, { "code": null, "e": 1549, "s": 1541, "text": "Output:" }, { "code": null, "e": 1561, "s": 1549, "text": "Example #2:" }, { "code": "# Implementation of matplotlib function import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt t = np.arange(0.0, 5.0, 0.1)s = np.exp(-t) + np.cos(3 * np.pi * t) + np.sin(np.pi * t)nse = np.random.normal(0.0, 0.8, t.shape) * s fig, ax = plt.subplots() ax.hlines(t, [0], s)ax.set_xlabel('time (s)')ax.hlines([1, 3, 5], -3, 5, color =\"lightgreen\")ax.set_title('matplotlib.axes.Axes.hlines Example') plt.show()", "e": 2005, "s": 1561, "text": null }, { "code": null, "e": 2013, "s": 2005, "text": "Output:" }, { "code": null, "e": 2031, "s": 2013, "text": "Python-matplotlib" }, { "code": null, "e": 2038, "s": 2031, "text": "Python" } ]
gpasswd command in Linux with examples
20 May, 2019 gpasswd command is used to administer the /etc/group and /etc/gshadow. As every group in Linux has administrators, members, and a password. It is an inherent security problem as more than one person is permitted to know the password. However, groups can perform co-operation between different users. This command assigns a user to a group with some security criteria. This command is called by a group administrator with a group name only which prompts for the new password of the group. System administrators can use the -A option to define group administrator(s) and -M option to define members. They have all rights of the group administrators and members. Syntax: gpasswd [option] group Options: Here only -A and -M options can be combined. -a, –add : This option is used to add a user to the named group. -d, –delete : It is used to remove a user from the named group. -r, –remove-password : It is used to remove the password from the named group. -R, –restrict : This option will restrict the access to the named group. -A, –administrators : Set the list of administrative users. -M, –members : It set the list of group members. -h, –help : It displays the help message and exit.$ sudo gpasswd -h $ sudo gpasswd -h Example: Creating a group and adding a user to it. After that deleting the user. Adding a group named as geeks.$ sudo groupadd geeks $ sudo groupadd geeks To display the created group with their id you can use:$cat /etc/group $cat /etc/group Now the group geeks is added so now execute command under to add the user to group geeks:$ sudo gpasswd -a umang geeks $ sudo gpasswd -a umang geeks Deleting the created user from group geeks.$ sudo gpasswd -d umang geeks $ sudo gpasswd -d umang geeks linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples 'crontab' in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples Docker - COPY Instruction UDP Server-Client implementation in C scp command in Linux with Examples diff command in Linux with examples echo command in Linux with Examples Cat command in Linux with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2019" }, { "code": null, "e": 688, "s": 28, "text": "gpasswd command is used to administer the /etc/group and /etc/gshadow. As every group in Linux has administrators, members, and a password. It is an inherent security problem as more than one person is permitted to know the password. However, groups can perform co-operation between different users. This command assigns a user to a group with some security criteria. This command is called by a group administrator with a group name only which prompts for the new password of the group. System administrators can use the -A option to define group administrator(s) and -M option to define members. They have all rights of the group administrators and members." }, { "code": null, "e": 696, "s": 688, "text": "Syntax:" }, { "code": null, "e": 719, "s": 696, "text": "gpasswd [option] group" }, { "code": null, "e": 773, "s": 719, "text": "Options: Here only -A and -M options can be combined." }, { "code": null, "e": 838, "s": 773, "text": "-a, –add : This option is used to add a user to the named group." }, { "code": null, "e": 902, "s": 838, "text": "-d, –delete : It is used to remove a user from the named group." }, { "code": null, "e": 981, "s": 902, "text": "-r, –remove-password : It is used to remove the password from the named group." }, { "code": null, "e": 1054, "s": 981, "text": "-R, –restrict : This option will restrict the access to the named group." }, { "code": null, "e": 1114, "s": 1054, "text": "-A, –administrators : Set the list of administrative users." }, { "code": null, "e": 1163, "s": 1114, "text": "-M, –members : It set the list of group members." }, { "code": null, "e": 1232, "s": 1163, "text": "-h, –help : It displays the help message and exit.$ sudo gpasswd -h " }, { "code": null, "e": 1251, "s": 1232, "text": "$ sudo gpasswd -h " }, { "code": null, "e": 1332, "s": 1251, "text": "Example: Creating a group and adding a user to it. After that deleting the user." }, { "code": null, "e": 1384, "s": 1332, "text": "Adding a group named as geeks.$ sudo groupadd geeks" }, { "code": null, "e": 1406, "s": 1384, "text": "$ sudo groupadd geeks" }, { "code": null, "e": 1477, "s": 1406, "text": "To display the created group with their id you can use:$cat /etc/group" }, { "code": null, "e": 1493, "s": 1477, "text": "$cat /etc/group" }, { "code": null, "e": 1612, "s": 1493, "text": "Now the group geeks is added so now execute command under to add the user to group geeks:$ sudo gpasswd -a umang geeks" }, { "code": null, "e": 1642, "s": 1612, "text": "$ sudo gpasswd -a umang geeks" }, { "code": null, "e": 1715, "s": 1642, "text": "Deleting the created user from group geeks.$ sudo gpasswd -d umang geeks" }, { "code": null, "e": 1745, "s": 1715, "text": "$ sudo gpasswd -d umang geeks" }, { "code": null, "e": 1759, "s": 1745, "text": "linux-command" }, { "code": null, "e": 1781, "s": 1759, "text": "Linux-system-commands" }, { "code": null, "e": 1788, "s": 1781, "text": "Picked" }, { "code": null, "e": 1799, "s": 1788, "text": "Linux-Unix" }, { "code": null, "e": 1897, "s": 1799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1932, "s": 1897, "text": "tar command in Linux with examples" }, { "code": null, "e": 1965, "s": 1932, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 2003, "s": 1965, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2039, "s": 2003, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2065, "s": 2039, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2103, "s": 2065, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 2138, "s": 2103, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2174, "s": 2138, "text": "diff command in Linux with examples" }, { "code": null, "e": 2210, "s": 2174, "text": "echo command in Linux with Examples" } ]
Python – Split String on vowels
01 Jun, 2021 Given a String, perform split on vowels. Input : test_str = ‘GFGaBst’ Output : [‘GFG’, ‘Bst’] Explanation : a is vowel and split happens on that.Input : test_str = ‘GFGaBstuforigeeks’ Output : [‘GFG’, ‘Bst’, ‘for’, ‘geeks’] Explanation : a, u, i are vowels and split happens on that. Method : Using regex() + split() In this, we use regex split() which accepts multiple characters to perform split, passing list of vowels, performs split operation over string. Python3 # Python3 code to demonstrate working of# Split String on vowels# Using split() + regeximport re # initializing stringstest_str = 'GFGaBste4oCS' # printing original stringprint("The original string is : " + str(test_str)) # splitting on vowels# constructing vowels list# and separating using | operatorres = re.split('a|e|i|o|u', test_str) # printing resultprint("The splitted string : " + str(res)) The original string is : GFGaBste4oCS The splitted string : ['GFG', 'Bst', '4', 'CS'] gabaa406 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Stack in Python Python Dictionary Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Iterate over characters of a string in Python Python | Convert set into a list
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2021" }, { "code": null, "e": 70, "s": 28, "text": "Given a String, perform split on vowels. " }, { "code": null, "e": 315, "s": 70, "text": "Input : test_str = ‘GFGaBst’ Output : [‘GFG’, ‘Bst’] Explanation : a is vowel and split happens on that.Input : test_str = ‘GFGaBstuforigeeks’ Output : [‘GFG’, ‘Bst’, ‘for’, ‘geeks’] Explanation : a, u, i are vowels and split happens on that. " }, { "code": null, "e": 348, "s": 315, "text": "Method : Using regex() + split()" }, { "code": null, "e": 492, "s": 348, "text": "In this, we use regex split() which accepts multiple characters to perform split, passing list of vowels, performs split operation over string." }, { "code": null, "e": 500, "s": 492, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Split String on vowels# Using split() + regeximport re # initializing stringstest_str = 'GFGaBste4oCS' # printing original stringprint(\"The original string is : \" + str(test_str)) # splitting on vowels# constructing vowels list# and separating using | operatorres = re.split('a|e|i|o|u', test_str) # printing resultprint(\"The splitted string : \" + str(res))", "e": 900, "s": 500, "text": null }, { "code": null, "e": 986, "s": 900, "text": "The original string is : GFGaBste4oCS\nThe splitted string : ['GFG', 'Bst', '4', 'CS']" }, { "code": null, "e": 995, "s": 986, "text": "gabaa406" }, { "code": null, "e": 1018, "s": 995, "text": "Python string-programs" }, { "code": null, "e": 1025, "s": 1018, "text": "Python" }, { "code": null, "e": 1041, "s": 1025, "text": "Python Programs" }, { "code": null, "e": 1139, "s": 1041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1189, "s": 1139, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 1211, "s": 1189, "text": "Enumerate() in Python" }, { "code": null, "e": 1227, "s": 1211, "text": "Deque in Python" }, { "code": null, "e": 1243, "s": 1227, "text": "Stack in Python" }, { "code": null, "e": 1261, "s": 1243, "text": "Python Dictionary" }, { "code": null, "e": 1283, "s": 1261, "text": "Defaultdict in Python" }, { "code": null, "e": 1329, "s": 1283, "text": "Python | Split string into list of characters" }, { "code": null, "e": 1368, "s": 1329, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1414, "s": 1368, "text": "Iterate over characters of a string in Python" } ]
Python Web Scraping Tutorial
16 Jun, 2022 Let’s suppose you want to get some information from a website? Let’s say an article from the geeksforgeeks website or some news article, what will you do? The first thing that may come in your mind is to copy and paste the information into your local media. But what if you want a large amount of data on a daily basis and as quickly as possible. In such situations, copy and paste will not work and that’s where you’ll need web scraping. In this article, we will discuss how to perform web scraping using the requests library and beautifulsoup library in Python. Requests library is used for making HTTP requests to a specific URL and returns the response. Python requests provide inbuilt functionalities for managing both the request and response. Requests installation depends on the type of operating system, the basic command anywhere would be to open a command terminal and run, pip install requests Python requests module has several built-in methods to make HTTP requests to specified URI using GET, POST, PUT, PATCH, or HEAD requests. A HTTP request is meant to either retrieve data from a specified URI or to push data to a server. It works as a request-response protocol between a client and a server. Here we will be using the GET request. GET method is used to retrieve information from the given server using a given URI. The GET method sends the encoded user information appended to the page request. Python3 import requests # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # check status code for response received# success code - 200print(r) # print content of requestprint(r.content) Output: When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being – get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the status code from the headers itself, and one can check if the request was processed successfully or not. Response objects can be used to imply lots of features, methods, and functionalities. Python3 import requests # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # print request objectprint(r.url) # print status codeprint(r.status_code) Output: https://www.geeksforgeeks.org/python-programming-language/ 200 For more information, refer to our Python Requests Tutorial. BeautifulSoup is used extract information from the HTML and XML files. It provides a parse tree and the functions to navigate, search or modify this parse tree. To install Beautifulsoup on Windows, Linux, or any operating system, one would need pip package. To check how to install pip on your operating system, check out – PIP Installation – Windows || Linux. Now run the below command in the terminal. pip install beautifulsoup4 Before getting out any information from the HTML of the page, we must understand the structure of the page. This is needed to be done in order to select the desired data from the entire page. We can do this by right-clicking on the page we want to scrape and select inspect element. After clicking the inspect button the Developer Tools of the browser gets open. Now almost all the browsers come with the developers tools installed, and we will be using Chrome for this tutorial. The developer’s tools allow seeing the site’s Document Object Model (DOM). If you don’t know about DOM then don’t worry just consider the text displayed as the HTML structure of the page. After getting the HTML of the page let’s see how to parse this raw HTML code into some useful information. First of all, we will create a BeautifulSoup object by specifying the parser we want to use. Note: BeautifulSoup library is built on top of the HTML parsing libraries like html5lib, lxml, html.parser, etc. So BeautifulSoup object and specify the parser library can be created at the same time. Python3 import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # check status code for response received# success code - 200print(r) # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser')print(soup.prettify()) Output: This information is still not useful to us, let’s see another example to make some clear picture from this. Let’s try to extract the title of the page. Python3 import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') # Getting the title tagprint(soup.title) # Getting the name of the tagprint(soup.title.name) # Getting the name of parent tagprint(soup.title.parent.name) # use the child attribute to get# the name of the child tag Output: <title>Python Programming Language - GeeksforGeeks</title> title html Now, we would like to extract some useful data from the HTML content. The soup object contains all the data in the nested structure which could be programmatically extracted. The website we want to scrape contains a lot of text so now let’s scrape all those content. First, let’s inspect the webpage we want to scrape. In the above image, we can see that all the content of the page is under the div with class entry-content. We will use the find class. This class will find the given tag with the given attribute. In our case, it will find all the div having class as entry-content. We have got all the content from the site but you can see that all the images and links are also scraped. So our next task is to find only the content from the above-parsed HTML. On again inspecting the HTML of our website – We can see that the content of the page is under the <p> tag. Now we have to find all the p tags present in this class. We can use the find_all class of the BeautifulSoup. Python3 import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') s = soup.find('div', class_='entry-content')content = s.find_all('p') print(content) Output: In the above example, we have found the elements by the class name but let’s see how to find elements by id. Now for this task let’s scrape the content of the leftbar of the page. The first step is to inspect the page and see the leftbar falls under which tag. The above image shows that the leftbar falls under the <div> tag with id as main. Now lets’s get the HTML content under this tag. Now let’s inspect more of the page get the content of the leftbar. We can see that the list in the leftbar is under the <ul> tag with the class as leftBarList and our task is to find all the li under this ul. Python3 import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') # Finding by ids = soup.find('div', id= 'main') # Getting the leftbarleftbar = s.find('ul', class_='leftBarList') # All the li under the above ulcontent = leftbar.find_all('li') print(content) Output: In the above examples, you must have seen that while scraping the data the tags also get scraped but what if we want only the text without any tags. Don’t worry we will discuss the same in this section. We will be using the text property. It only prints the text from the tag. We will be using the above example and will remove all the tags from them. Python3 import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') s = soup.find('div', class_='entry-content') lines = s.find_all('p') for line in lines: print(line.text) Output: Python3 import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') # Finding by ids = soup.find('div', id= 'main') # Getting the leftbarleftbar = s.find('ul', class_='leftBarList') # All the li under the above ullines = leftbar.find_all('li') for line in lines: print(line.text) Output: Till now we have seen how to extract text, let’s now see how to extract the links from the page. Python3 import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') # find all the anchor tags with "href"for link in soup.find_all('a'): print(link.get('href')) Output: On again inspecting the page, we can see that images lie inside the img tag and the link of that image is inside the src attribute. See the below image – Python3 import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') images_list = [] images = soup.select('img')for image in images: src = image.get('src') alt = image.get('alt') images_list.append({"src": src, "alt": alt}) for image in images_list: print(image) Output: Now, there may arise various instances where you may want to get data from multiple pages from the same website or multiple different URLs as well, and manually writing code for each webpage is a time-consuming and tedious task. Plus, it defines all basic principles of automation. Duh! To solve this exact problem, we will see two main techniques that will help us extract data from multiple webpages: The same website Different website URLs page numbers at the bottom of the GeeksforGeeks website Most websites have pages labeled from 1 to N. This makes it really simple for us to loop through these pages and extract data from them as these pages have similar structures. For example: page numbers at the bottom of the GeeksforGeeks website Here, we can see the page details at the end of the URL. Using this information we can easily create a for loop iterating over as many pages as we want (by putting page/(i)/ in the URL string and iterating “i” till N) and scrape all the useful data from them. The following code will give you more clarity over how to scrape data by using a For Loop in Python. Python3 import requestsfrom bs4 import BeautifulSoup as bs URL = 'https://www.geeksforgeeks.org/page/1/' req = requests.get(URL)soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs = {'class','head'}) print(titles[4].text) Output: 7 Most Common Time Wastes During Software Development Now, using the above code, we can get the titles of all the articles by just sandwiching those lines with a loop. Python3 import requestsfrom bs4 import BeautifulSoup as bs URL = 'https://www.geeksforgeeks.org/page/' for page in range(1, 10): req = requests.get(URL + str(page) + '/') soup = bs(req.text, 'html.parser') titles = soup.find_all('div', attrs={'class', 'head'}) for i in range(4, 19): if page > 1: print(f"{(i-3)+page*15}" + titles[i].text) else: print(f"{i-3}" + titles[i].text) Output: The above technique is absolutely wonderful, but what if you need to scrape different pages, and you don’t know their page numbers? You’ll need to scrape those different URLs one by one and manually code a script for every such webpage. Instead, you could just make a list of these URLs and loop through them. By simply iterating the items in the list i.e. the URLs, we will be able to extract the titles of those pages without having to write code for each page. Here’s an example code of how you can do it. Python3 import requestsfrom bs4 import BeautifulSoup as bs URL = ['https://www.geeksforgeeks.org','https://www.geeksforgeeks.org/page/10/'] for url in range(0,2): req = requests.get(URL[url]) soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs={'class','head'}) for i in range(4, 19): if url+1 > 1: print(f"{(i - 3) + url * 15}" + titles[i].text) else: print(f"{i - 3}" + titles[i].text) Output: For more information, refer to our Python BeautifulSoup Tutorial. First we will create a list of dictionaries with the key value pairs that we want to add in the CSV file. Then we will use the csv module to write the output in the CSV file. See the below example for better understanding. Python3 import requestsfrom bs4 import BeautifulSoup as bsimport csv URL = 'https://www.geeksforgeeks.org/page/' soup = bs(req.text, 'html.parser') titles = soup.find_all('div', attrs={'class', 'head'})titles_list = [] count = 1for title in titles: d = {} d['Title Number'] = f'Title {count}' d['Title Name'] = title.text count += 1 titles_list.append(d) filename = 'titles.csv'with open(filename, 'w', newline='') as f: w = csv.DictWriter(f,['Title Number','Title Name']) w.writeheader() w.writerows(titles_list) Output: surindertarika1234 mehrayush762 sumitgumber28 Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 493, "s": 54, "text": "Let’s suppose you want to get some information from a website? Let’s say an article from the geeksforgeeks website or some news article, what will you do? The first thing that may come in your mind is to copy and paste the information into your local media. But what if you want a large amount of data on a daily basis and as quickly as possible. In such situations, copy and paste will not work and that’s where you’ll need web scraping." }, { "code": null, "e": 618, "s": 493, "text": "In this article, we will discuss how to perform web scraping using the requests library and beautifulsoup library in Python." }, { "code": null, "e": 804, "s": 618, "text": "Requests library is used for making HTTP requests to a specific URL and returns the response. Python requests provide inbuilt functionalities for managing both the request and response." }, { "code": null, "e": 939, "s": 804, "text": "Requests installation depends on the type of operating system, the basic command anywhere would be to open a command terminal and run," }, { "code": null, "e": 960, "s": 939, "text": "pip install requests" }, { "code": null, "e": 1307, "s": 960, "text": "Python requests module has several built-in methods to make HTTP requests to specified URI using GET, POST, PUT, PATCH, or HEAD requests. A HTTP request is meant to either retrieve data from a specified URI or to push data to a server. It works as a request-response protocol between a client and a server. Here we will be using the GET request. " }, { "code": null, "e": 1472, "s": 1307, "text": "GET method is used to retrieve information from the given server using a given URI. The GET method sends the encoded user information appended to the page request. " }, { "code": null, "e": 1480, "s": 1472, "text": "Python3" }, { "code": "import requests # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # check status code for response received# success code - 200print(r) # print content of requestprint(r.content)", "e": 1710, "s": 1480, "text": null }, { "code": null, "e": 1721, "s": 1713, "text": "Output:" }, { "code": null, "e": 2180, "s": 1725, "text": "When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being – get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the status code from the headers itself, and one can check if the request was processed successfully or not." }, { "code": null, "e": 2268, "s": 2182, "text": "Response objects can be used to imply lots of features, methods, and functionalities." }, { "code": null, "e": 2280, "s": 2272, "text": "Python3" }, { "code": "import requests # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # print request objectprint(r.url) # print status codeprint(r.status_code)", "e": 2474, "s": 2280, "text": null }, { "code": null, "e": 2485, "s": 2477, "text": "Output:" }, { "code": null, "e": 2550, "s": 2487, "text": "https://www.geeksforgeeks.org/python-programming-language/\n200" }, { "code": null, "e": 2613, "s": 2552, "text": "For more information, refer to our Python Requests Tutorial." }, { "code": null, "e": 2778, "s": 2617, "text": "BeautifulSoup is used extract information from the HTML and XML files. It provides a parse tree and the functions to navigate, search or modify this parse tree." }, { "code": null, "e": 3025, "s": 2782, "text": "To install Beautifulsoup on Windows, Linux, or any operating system, one would need pip package. To check how to install pip on your operating system, check out – PIP Installation – Windows || Linux. Now run the below command in the terminal." }, { "code": null, "e": 3054, "s": 3027, "text": "pip install beautifulsoup4" }, { "code": null, "e": 3339, "s": 3056, "text": "Before getting out any information from the HTML of the page, we must understand the structure of the page. This is needed to be done in order to select the desired data from the entire page. We can do this by right-clicking on the page we want to scrape and select inspect element." }, { "code": null, "e": 3541, "s": 3343, "text": "After clicking the inspect button the Developer Tools of the browser gets open. Now almost all the browsers come with the developers tools installed, and we will be using Chrome for this tutorial. " }, { "code": null, "e": 3734, "s": 3545, "text": "The developer’s tools allow seeing the site’s Document Object Model (DOM). If you don’t know about DOM then don’t worry just consider the text displayed as the HTML structure of the page. " }, { "code": null, "e": 3938, "s": 3738, "text": "After getting the HTML of the page let’s see how to parse this raw HTML code into some useful information. First of all, we will create a BeautifulSoup object by specifying the parser we want to use." }, { "code": null, "e": 4141, "s": 3940, "text": "Note: BeautifulSoup library is built on top of the HTML parsing libraries like html5lib, lxml, html.parser, etc. So BeautifulSoup object and specify the parser library can be created at the same time." }, { "code": null, "e": 4153, "s": 4145, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # check status code for response received# success code - 200print(r) # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser')print(soup.prettify())", "e": 4457, "s": 4153, "text": null }, { "code": null, "e": 4465, "s": 4457, "text": "Output:" }, { "code": null, "e": 4617, "s": 4465, "text": "This information is still not useful to us, let’s see another example to make some clear picture from this. Let’s try to extract the title of the page." }, { "code": null, "e": 4625, "s": 4617, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') # Getting the title tagprint(soup.title) # Getting the name of the tagprint(soup.title.name) # Getting the name of parent tagprint(soup.title.parent.name) # use the child attribute to get# the name of the child tag", "e": 5052, "s": 4625, "text": null }, { "code": null, "e": 5060, "s": 5052, "text": "Output:" }, { "code": null, "e": 5130, "s": 5060, "text": "<title>Python Programming Language - GeeksforGeeks</title>\ntitle\nhtml" }, { "code": null, "e": 5450, "s": 5130, "text": "Now, we would like to extract some useful data from the HTML content. The soup object contains all the data in the nested structure which could be programmatically extracted. The website we want to scrape contains a lot of text so now let’s scrape all those content. First, let’s inspect the webpage we want to scrape. " }, { "code": null, "e": 5941, "s": 5450, "text": "In the above image, we can see that all the content of the page is under the div with class entry-content. We will use the find class. This class will find the given tag with the given attribute. In our case, it will find all the div having class as entry-content. We have got all the content from the site but you can see that all the images and links are also scraped. So our next task is to find only the content from the above-parsed HTML. On again inspecting the HTML of our website – " }, { "code": null, "e": 6113, "s": 5941, "text": "We can see that the content of the page is under the <p> tag. Now we have to find all the p tags present in this class. We can use the find_all class of the BeautifulSoup." }, { "code": null, "e": 6121, "s": 6113, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') s = soup.find('div', class_='entry-content')content = s.find_all('p') print(content)", "e": 6418, "s": 6121, "text": null }, { "code": null, "e": 6429, "s": 6421, "text": "Output:" }, { "code": null, "e": 6694, "s": 6433, "text": "In the above example, we have found the elements by the class name but let’s see how to find elements by id. Now for this task let’s scrape the content of the leftbar of the page. The first step is to inspect the page and see the leftbar falls under which tag." }, { "code": null, "e": 6896, "s": 6698, "text": "The above image shows that the leftbar falls under the <div> tag with id as main. Now lets’s get the HTML content under this tag. Now let’s inspect more of the page get the content of the leftbar. " }, { "code": null, "e": 7042, "s": 6900, "text": "We can see that the list in the leftbar is under the <ul> tag with the class as leftBarList and our task is to find all the li under this ul." }, { "code": null, "e": 7052, "s": 7044, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') # Finding by ids = soup.find('div', id= 'main') # Getting the leftbarleftbar = s.find('ul', class_='leftBarList') # All the li under the above ulcontent = leftbar.find_all('li') print(content)", "e": 7457, "s": 7052, "text": null }, { "code": null, "e": 7468, "s": 7460, "text": "Output:" }, { "code": null, "e": 7824, "s": 7472, "text": "In the above examples, you must have seen that while scraping the data the tags also get scraped but what if we want only the text without any tags. Don’t worry we will discuss the same in this section. We will be using the text property. It only prints the text from the tag. We will be using the above example and will remove all the tags from them." }, { "code": null, "e": 7836, "s": 7828, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') s = soup.find('div', class_='entry-content') lines = s.find_all('p') for line in lines: print(line.text)", "e": 8156, "s": 7836, "text": null }, { "code": null, "e": 8167, "s": 8159, "text": "Output:" }, { "code": null, "e": 8179, "s": 8171, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') # Finding by ids = soup.find('div', id= 'main') # Getting the leftbarleftbar = s.find('ul', class_='leftBarList') # All the li under the above ullines = leftbar.find_all('li') for line in lines: print(line.text)", "e": 8606, "s": 8179, "text": null }, { "code": null, "e": 8617, "s": 8609, "text": "Output:" }, { "code": null, "e": 8718, "s": 8621, "text": "Till now we have seen how to extract text, let’s now see how to extract the links from the page." }, { "code": null, "e": 8730, "s": 8722, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') # find all the anchor tags with \"href\"for link in soup.find_all('a'): print(link.get('href'))", "e": 9039, "s": 8730, "text": null }, { "code": null, "e": 9050, "s": 9042, "text": "Output:" }, { "code": null, "e": 9210, "s": 9054, "text": "On again inspecting the page, we can see that images lie inside the img tag and the link of that image is inside the src attribute. See the below image – " }, { "code": null, "e": 9222, "s": 9214, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup # Making a GET requestr = requests.get('https://www.geeksforgeeks.org/python-programming-language/') # Parsing the HTMLsoup = BeautifulSoup(r.content, 'html.parser') images_list = [] images = soup.select('img')for image in images: src = image.get('src') alt = image.get('alt') images_list.append({\"src\": src, \"alt\": alt}) for image in images_list: print(image)", "e": 9645, "s": 9222, "text": null }, { "code": null, "e": 9656, "s": 9648, "text": "Output:" }, { "code": null, "e": 9949, "s": 9660, "text": "Now, there may arise various instances where you may want to get data from multiple pages from the same website or multiple different URLs as well, and manually writing code for each webpage is a time-consuming and tedious task. Plus, it defines all basic principles of automation. Duh! " }, { "code": null, "e": 10067, "s": 9951, "text": "To solve this exact problem, we will see two main techniques that will help us extract data from multiple webpages:" }, { "code": null, "e": 10086, "s": 10069, "text": "The same website" }, { "code": null, "e": 10109, "s": 10086, "text": "Different website URLs" }, { "code": null, "e": 10165, "s": 10109, "text": "page numbers at the bottom of the GeeksforGeeks website" }, { "code": null, "e": 10356, "s": 10167, "text": "Most websites have pages labeled from 1 to N. This makes it really simple for us to loop through these pages and extract data from them as these pages have similar structures. For example:" }, { "code": null, "e": 10414, "s": 10358, "text": "page numbers at the bottom of the GeeksforGeeks website" }, { "code": null, "e": 10777, "s": 10416, "text": "Here, we can see the page details at the end of the URL. Using this information we can easily create a for loop iterating over as many pages as we want (by putting page/(i)/ in the URL string and iterating “i” till N) and scrape all the useful data from them. The following code will give you more clarity over how to scrape data by using a For Loop in Python." }, { "code": null, "e": 10787, "s": 10779, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup as bs URL = 'https://www.geeksforgeeks.org/page/1/' req = requests.get(URL)soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs = {'class','head'}) print(titles[4].text)", "e": 11019, "s": 10787, "text": null }, { "code": null, "e": 11027, "s": 11019, "text": "Output:" }, { "code": null, "e": 11081, "s": 11027, "text": "7 Most Common Time Wastes During Software Development" }, { "code": null, "e": 11195, "s": 11081, "text": "Now, using the above code, we can get the titles of all the articles by just sandwiching those lines with a loop." }, { "code": null, "e": 11203, "s": 11195, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup as bs URL = 'https://www.geeksforgeeks.org/page/' for page in range(1, 10): req = requests.get(URL + str(page) + '/') soup = bs(req.text, 'html.parser') titles = soup.find_all('div', attrs={'class', 'head'}) for i in range(4, 19): if page > 1: print(f\"{(i-3)+page*15}\" + titles[i].text) else: print(f\"{i-3}\" + titles[i].text)", "e": 11625, "s": 11203, "text": null }, { "code": null, "e": 11633, "s": 11625, "text": "Output:" }, { "code": null, "e": 11870, "s": 11633, "text": "The above technique is absolutely wonderful, but what if you need to scrape different pages, and you don’t know their page numbers? You’ll need to scrape those different URLs one by one and manually code a script for every such webpage." }, { "code": null, "e": 12142, "s": 11870, "text": "Instead, you could just make a list of these URLs and loop through them. By simply iterating the items in the list i.e. the URLs, we will be able to extract the titles of those pages without having to write code for each page. Here’s an example code of how you can do it." }, { "code": null, "e": 12150, "s": 12142, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup as bs URL = ['https://www.geeksforgeeks.org','https://www.geeksforgeeks.org/page/10/'] for url in range(0,2): req = requests.get(URL[url]) soup = bs(req.text, 'html.parser') titles = soup.find_all('div',attrs={'class','head'}) for i in range(4, 19): if url+1 > 1: print(f\"{(i - 3) + url * 15}\" + titles[i].text) else: print(f\"{i - 3}\" + titles[i].text)", "e": 12597, "s": 12150, "text": null }, { "code": null, "e": 12605, "s": 12597, "text": "Output:" }, { "code": null, "e": 12671, "s": 12605, "text": "For more information, refer to our Python BeautifulSoup Tutorial." }, { "code": null, "e": 12894, "s": 12671, "text": "First we will create a list of dictionaries with the key value pairs that we want to add in the CSV file. Then we will use the csv module to write the output in the CSV file. See the below example for better understanding." }, { "code": null, "e": 12902, "s": 12894, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoup as bsimport csv URL = 'https://www.geeksforgeeks.org/page/' soup = bs(req.text, 'html.parser') titles = soup.find_all('div', attrs={'class', 'head'})titles_list = [] count = 1for title in titles: d = {} d['Title Number'] = f'Title {count}' d['Title Name'] = title.text count += 1 titles_list.append(d) filename = 'titles.csv'with open(filename, 'w', newline='') as f: w = csv.DictWriter(f,['Title Number','Title Name']) w.writeheader() w.writerows(titles_list)", "e": 13437, "s": 12902, "text": null }, { "code": null, "e": 13448, "s": 13440, "text": "Output:" }, { "code": null, "e": 13471, "s": 13452, "text": "surindertarika1234" }, { "code": null, "e": 13484, "s": 13471, "text": "mehrayush762" }, { "code": null, "e": 13498, "s": 13484, "text": "sumitgumber28" }, { "code": null, "e": 13511, "s": 13498, "text": "Web-scraping" }, { "code": null, "e": 13518, "s": 13511, "text": "Python" }, { "code": null, "e": 13616, "s": 13518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13648, "s": 13616, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 13675, "s": 13648, "text": "Python Classes and Objects" }, { "code": null, "e": 13706, "s": 13675, "text": "Python | os.path.join() method" }, { "code": null, "e": 13729, "s": 13706, "text": "Introduction To PYTHON" }, { "code": null, "e": 13750, "s": 13729, "text": "Python OOPs Concepts" }, { "code": null, "e": 13806, "s": 13750, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 13848, "s": 13806, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 13890, "s": 13848, "text": "Check if element exists in list in Python" }, { "code": null, "e": 13929, "s": 13890, "text": "Python | Get unique values from a list" } ]
How to send state/props to another component in React with onClick?
25 Oct, 2020 The props and state are the main concepts of React. Actually, only changes in props and/ or state trigger React to rerender your components and potentially update the DOM in the browser Props: It allows you to pass data from a parent component to a child component. State: While props allow you to pass data from a parent component to a child component, the state is used to change the component, well, state from within. Changes to the state also trigger a UI update. Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop. For a better understanding look at this example. For class-based component. App.js:JavascriptJavascript// First Component i.e. App import React, { Component } from 'react';import './App.css'import Component2 from './Component2'; class App extends Component { state={data:""} changeState = () => { this.setState({data:`state/props of parent component is send by onClick event to another component`}); }; render(){ return ( <div className="App"> <Component2 data={this.state.data} /> <div className="main-cointainer"> <h2>Compnent1</h2> <button onClick={this.changeState} type="button"> Send state </button> </div> </div> ); }} export default App; Component2.js:JavascriptJavascriptimport React from 'react'; const Component2 = (props) => { return ( <div className="main-cointainer"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )} export default Component2; App.js:JavascriptJavascript// First Component i.e. App import React, { Component } from 'react';import './App.css'import Component2 from './Component2'; class App extends Component { state={data:""} changeState = () => { this.setState({data:`state/props of parent component is send by onClick event to another component`}); }; render(){ return ( <div className="App"> <Component2 data={this.state.data} /> <div className="main-cointainer"> <h2>Compnent1</h2> <button onClick={this.changeState} type="button"> Send state </button> </div> </div> ); }} export default App; App.js: Javascript // First Component i.e. App import React, { Component } from 'react';import './App.css'import Component2 from './Component2'; class App extends Component { state={data:""} changeState = () => { this.setState({data:`state/props of parent component is send by onClick event to another component`}); }; render(){ return ( <div className="App"> <Component2 data={this.state.data} /> <div className="main-cointainer"> <h2>Compnent1</h2> <button onClick={this.changeState} type="button"> Send state </button> </div> </div> ); }} export default App; Component2.js:JavascriptJavascriptimport React from 'react'; const Component2 = (props) => { return ( <div className="main-cointainer"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )} export default Component2; Component2.js: Javascript import React from 'react'; const Component2 = (props) => { return ( <div className="main-cointainer"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )} export default Component2; For Function-based component. App.js:JavascriptJavascript// First component i.e App import React, { useState } from 'react';import './App.css'import Component2 from './Component2'; function App() { const [state, setstate] = useState({data:""}) const changeState = () => { setstate({data:`state/props of parent component is send by onClick event to another component`}); }; return ( <div className="App"> <Component2 data={state.data} /> <div className="main-cointainer"> <h2>Compnent1</h2> <button onClick={changeState} type="button"> Send state </button> </div> </div> ); } export default App;Component2.js:JavascriptJavascript// Second Componentimport React from 'react';import './Component2.css' export default function Component2(props) { return ( <div className="main-cointainer"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )} App.js:JavascriptJavascript// First component i.e App import React, { useState } from 'react';import './App.css'import Component2 from './Component2'; function App() { const [state, setstate] = useState({data:""}) const changeState = () => { setstate({data:`state/props of parent component is send by onClick event to another component`}); }; return ( <div className="App"> <Component2 data={state.data} /> <div className="main-cointainer"> <h2>Compnent1</h2> <button onClick={changeState} type="button"> Send state </button> </div> </div> ); } export default App; App.js: Javascript // First component i.e App import React, { useState } from 'react';import './App.css'import Component2 from './Component2'; function App() { const [state, setstate] = useState({data:""}) const changeState = () => { setstate({data:`state/props of parent component is send by onClick event to another component`}); }; return ( <div className="App"> <Component2 data={state.data} /> <div className="main-cointainer"> <h2>Compnent1</h2> <button onClick={changeState} type="button"> Send state </button> </div> </div> ); } export default App; Component2.js:JavascriptJavascript// Second Componentimport React from 'react';import './Component2.css' export default function Component2(props) { return ( <div className="main-cointainer"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )} Component2.js: Javascript // Second Componentimport React from 'react';import './Component2.css' export default function Component2(props) { return ( <div className="main-cointainer"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )} Output : Before clicking on the button:After clicking the button: Before clicking on the button: Before clicking on the button: After clicking the button: After clicking the button: react-js 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 How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page? How to set input type date in dd-mm-yyyy format using HTML ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Oct, 2020" }, { "code": null, "e": 240, "s": 54, "text": "The props and state are the main concepts of React. Actually, only changes in props and/ or state trigger React to rerender your components and potentially update the DOM in the browser" }, { "code": null, "e": 320, "s": 240, "text": "Props: It allows you to pass data from a parent component to a child component." }, { "code": null, "e": 523, "s": 320, "text": "State: While props allow you to pass data from a parent component to a child component, the state is used to change the component, well, state from within. Changes to the state also trigger a UI update." }, { "code": null, "e": 833, "s": 523, "text": "Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop. For a better understanding look at this example." }, { "code": null, "e": 860, "s": 833, "text": "For class-based component." }, { "code": null, "e": 1906, "s": 860, "text": "App.js:JavascriptJavascript// First Component i.e. App import React, { Component } from 'react';import './App.css'import Component2 from './Component2'; class App extends Component { state={data:\"\"} changeState = () => { this.setState({data:`state/props of parent component is send by onClick event to another component`}); }; render(){ return ( <div className=\"App\"> <Component2 data={this.state.data} /> <div className=\"main-cointainer\"> <h2>Compnent1</h2> <button onClick={this.changeState} type=\"button\"> Send state </button> </div> </div> ); }} export default App; Component2.js:JavascriptJavascriptimport React from 'react'; const Component2 = (props) => { return ( <div className=\"main-cointainer\"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )} export default Component2;" }, { "code": null, "e": 2691, "s": 1906, "text": "App.js:JavascriptJavascript// First Component i.e. App import React, { Component } from 'react';import './App.css'import Component2 from './Component2'; class App extends Component { state={data:\"\"} changeState = () => { this.setState({data:`state/props of parent component is send by onClick event to another component`}); }; render(){ return ( <div className=\"App\"> <Component2 data={this.state.data} /> <div className=\"main-cointainer\"> <h2>Compnent1</h2> <button onClick={this.changeState} type=\"button\"> Send state </button> </div> </div> ); }} export default App; " }, { "code": null, "e": 2699, "s": 2691, "text": "App.js:" }, { "code": null, "e": 2710, "s": 2699, "text": "Javascript" }, { "code": "// First Component i.e. App import React, { Component } from 'react';import './App.css'import Component2 from './Component2'; class App extends Component { state={data:\"\"} changeState = () => { this.setState({data:`state/props of parent component is send by onClick event to another component`}); }; render(){ return ( <div className=\"App\"> <Component2 data={this.state.data} /> <div className=\"main-cointainer\"> <h2>Compnent1</h2> <button onClick={this.changeState} type=\"button\"> Send state </button> </div> </div> ); }} export default App; ", "e": 3468, "s": 2710, "text": null }, { "code": null, "e": 3730, "s": 3468, "text": "Component2.js:JavascriptJavascriptimport React from 'react'; const Component2 = (props) => { return ( <div className=\"main-cointainer\"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )} export default Component2;" }, { "code": null, "e": 3745, "s": 3730, "text": "Component2.js:" }, { "code": null, "e": 3756, "s": 3745, "text": "Javascript" }, { "code": "import React from 'react'; const Component2 = (props) => { return ( <div className=\"main-cointainer\"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )} export default Component2;", "e": 3984, "s": 3756, "text": null }, { "code": null, "e": 4014, "s": 3984, "text": "For Function-based component." }, { "code": null, "e": 5055, "s": 4014, "text": "App.js:JavascriptJavascript// First component i.e App import React, { useState } from 'react';import './App.css'import Component2 from './Component2'; function App() { const [state, setstate] = useState({data:\"\"}) const changeState = () => { setstate({data:`state/props of parent component is send by onClick event to another component`}); }; return ( <div className=\"App\"> <Component2 data={state.data} /> <div className=\"main-cointainer\"> <h2>Compnent1</h2> <button onClick={changeState} type=\"button\"> Send state </button> </div> </div> ); } export default App;Component2.js:JavascriptJavascript// Second Componentimport React from 'react';import './Component2.css' export default function Component2(props) { return ( <div className=\"main-cointainer\"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )}" }, { "code": null, "e": 5807, "s": 5055, "text": "App.js:JavascriptJavascript// First component i.e App import React, { useState } from 'react';import './App.css'import Component2 from './Component2'; function App() { const [state, setstate] = useState({data:\"\"}) const changeState = () => { setstate({data:`state/props of parent component is send by onClick event to another component`}); }; return ( <div className=\"App\"> <Component2 data={state.data} /> <div className=\"main-cointainer\"> <h2>Compnent1</h2> <button onClick={changeState} type=\"button\"> Send state </button> </div> </div> ); } export default App;" }, { "code": null, "e": 5815, "s": 5807, "text": "App.js:" }, { "code": null, "e": 5826, "s": 5815, "text": "Javascript" }, { "code": "// First component i.e App import React, { useState } from 'react';import './App.css'import Component2 from './Component2'; function App() { const [state, setstate] = useState({data:\"\"}) const changeState = () => { setstate({data:`state/props of parent component is send by onClick event to another component`}); }; return ( <div className=\"App\"> <Component2 data={state.data} /> <div className=\"main-cointainer\"> <h2>Compnent1</h2> <button onClick={changeState} type=\"button\"> Send state </button> </div> </div> ); } export default App;", "e": 6551, "s": 5826, "text": null }, { "code": null, "e": 6841, "s": 6551, "text": "Component2.js:JavascriptJavascript// Second Componentimport React from 'react';import './Component2.css' export default function Component2(props) { return ( <div className=\"main-cointainer\"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )}" }, { "code": null, "e": 6856, "s": 6841, "text": "Component2.js:" }, { "code": null, "e": 6867, "s": 6856, "text": "Javascript" }, { "code": "// Second Componentimport React from 'react';import './Component2.css' export default function Component2(props) { return ( <div className=\"main-cointainer\"> <h2>Compnent2</h2> <p>{props.data} </p> </div> )}", "e": 7123, "s": 6867, "text": null }, { "code": null, "e": 7133, "s": 7123, "text": "Output : " }, { "code": null, "e": 7191, "s": 7133, "text": "Before clicking on the button:After clicking the button: " }, { "code": null, "e": 7222, "s": 7191, "text": "Before clicking on the button:" }, { "code": null, "e": 7253, "s": 7222, "text": "Before clicking on the button:" }, { "code": null, "e": 7281, "s": 7253, "text": "After clicking the button: " }, { "code": null, "e": 7309, "s": 7281, "text": "After clicking the button: " }, { "code": null, "e": 7318, "s": 7309, "text": "react-js" }, { "code": null, "e": 7335, "s": 7318, "text": "Web Technologies" }, { "code": null, "e": 7433, "s": 7335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7494, "s": 7433, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7537, "s": 7494, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 7609, "s": 7537, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 7649, "s": 7609, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7673, "s": 7649, "text": "REST API (Introduction)" }, { "code": null, "e": 7706, "s": 7673, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 7766, "s": 7706, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 7824, "s": 7766, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 7885, "s": 7824, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python - Proxy Server
Proxy servers are used to browse to some website through another server so that the browsing remains anonymous. It can also be used to bypass the blocking of specific IP addresses. We use the urlopen method from the urllib module to access the website by passing the proxy server address as a parameter. In the below example we use a proxy address to access the website twitter.con for anonymous access. The response status of OK proves the successful access through a proxy server. import urllib URL = 'https://www.twitter.com' PROXY_ADDRESS = "265.24.11.6:8080" if __name__ == '__main__': resp = urllib.urlopen(URL, proxies = {"http" : PROXY_ADDRESS}) print "Proxy server returns response headers: %s " %resp.headers When we run the above program, we get the following output − Proxy server returns response headers: cache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0 content-length: 145960 content-type: text/html;charset=utf-8 date: Mon, 02 Jul 2018 02:06:19 GMT expires: Tue, 31 Mar 1981 05:00:00 GMT last-modified: Mon, 02 Jul 2018 02:06:19 GMT pragma: no-cache server: tsa_n set-cookie: fm=0; Expires=Mon, 02 Jul 2018 02:06:10 GMT; Path=/; Domain=.twitter.com; Secure; HTTPOnly set-cookie: _twitter_sess=BAh7CSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCAifvVhkAToMY3NyZl9p%250AZCIlNzlhY2ZhMzdmNGFkYTU0ZTRmMDkxODRhNWNiYzI0MDI6B2lkIiUyZTgy%250AOTAyYjY4NTBkMzE3YzNjYTQwNzZjZDhhYjZhMQ%253D%253D--6807256d74a01129a7b0dcf383f56f169fb8a66c; Path=/; Domain=.twitter.com; Secure; HTTPOnly set-cookie: personalization_id="v1_iDacJdPWUx3e81f8UErWTA=="; Expires=Wed, 01 Jul 2020 02:06:19 GMT; Path=/; Domain=.twitter.com set-cookie: guest_id=v1%3A153049717939764273; Expires=Wed, 01 Jul 2020 02:06:19 GMT; Path=/; Domain=.twitter.com set-cookie: ct0=50c8b59b09322825cd750ea082e43bdc; Expires=Mon, 02 Jul 2018 08:06:19 GMT; Path=/; Domain=.twitter.com; Secure status: 200 OK strict-transport-security: max-age=631138519 x-connection-hash: 89dfbab81abc35dd8f618509c6171bd3 x-content-type-options: nosniff x-frame-options: SAMEORIGIN x-response-time: 312 x-transaction: 007b998000f86eaf x-twitter-response-tags: BouncerCompliant x-ua-compatible: IE=edge,chrome=1 x-xss-protection: 1; mode=block; report=https://twitter.com/i/xss_report 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2507, "s": 2326, "text": "Proxy servers are used to browse to some website through another server so that the browsing remains anonymous. It can also be used to bypass the blocking of specific IP addresses." }, { "code": null, "e": 2630, "s": 2507, "text": "We use the urlopen method from the urllib module to access the website by passing the proxy server address as a parameter." }, { "code": null, "e": 2810, "s": 2630, "text": "In the below example we use a proxy address to access the website twitter.con for anonymous access. The response status of OK proves the successful access through a proxy server. " }, { "code": null, "e": 3050, "s": 2810, "text": "import urllib\nURL = 'https://www.twitter.com'\nPROXY_ADDRESS = \"265.24.11.6:8080\"\nif __name__ == '__main__':\n resp = urllib.urlopen(URL, proxies = {\"http\" : PROXY_ADDRESS})\nprint \"Proxy server returns response headers: %s \" %resp.headers" }, { "code": null, "e": 3111, "s": 3050, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 4645, "s": 3111, "text": "Proxy server returns response headers: cache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0\ncontent-length: 145960\ncontent-type: text/html;charset=utf-8\ndate: Mon, 02 Jul 2018 02:06:19 GMT\nexpires: Tue, 31 Mar 1981 05:00:00 GMT\nlast-modified: Mon, 02 Jul 2018 02:06:19 GMT\npragma: no-cache\nserver: tsa_n\nset-cookie: fm=0; Expires=Mon, 02 Jul 2018 02:06:10 GMT; Path=/; Domain=.twitter.com; Secure; HTTPOnly\nset-cookie: _twitter_sess=BAh7CSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCAifvVhkAToMY3NyZl9p%250AZCIlNzlhY2ZhMzdmNGFkYTU0ZTRmMDkxODRhNWNiYzI0MDI6B2lkIiUyZTgy%250AOTAyYjY4NTBkMzE3YzNjYTQwNzZjZDhhYjZhMQ%253D%253D--6807256d74a01129a7b0dcf383f56f169fb8a66c; Path=/; Domain=.twitter.com; Secure; HTTPOnly\nset-cookie: personalization_id=\"v1_iDacJdPWUx3e81f8UErWTA==\"; Expires=Wed, 01 Jul 2020 02:06:19 GMT; Path=/; Domain=.twitter.com\nset-cookie: guest_id=v1%3A153049717939764273; Expires=Wed, 01 Jul 2020 02:06:19 GMT; Path=/; Domain=.twitter.com\nset-cookie: ct0=50c8b59b09322825cd750ea082e43bdc; Expires=Mon, 02 Jul 2018 08:06:19 GMT; Path=/; Domain=.twitter.com; Secure\nstatus: 200 OK\nstrict-transport-security: max-age=631138519\nx-connection-hash: 89dfbab81abc35dd8f618509c6171bd3\nx-content-type-options: nosniff\nx-frame-options: SAMEORIGIN\nx-response-time: 312\nx-transaction: 007b998000f86eaf\nx-twitter-response-tags: BouncerCompliant\nx-ua-compatible: IE=edge,chrome=1\nx-xss-protection: 1; mode=block; report=https://twitter.com/i/xss_report\n\n" }, { "code": null, "e": 4682, "s": 4645, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4698, "s": 4682, "text": " Malhar Lathkar" }, { "code": null, "e": 4731, "s": 4698, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4750, "s": 4731, "text": " Arnab Chakraborty" }, { "code": null, "e": 4785, "s": 4750, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4807, "s": 4785, "text": " In28Minutes Official" }, { "code": null, "e": 4841, "s": 4807, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4869, "s": 4841, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4904, "s": 4869, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4918, "s": 4904, "text": " Lets Kode It" }, { "code": null, "e": 4951, "s": 4918, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4968, "s": 4951, "text": " Abhilash Nelson" }, { "code": null, "e": 4975, "s": 4968, "text": " Print" }, { "code": null, "e": 4986, "s": 4975, "text": " Add Notes" } ]
Output Iterators in C++ - GeeksforGeeks
25 Apr, 2019 After going through the template definition of various STL algorithms like std::copy, std::move, std::transform, you must have found their template definition consisting of objects of type Output Iterator. So what are they and why are they used ? Output iterators are one of the five main types of iterators present in C++ Standard Library, others being Input iterators, Forward iterator, Bidirectional iterator and Random – access iterators. Output iterators are considered to be the exact opposite of input iterators, as they perform the opposite function of input iterators. They can be assigned values in a sequence, but cannot be used to access values, unlike input iterators which do the reverse of accessing values and cannot be assigned values. So, we can say that input and output iterators are complementary to each other. One important thing to be kept in mind is that forward, bidirectional and random-access iterators are also valid output iterators, as shown in the iterator hierarchy above. Salient Features Usability: Just like input iterators, Output iterators can be used only with single-pass algorithms, i.e., algorithms in which we can go to all the locations in the range at most once, such that these locations can be dereferenced or assigned value only once.Equality / Inequality Comparison: Unlike input iterators, output iterators cannot be compared for equality with another iterator.So, the following two expressions are invalid if A and B are output iterators:A == B // Invalid - Checking for equality A != B // Invalid - Checking for inequality Dereferencing: An input iterator can be dereferenced as an rvalue, using operator * and ->, whereas an output iterator can be dereferenced as an lvalue to provide the location to store the value.So, the following two expressions are valid if A is an output iterator:*A = 1 // Dereferencing using * A -> m = 7 // Assigning a member element m Incrementable: An output iterator can be incremented, so that it refers to the next element in sequence, using operator ++().So, the following two expressions are valid if A is an output iterator:A++ // Using post increment operator ++A // Using pre increment operator Swappable: The value pointed to by these iterators can be exchanged or swapped. Usability: Just like input iterators, Output iterators can be used only with single-pass algorithms, i.e., algorithms in which we can go to all the locations in the range at most once, such that these locations can be dereferenced or assigned value only once. Equality / Inequality Comparison: Unlike input iterators, output iterators cannot be compared for equality with another iterator.So, the following two expressions are invalid if A and B are output iterators:A == B // Invalid - Checking for equality A != B // Invalid - Checking for inequality So, the following two expressions are invalid if A and B are output iterators: A == B // Invalid - Checking for equality A != B // Invalid - Checking for inequality Dereferencing: An input iterator can be dereferenced as an rvalue, using operator * and ->, whereas an output iterator can be dereferenced as an lvalue to provide the location to store the value.So, the following two expressions are valid if A is an output iterator:*A = 1 // Dereferencing using * A -> m = 7 // Assigning a member element m So, the following two expressions are valid if A is an output iterator: *A = 1 // Dereferencing using * A -> m = 7 // Assigning a member element m Incrementable: An output iterator can be incremented, so that it refers to the next element in sequence, using operator ++().So, the following two expressions are valid if A is an output iterator:A++ // Using post increment operator ++A // Using pre increment operator So, the following two expressions are valid if A is an output iterator: A++ // Using post increment operator ++A // Using pre increment operator Swappable: The value pointed to by these iterators can be exchanged or swapped. Practical implementation After understanding its features and deficiencies, it is very important to learn about its practical implementation as well. As told earlier, output iterators are used only when we want to assign elements and not when we have to access elements. The following two STL algorithms can show this fact: std::move: As the name suggests, this algorithm is used to move elements in a range into another range. Now, as far as accessing elements are concerned, input iterators are fine, but as soon as we have to assign elements in another container, then we cannot use these input iterators for this purpose, that is why here using output iterators becomes a compulsion.// Definition of std::move() template OutputIterator move (InputIterator first, InputIterator last, OutputIterator result) { while (first!=last) { *result = std::move(*first); ++result; ++first; } return result; } Here, since the result is the iterator to the resultant container, to which elements are assigned, so for this, we cannot use input iterators and have made use of output iterators at their place, whereas for accessing elements, input iterators are used which only needs to be incremented and accessed. // Definition of std::move() template OutputIterator move (InputIterator first, InputIterator last, OutputIterator result) { while (first!=last) { *result = std::move(*first); ++result; ++first; } return result; } Here, since the result is the iterator to the resultant container, to which elements are assigned, so for this, we cannot use input iterators and have made use of output iterators at their place, whereas for accessing elements, input iterators are used which only needs to be incremented and accessed. std::find: As we know this algorithm is used to find the presence of an element inside a container and doesn’t involve the use of output iterators.// Definition of std::find() template InputIterator find (InputIterator first, InputIterator last, const T& val) { while (first!=last) { if (*first==val) return first; ++first; } return last; } So, since here, there was no need for assigning values to iterators and only we needed to access and compare the iterators, so there was no need of output iterator and we have, therefore, used only the input iterators only. // Definition of std::find() template InputIterator find (InputIterator first, InputIterator last, const T& val) { while (first!=last) { if (*first==val) return first; ++first; } return last; } So, since here, there was no need for assigning values to iterators and only we needed to access and compare the iterators, so there was no need of output iterator and we have, therefore, used only the input iterators only. So, the two above examples very well show when, where, why and how output iterators are used practically. Limitations After studying about the salient features, one must also know the deficiencies of output iterators as well, which are mentioned in the following points: Only assigning, no accessing: One of the biggest deficiency is that we cannot access the output iterators as rvalue. So, an output iterator can only modify the element to which it points by being used as the target for an assignment.// C++ program to demonstrate output iterator#include<iostream>#include<vector>using namespace std;int main(){ vector<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator vector<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning elements using iterator *i1 = 1; } // v1 becomes 1 1 1 1 1 return 0;}The above is an example of assigning elements using output iterator, however, if we do something like:a = *i1 ; // where a is a variable So, this is not allowed for output iterator, as they can only be the target in assignment. However, if you try this for above code, it will work, because vectors return iterators higher in hierarchy than output iterators.This big deficiency is the reason why many algorithms like std::find, which requires to access the elements in a range and check for equality cannot use output iterators for doing so, because we can’t access values using it, so instead we make use of input iterators.Cannot be decremented: Just like we can use operator ++() with output iterators for incrementing them, we cannot decrement them.If A is an output iterator,then A-- // Not allowed with output iterators Use in multi-pass algorithms: Since, it is unidirectional and can only move forward, therefore, such iterators cannot be used in multi-pass algorithms, in which we need to move through the container multiple times.Relational Operators: Just like output iterators cannot be used with equality operators (==), it also can not be used with other relational operators like =.If A and B are output iterators, then A == B // Not Allowed A <= B // Not Allowed Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that output operators can only move in one direction that too forward and that too sequentially.If A and B are output iterators, then A + 1 // Not allowed B - 2 // Not allowed Only assigning, no accessing: One of the biggest deficiency is that we cannot access the output iterators as rvalue. So, an output iterator can only modify the element to which it points by being used as the target for an assignment.// C++ program to demonstrate output iterator#include<iostream>#include<vector>using namespace std;int main(){ vector<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator vector<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning elements using iterator *i1 = 1; } // v1 becomes 1 1 1 1 1 return 0;}The above is an example of assigning elements using output iterator, however, if we do something like:a = *i1 ; // where a is a variable So, this is not allowed for output iterator, as they can only be the target in assignment. However, if you try this for above code, it will work, because vectors return iterators higher in hierarchy than output iterators.This big deficiency is the reason why many algorithms like std::find, which requires to access the elements in a range and check for equality cannot use output iterators for doing so, because we can’t access values using it, so instead we make use of input iterators. // C++ program to demonstrate output iterator#include<iostream>#include<vector>using namespace std;int main(){ vector<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator vector<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning elements using iterator *i1 = 1; } // v1 becomes 1 1 1 1 1 return 0;} The above is an example of assigning elements using output iterator, however, if we do something like: a = *i1 ; // where a is a variable So, this is not allowed for output iterator, as they can only be the target in assignment. However, if you try this for above code, it will work, because vectors return iterators higher in hierarchy than output iterators. This big deficiency is the reason why many algorithms like std::find, which requires to access the elements in a range and check for equality cannot use output iterators for doing so, because we can’t access values using it, so instead we make use of input iterators. Cannot be decremented: Just like we can use operator ++() with output iterators for incrementing them, we cannot decrement them.If A is an output iterator,then A-- // Not allowed with output iterators If A is an output iterator,then A-- // Not allowed with output iterators Use in multi-pass algorithms: Since, it is unidirectional and can only move forward, therefore, such iterators cannot be used in multi-pass algorithms, in which we need to move through the container multiple times. Relational Operators: Just like output iterators cannot be used with equality operators (==), it also can not be used with other relational operators like =.If A and B are output iterators, then A == B // Not Allowed A <= B // Not Allowed If A and B are output iterators, then A == B // Not Allowed A <= B // Not Allowed Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that output operators can only move in one direction that too forward and that too sequentially.If A and B are output iterators, then A + 1 // Not allowed B - 2 // Not allowed If A and B are output iterators, then A + 1 // Not allowed B - 2 // Not allowed This article is contributed by Mrigendra Singh. 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. Akanksha_Rai cpp-iterator STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Friend class and function in C++ Polymorphism in C++ List in C++ Standard Template Library (STL) Pair in C++ Standard Template Library (STL) Convert string to char array in C++ new and delete operators in C++ for dynamic memory Destructors in C++ Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 23731, "s": 23703, "text": "\n25 Apr, 2019" }, { "code": null, "e": 23978, "s": 23731, "text": "After going through the template definition of various STL algorithms like std::copy, std::move, std::transform, you must have found their template definition consisting of objects of type Output Iterator. So what are they and why are they used ?" }, { "code": null, "e": 24174, "s": 23978, "text": "Output iterators are one of the five main types of iterators present in C++ Standard Library, others being Input iterators, Forward iterator, Bidirectional iterator and Random – access iterators." }, { "code": null, "e": 24564, "s": 24174, "text": "Output iterators are considered to be the exact opposite of input iterators, as they perform the opposite function of input iterators. They can be assigned values in a sequence, but cannot be used to access values, unlike input iterators which do the reverse of accessing values and cannot be assigned values. So, we can say that input and output iterators are complementary to each other." }, { "code": null, "e": 24737, "s": 24564, "text": "One important thing to be kept in mind is that forward, bidirectional and random-access iterators are also valid output iterators, as shown in the iterator hierarchy above." }, { "code": null, "e": 24754, "s": 24737, "text": "Salient Features" }, { "code": null, "e": 26009, "s": 24754, "text": "Usability: Just like input iterators, Output iterators can be used only with single-pass algorithms, i.e., algorithms in which we can go to all the locations in the range at most once, such that these locations can be dereferenced or assigned value only once.Equality / Inequality Comparison: Unlike input iterators, output iterators cannot be compared for equality with another iterator.So, the following two expressions are invalid if A and B are output iterators:A == B // Invalid - Checking for equality\nA != B // Invalid - Checking for inequality\nDereferencing: An input iterator can be dereferenced as an rvalue, using operator * and ->, whereas an output iterator can be dereferenced as an lvalue to provide the location to store the value.So, the following two expressions are valid if A is an output iterator:*A = 1 // Dereferencing using *\nA -> m = 7 // Assigning a member element m\nIncrementable: An output iterator can be incremented, so that it refers to the next element in sequence, using operator ++().So, the following two expressions are valid if A is an output iterator:A++ // Using post increment operator\n++A // Using pre increment operator\nSwappable: The value pointed to by these iterators can be exchanged or swapped." }, { "code": null, "e": 26269, "s": 26009, "text": "Usability: Just like input iterators, Output iterators can be used only with single-pass algorithms, i.e., algorithms in which we can go to all the locations in the range at most once, such that these locations can be dereferenced or assigned value only once." }, { "code": null, "e": 26565, "s": 26269, "text": "Equality / Inequality Comparison: Unlike input iterators, output iterators cannot be compared for equality with another iterator.So, the following two expressions are invalid if A and B are output iterators:A == B // Invalid - Checking for equality\nA != B // Invalid - Checking for inequality\n" }, { "code": null, "e": 26644, "s": 26565, "text": "So, the following two expressions are invalid if A and B are output iterators:" }, { "code": null, "e": 26733, "s": 26644, "text": "A == B // Invalid - Checking for equality\nA != B // Invalid - Checking for inequality\n" }, { "code": null, "e": 27082, "s": 26733, "text": "Dereferencing: An input iterator can be dereferenced as an rvalue, using operator * and ->, whereas an output iterator can be dereferenced as an lvalue to provide the location to store the value.So, the following two expressions are valid if A is an output iterator:*A = 1 // Dereferencing using *\nA -> m = 7 // Assigning a member element m\n" }, { "code": null, "e": 27154, "s": 27082, "text": "So, the following two expressions are valid if A is an output iterator:" }, { "code": null, "e": 27237, "s": 27154, "text": "*A = 1 // Dereferencing using *\nA -> m = 7 // Assigning a member element m\n" }, { "code": null, "e": 27511, "s": 27237, "text": "Incrementable: An output iterator can be incremented, so that it refers to the next element in sequence, using operator ++().So, the following two expressions are valid if A is an output iterator:A++ // Using post increment operator\n++A // Using pre increment operator\n" }, { "code": null, "e": 27583, "s": 27511, "text": "So, the following two expressions are valid if A is an output iterator:" }, { "code": null, "e": 27661, "s": 27583, "text": "A++ // Using post increment operator\n++A // Using pre increment operator\n" }, { "code": null, "e": 27741, "s": 27661, "text": "Swappable: The value pointed to by these iterators can be exchanged or swapped." }, { "code": null, "e": 27766, "s": 27741, "text": "Practical implementation" }, { "code": null, "e": 28065, "s": 27766, "text": "After understanding its features and deficiencies, it is very important to learn about its practical implementation as well. As told earlier, output iterators are used only when we want to assign elements and not when we have to access elements. The following two STL algorithms can show this fact:" }, { "code": null, "e": 29006, "s": 28065, "text": "std::move: As the name suggests, this algorithm is used to move elements in a range into another range. Now, as far as accessing elements are concerned, input iterators are fine, but as soon as we have to assign elements in another container, then we cannot use these input iterators for this purpose, that is why here using output iterators becomes a compulsion.// Definition of std::move()\ntemplate \nOutputIterator move (InputIterator first, InputIterator last,\n OutputIterator result)\n{\n while (first!=last)\n {\n *result = std::move(*first);\n ++result;\n ++first;\n }\n return result;\n}\nHere, since the result is the iterator to the resultant container, to which elements are assigned, so for this, we cannot use input iterators and have made use of output iterators at their place, whereas for accessing elements, input iterators are used which only needs to be incremented and accessed." }, { "code": null, "e": 29283, "s": 29006, "text": "// Definition of std::move()\ntemplate \nOutputIterator move (InputIterator first, InputIterator last,\n OutputIterator result)\n{\n while (first!=last)\n {\n *result = std::move(*first);\n ++result;\n ++first;\n }\n return result;\n}\n" }, { "code": null, "e": 29585, "s": 29283, "text": "Here, since the result is the iterator to the resultant container, to which elements are assigned, so for this, we cannot use input iterators and have made use of output iterators at their place, whereas for accessing elements, input iterators are used which only needs to be incremented and accessed." }, { "code": null, "e": 30205, "s": 29585, "text": "std::find: As we know this algorithm is used to find the presence of an element inside a container and doesn’t involve the use of output iterators.// Definition of std::find()\ntemplate \nInputIterator find (InputIterator first, InputIterator last, \n const T& val)\n{\n while (first!=last) \n {\n if (*first==val) return first;\n ++first;\n }\n return last;\n}\nSo, since here, there was no need for assigning values to iterators and only we needed to access and compare the iterators, so there was no need of output iterator and we have, therefore, used only the input iterators only." }, { "code": null, "e": 30455, "s": 30205, "text": "// Definition of std::find()\ntemplate \nInputIterator find (InputIterator first, InputIterator last, \n const T& val)\n{\n while (first!=last) \n {\n if (*first==val) return first;\n ++first;\n }\n return last;\n}\n" }, { "code": null, "e": 30679, "s": 30455, "text": "So, since here, there was no need for assigning values to iterators and only we needed to access and compare the iterators, so there was no need of output iterator and we have, therefore, used only the input iterators only." }, { "code": null, "e": 30785, "s": 30679, "text": "So, the two above examples very well show when, where, why and how output iterators are used practically." }, { "code": null, "e": 30797, "s": 30785, "text": "Limitations" }, { "code": null, "e": 30950, "s": 30797, "text": "After studying about the salient features, one must also know the deficiencies of output iterators as well, which are mentioned in the following points:" }, { "code": null, "e": 33157, "s": 30950, "text": "Only assigning, no accessing: One of the biggest deficiency is that we cannot access the output iterators as rvalue. So, an output iterator can only modify the element to which it points by being used as the target for an assignment.// C++ program to demonstrate output iterator#include<iostream>#include<vector>using namespace std;int main(){ vector<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator vector<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning elements using iterator *i1 = 1; } // v1 becomes 1 1 1 1 1 return 0;}The above is an example of assigning elements using output iterator, however, if we do something like:a = *i1 ; // where a is a variable\nSo, this is not allowed for output iterator, as they can only be the target in assignment. However, if you try this for above code, it will work, because vectors return iterators higher in hierarchy than output iterators.This big deficiency is the reason why many algorithms like std::find, which requires to access the elements in a range and check for equality cannot use output iterators for doing so, because we can’t access values using it, so instead we make use of input iterators.Cannot be decremented: Just like we can use operator ++() with output iterators for incrementing them, we cannot decrement them.If A is an output iterator,then\n\nA-- // Not allowed with output iterators\nUse in multi-pass algorithms: Since, it is unidirectional and can only move forward, therefore, such iterators cannot be used in multi-pass algorithms, in which we need to move through the container multiple times.Relational Operators: Just like output iterators cannot be used with equality operators (==), it also can not be used with other relational operators like =.If A and B are output iterators, then\n\nA == B // Not Allowed\nA <= B // Not Allowed\nArithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that output operators can only move in one direction that too forward and that too sequentially.If A and B are output iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\n" }, { "code": null, "e": 34375, "s": 33157, "text": "Only assigning, no accessing: One of the biggest deficiency is that we cannot access the output iterators as rvalue. So, an output iterator can only modify the element to which it points by being used as the target for an assignment.// C++ program to demonstrate output iterator#include<iostream>#include<vector>using namespace std;int main(){ vector<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator vector<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning elements using iterator *i1 = 1; } // v1 becomes 1 1 1 1 1 return 0;}The above is an example of assigning elements using output iterator, however, if we do something like:a = *i1 ; // where a is a variable\nSo, this is not allowed for output iterator, as they can only be the target in assignment. However, if you try this for above code, it will work, because vectors return iterators higher in hierarchy than output iterators.This big deficiency is the reason why many algorithms like std::find, which requires to access the elements in a range and check for equality cannot use output iterators for doing so, because we can’t access values using it, so instead we make use of input iterators." }, { "code": "// C++ program to demonstrate output iterator#include<iostream>#include<vector>using namespace std;int main(){ vector<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator vector<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning elements using iterator *i1 = 1; } // v1 becomes 1 1 1 1 1 return 0;}", "e": 34735, "s": 34375, "text": null }, { "code": null, "e": 34838, "s": 34735, "text": "The above is an example of assigning elements using output iterator, however, if we do something like:" }, { "code": null, "e": 34874, "s": 34838, "text": "a = *i1 ; // where a is a variable\n" }, { "code": null, "e": 35096, "s": 34874, "text": "So, this is not allowed for output iterator, as they can only be the target in assignment. However, if you try this for above code, it will work, because vectors return iterators higher in hierarchy than output iterators." }, { "code": null, "e": 35364, "s": 35096, "text": "This big deficiency is the reason why many algorithms like std::find, which requires to access the elements in a range and check for equality cannot use output iterators for doing so, because we can’t access values using it, so instead we make use of input iterators." }, { "code": null, "e": 35570, "s": 35364, "text": "Cannot be decremented: Just like we can use operator ++() with output iterators for incrementing them, we cannot decrement them.If A is an output iterator,then\n\nA-- // Not allowed with output iterators\n" }, { "code": null, "e": 35648, "s": 35570, "text": "If A is an output iterator,then\n\nA-- // Not allowed with output iterators\n" }, { "code": null, "e": 35863, "s": 35648, "text": "Use in multi-pass algorithms: Since, it is unidirectional and can only move forward, therefore, such iterators cannot be used in multi-pass algorithms, in which we need to move through the container multiple times." }, { "code": null, "e": 36112, "s": 35863, "text": "Relational Operators: Just like output iterators cannot be used with equality operators (==), it also can not be used with other relational operators like =.If A and B are output iterators, then\n\nA == B // Not Allowed\nA <= B // Not Allowed\n" }, { "code": null, "e": 36204, "s": 36112, "text": "If A and B are output iterators, then\n\nA == B // Not Allowed\nA <= B // Not Allowed\n" }, { "code": null, "e": 36527, "s": 36204, "text": "Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that output operators can only move in one direction that too forward and that too sequentially.If A and B are output iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\n" }, { "code": null, "e": 36617, "s": 36527, "text": "If A and B are output iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\n" }, { "code": null, "e": 36920, "s": 36617, "text": "This article is contributed by Mrigendra Singh. 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": 37045, "s": 36920, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 37058, "s": 37045, "text": "Akanksha_Rai" }, { "code": null, "e": 37071, "s": 37058, "text": "cpp-iterator" }, { "code": null, "e": 37075, "s": 37071, "text": "STL" }, { "code": null, "e": 37079, "s": 37075, "text": "C++" }, { "code": null, "e": 37083, "s": 37079, "text": "STL" }, { "code": null, "e": 37087, "s": 37083, "text": "CPP" }, { "code": null, "e": 37185, "s": 37087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37194, "s": 37185, "text": "Comments" }, { "code": null, "e": 37207, "s": 37194, "text": "Old Comments" }, { "code": null, "e": 37235, "s": 37207, "text": "Operator Overloading in C++" }, { "code": null, "e": 37259, "s": 37235, "text": "Sorting a vector in C++" }, { "code": null, "e": 37292, "s": 37259, "text": "Friend class and function in C++" }, { "code": null, "e": 37312, "s": 37292, "text": "Polymorphism in C++" }, { "code": null, "e": 37356, "s": 37312, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 37400, "s": 37356, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 37436, "s": 37400, "text": "Convert string to char array in C++" }, { "code": null, "e": 37487, "s": 37436, "text": "new and delete operators in C++ for dynamic memory" }, { "code": null, "e": 37506, "s": 37487, "text": "Destructors in C++" } ]
Understanding Axes and Dimensions | Numpy | Pandas | by Shiva Verma | Towards Data Science
I am going to explain a really basic but important topic, Axes and Dimensions. Many people find it quite confusing, especially using axis while applying a function on multi-dimensional data. Axis or dimensions is a very generic concept. Whether you are handling data in Numpy, Pandas, TensorFlow, or another library, you have to encounter it frequently. And the concepts I am going to explain will be common across all these libraries. In simple words, the Axis is something that represents the dimension of data. Let’s go through various examples to understand it at its core. A Scalar is zero-dimensional data. It has no dimensions or axis. 4 A Vector is one-dimensional data. Vector is a collection of Scalars. Vector has a shape (N,) , where N is the number of scalars in it. [1,2,3,4] The vector has one axis since it is one dimensional. So you can only apply a function across axis-0. Axes are always 0 indexed. np.sum([1,2,3,4], axis=0)>> 10 A Matrix is an example of two-dimensional data. Matrix is a collection of vectors and has a shape of (N,M) , where N is the number of vectors in it and M is the number of scalars in each vector. The shape of the following example matrix would be(2,3). [[1,2,3], [4,5,6]] Matrix is a 2-dimensional data so it has 2 axes. Let’s see how to apply a Sum function along both axes. Taking sum across axis-0 means we are summing all vectors together. data = [[1,2,3],[4,5,6]]np.sum(data, axis=0)>> [5, 7, 9] Taking sum across axis-1 means, we are summing all scalars inside a vector. data = [[1,2,3],[4,5,6]]np.sum(data, axis=1)>> [6, 15] You can also choose to not provide any axis in the arguments. Doing so you will get a sum of all elements together. Means function is applied to all the elements present in the data irrespective of the axis. data = [[1,2,3],[4,5,6]]np.sum(data)>> [21] Similarly, 3D data is a collection of 2D data-points(matrix). The shape of 3D data would be (N,M,P). There would be N matrices of shape (M,P). The shape of the following 3-dimensional data would be(2,2,3). [[[1,1,1], [3,3,3]], [[2,2,2], [4,4,4]]] Applying sum function across axis-0 means you are summing all matrices together. Applying sum function across axis-1 means you are summing all vectors inside each metrics. Applying sum function across axis-2 means you are summing all scalars inside each Vector. Let’s extend this concept for any number of dimension. A data with n dimension would be having the following shape. (N1, N2, N3 ..... Nn) There are N1 data-points of shape (N2, N3 .. Nn) along axis-0. Applying a function across axis-0 means you are performing computation between these N1 data-points. Each data-point along axis-0 will have N2 data-points of shape (N3, N4 .. Nn). These N2 data-points would be considered along axis-1. Applying a function across axis-1 means you are performing computation between these N2 data-points. Similarly, it goes on. You can use negative indexing for axis as well. axis -1 would be the last axis and axis -2 would be the second last axis. We were applying the functions within a single datapoint. Let’s see what axis means when we apply a function between multiple data points. Let’s look at the following example, where we are applying a Sum function on 2 distinct datapoints across axis-0. data1 = [1,2,3]data2 = [4,5,6]np.sum((data1, data2), axis=0)>> [5, 7, 9] These data points will be treated as a single data point with a shape of (2,3) as following since there are 2 vectors of length 3. [[1,2,3],[4,5,6]] Similarly, if there are N distinct data points, you can think of it as a combined single data-points and apply any function as you are applying within a single datapoint. Similarly in Pandas, you can handle Series as 1 Dimensional data and Dataframe as 2 Dimensional data. For example, in Dataframe, rows are considered along axis-0 and columns along axis-1. Applying any function across axis-0 means you are performing computation between all rows and applying a function across axis-1 means you are performing computation between all columns. In this blog, I took an example of Sum function, but there are many more functions you would be performing using axis. This blog is written to build your foundation towards axis and dimension. You would be getting better on it as you would be practicing more and more.
[ { "code": null, "e": 362, "s": 171, "text": "I am going to explain a really basic but important topic, Axes and Dimensions. Many people find it quite confusing, especially using axis while applying a function on multi-dimensional data." }, { "code": null, "e": 607, "s": 362, "text": "Axis or dimensions is a very generic concept. Whether you are handling data in Numpy, Pandas, TensorFlow, or another library, you have to encounter it frequently. And the concepts I am going to explain will be common across all these libraries." }, { "code": null, "e": 749, "s": 607, "text": "In simple words, the Axis is something that represents the dimension of data. Let’s go through various examples to understand it at its core." }, { "code": null, "e": 814, "s": 749, "text": "A Scalar is zero-dimensional data. It has no dimensions or axis." }, { "code": null, "e": 816, "s": 814, "text": "4" }, { "code": null, "e": 951, "s": 816, "text": "A Vector is one-dimensional data. Vector is a collection of Scalars. Vector has a shape (N,) , where N is the number of scalars in it." }, { "code": null, "e": 961, "s": 951, "text": "[1,2,3,4]" }, { "code": null, "e": 1089, "s": 961, "text": "The vector has one axis since it is one dimensional. So you can only apply a function across axis-0. Axes are always 0 indexed." }, { "code": null, "e": 1120, "s": 1089, "text": "np.sum([1,2,3,4], axis=0)>> 10" }, { "code": null, "e": 1315, "s": 1120, "text": "A Matrix is an example of two-dimensional data. Matrix is a collection of vectors and has a shape of (N,M) , where N is the number of vectors in it and M is the number of scalars in each vector." }, { "code": null, "e": 1372, "s": 1315, "text": "The shape of the following example matrix would be(2,3)." }, { "code": null, "e": 1391, "s": 1372, "text": "[[1,2,3], [4,5,6]]" }, { "code": null, "e": 1495, "s": 1391, "text": "Matrix is a 2-dimensional data so it has 2 axes. Let’s see how to apply a Sum function along both axes." }, { "code": null, "e": 1563, "s": 1495, "text": "Taking sum across axis-0 means we are summing all vectors together." }, { "code": null, "e": 1620, "s": 1563, "text": "data = [[1,2,3],[4,5,6]]np.sum(data, axis=0)>> [5, 7, 9]" }, { "code": null, "e": 1696, "s": 1620, "text": "Taking sum across axis-1 means, we are summing all scalars inside a vector." }, { "code": null, "e": 1751, "s": 1696, "text": "data = [[1,2,3],[4,5,6]]np.sum(data, axis=1)>> [6, 15]" }, { "code": null, "e": 1959, "s": 1751, "text": "You can also choose to not provide any axis in the arguments. Doing so you will get a sum of all elements together. Means function is applied to all the elements present in the data irrespective of the axis." }, { "code": null, "e": 2003, "s": 1959, "text": "data = [[1,2,3],[4,5,6]]np.sum(data)>> [21]" }, { "code": null, "e": 2146, "s": 2003, "text": "Similarly, 3D data is a collection of 2D data-points(matrix). The shape of 3D data would be (N,M,P). There would be N matrices of shape (M,P)." }, { "code": null, "e": 2209, "s": 2146, "text": "The shape of the following 3-dimensional data would be(2,2,3)." }, { "code": null, "e": 2252, "s": 2209, "text": "[[[1,1,1], [3,3,3]], [[2,2,2], [4,4,4]]]" }, { "code": null, "e": 2333, "s": 2252, "text": "Applying sum function across axis-0 means you are summing all matrices together." }, { "code": null, "e": 2424, "s": 2333, "text": "Applying sum function across axis-1 means you are summing all vectors inside each metrics." }, { "code": null, "e": 2514, "s": 2424, "text": "Applying sum function across axis-2 means you are summing all scalars inside each Vector." }, { "code": null, "e": 2630, "s": 2514, "text": "Let’s extend this concept for any number of dimension. A data with n dimension would be having the following shape." }, { "code": null, "e": 2652, "s": 2630, "text": "(N1, N2, N3 ..... Nn)" }, { "code": null, "e": 2816, "s": 2652, "text": "There are N1 data-points of shape (N2, N3 .. Nn) along axis-0. Applying a function across axis-0 means you are performing computation between these N1 data-points." }, { "code": null, "e": 3051, "s": 2816, "text": "Each data-point along axis-0 will have N2 data-points of shape (N3, N4 .. Nn). These N2 data-points would be considered along axis-1. Applying a function across axis-1 means you are performing computation between these N2 data-points." }, { "code": null, "e": 3074, "s": 3051, "text": "Similarly, it goes on." }, { "code": null, "e": 3196, "s": 3074, "text": "You can use negative indexing for axis as well. axis -1 would be the last axis and axis -2 would be the second last axis." }, { "code": null, "e": 3335, "s": 3196, "text": "We were applying the functions within a single datapoint. Let’s see what axis means when we apply a function between multiple data points." }, { "code": null, "e": 3449, "s": 3335, "text": "Let’s look at the following example, where we are applying a Sum function on 2 distinct datapoints across axis-0." }, { "code": null, "e": 3522, "s": 3449, "text": "data1 = [1,2,3]data2 = [4,5,6]np.sum((data1, data2), axis=0)>> [5, 7, 9]" }, { "code": null, "e": 3653, "s": 3522, "text": "These data points will be treated as a single data point with a shape of (2,3) as following since there are 2 vectors of length 3." }, { "code": null, "e": 3671, "s": 3653, "text": "[[1,2,3],[4,5,6]]" }, { "code": null, "e": 3842, "s": 3671, "text": "Similarly, if there are N distinct data points, you can think of it as a combined single data-points and apply any function as you are applying within a single datapoint." }, { "code": null, "e": 3944, "s": 3842, "text": "Similarly in Pandas, you can handle Series as 1 Dimensional data and Dataframe as 2 Dimensional data." }, { "code": null, "e": 4216, "s": 3944, "text": "For example, in Dataframe, rows are considered along axis-0 and columns along axis-1. Applying any function across axis-0 means you are performing computation between all rows and applying a function across axis-1 means you are performing computation between all columns." } ]
Detection of a specific color(blue here) using OpenCV with Python?
For many people, image processing may seem like a scary and daunting task but it is not as hard as many people thought it is. In this tutorial we’ll be doing basic color detection in openCv with python. We represent colors on a computers by color-space or color models which basically describes range of colors as tuples of numbers. Instead of going for each color, we’ll discuss most common color-space we use .i.e. RGB(Red, Green, Blue) and HSV (Hue, Saturation, Value). RGB basically describes color as a tuple of three components. Each component can take a value between 0 and 255, where the tuple (0, 0, 0) represents black and (255, 255, 255) represents white. For example, if we were to show a pure blue pixel on-screen, then the R value would be 0, the G value would be 0, and the B value would be 255. Below are a few more examples of colors in RGB: With HSV, a pixel is also represented by 3 parameters, but it is instead Hue, Saturation and Value. However, unlike RGB, HSV does not use the primary color to represent a pixel. Instead, it uses hue, which is the color or shade of the pixel. The saturation is the intensity of the color, where a saturation of 0 represent 0 and a saturation of 255 is maximum intensity.Value will tell how bright or dark the color is. So let’s first download the image with which we will be working with, Now that we have got the colors image, we can start the fun part. Just open your favourite python text editor or IDE and let’s get started. import cv2 import numpy as np import imutils img = cv2.imread('color2.jpg') In above line of code, first two lines handle all the imports. In third line, I’m importing imutils module, which helps in resizing images and finding the range of colors. In line 4 we’ve open the image. hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) Now we have convert the image to an hsv image because hsv helps to differentiate intensity from color. lower_range = np.array([110,50,50]) upper_range = np.array([130,255,255]) Now we define the upper and lower limit of the blue we want to detect. To find these limit we can use the range-detector script in the imutils library. We put these values into a NumPy array. mask = cv2.inRange(hsv, lower_range, upper_range) Here we are actually creating a mask with the specified blue. The mask simply represent a specific part of the image. In this case, we are checking through the hsv image, and checking for colors that are between the lower-range and upper-range. The areas that match will an image set to the mask variable. cv2.imshow('image', img) cv2.imshow('mask', mask) while(True): k = cv2.waitKey(5) & 0xFF if k == 27: break cv2.destroyAllWindows() Finally, we can show the original and mask image side by side to see the difference. If you want to understand what 0xFF means in the code read this. The code then waits for the user to hit the ‘Esc’ button which will quit it and destroy all the windows to cleanup. import cv2 import numpy as np import imutils img = cv2.imread('color2.jpg') hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) lower_range = np.array([110,50,50]) upper_range = np.array([130,255,255]) mask = cv2.inRange(hsv, lower_range, upper_range) cv2.imshow('image', img) cv2.imshow('mask', mask) while(True): k = cv2.waitKey(5) & 0xFF if k == 27: break cv2.destroyAllWindows() In above, we see there are couples of black spots in the mask, that is the noise.
[ { "code": null, "e": 1265, "s": 1062, "text": "For many people, image processing may seem like a scary and daunting task but it is not as hard as many people thought it is. In this tutorial we’ll be doing basic color detection in openCv with python." }, { "code": null, "e": 1395, "s": 1265, "text": "We represent colors on a computers by color-space or color models which basically describes range of colors as tuples of numbers." }, { "code": null, "e": 1535, "s": 1395, "text": "Instead of going for each color, we’ll discuss most common color-space we use .i.e. RGB(Red, Green, Blue) and HSV (Hue, Saturation, Value)." }, { "code": null, "e": 1873, "s": 1535, "text": "RGB basically describes color as a tuple of three components. Each component can take a value between 0 and 255, where the tuple (0, 0, 0) represents black and (255, 255, 255) represents white. For example, if we were to show a pure blue pixel on-screen, then the R value would be 0, the G value would be 0, and the B value would be 255." }, { "code": null, "e": 1921, "s": 1873, "text": "Below are a few more examples of colors in RGB:" }, { "code": null, "e": 2163, "s": 1921, "text": "With HSV, a pixel is also represented by 3 parameters, but it is instead Hue, Saturation and Value. However, unlike RGB, HSV does not use the primary color to represent a pixel. Instead, it uses hue, which is the color or shade of the pixel." }, { "code": null, "e": 2340, "s": 2163, "text": "The saturation is the intensity of the color, where a saturation of 0 represent 0 and a saturation of 255 is maximum intensity.Value will tell how bright or dark the color is." }, { "code": null, "e": 2410, "s": 2340, "text": "So let’s first download the image with which we will be working with," }, { "code": null, "e": 2550, "s": 2410, "text": "Now that we have got the colors image, we can start the fun part. Just open your favourite python text editor or IDE and let’s get started." }, { "code": null, "e": 2626, "s": 2550, "text": "import cv2\nimport numpy as np\nimport imutils\nimg = cv2.imread('color2.jpg')" }, { "code": null, "e": 2830, "s": 2626, "text": "In above line of code, first two lines handle all the imports. In third line, I’m importing imutils module, which helps in resizing images and finding the range of colors. In line 4 we’ve open the image." }, { "code": null, "e": 2873, "s": 2830, "text": "hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)" }, { "code": null, "e": 2976, "s": 2873, "text": "Now we have convert the image to an hsv image because hsv helps to differentiate intensity from color." }, { "code": null, "e": 3050, "s": 2976, "text": "lower_range = np.array([110,50,50])\nupper_range = np.array([130,255,255])" }, { "code": null, "e": 3242, "s": 3050, "text": "Now we define the upper and lower limit of the blue we want to detect. To find these limit we can use the range-detector script in the imutils library. We put these values into a NumPy array." }, { "code": null, "e": 3292, "s": 3242, "text": "mask = cv2.inRange(hsv, lower_range, upper_range)" }, { "code": null, "e": 3598, "s": 3292, "text": "Here we are actually creating a mask with the specified blue. The mask simply represent a specific part of the image. In this case, we are checking through the hsv image, and checking for colors that are between the lower-range and upper-range. The areas that match will an image set to the mask variable." }, { "code": null, "e": 3743, "s": 3598, "text": "cv2.imshow('image', img)\ncv2.imshow('mask', mask)\n\nwhile(True):\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n\ncv2.destroyAllWindows()" }, { "code": null, "e": 4009, "s": 3743, "text": "Finally, we can show the original and mask image side by side to see the difference. If you want to understand what 0xFF means in the code read this. The code then waits for the user to hit the ‘Esc’ button which will quit it and destroy all the windows to cleanup." }, { "code": null, "e": 4402, "s": 4009, "text": "import cv2\nimport numpy as np\nimport imutils\n\nimg = cv2.imread('color2.jpg')\n\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\nlower_range = np.array([110,50,50])\nupper_range = np.array([130,255,255])\n\nmask = cv2.inRange(hsv, lower_range, upper_range)\n\ncv2.imshow('image', img)\ncv2.imshow('mask', mask)\n\nwhile(True):\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n\ncv2.destroyAllWindows()" }, { "code": null, "e": 4484, "s": 4402, "text": "In above, we see there are couples of black spots in the mask, that is the noise." } ]
How to use MySQL Date functions with WHERE clause?
By using the WHERE clause with any of the MySQL date functions, the query will filter the rows based on the condition provided in the WHERE clause. To understand it, consider the data from ‘Collegedetail’ table as follows mysql> Select * from Collegedetail; +------+---------+------------+ | ID | Country | Estb | +------+---------+------------+ | 111 | INDIA | 2010-05-01 | | 130 | INDIA | 1995-10-25 | | 139 | USA | 1994-09-25 | | 1539 | UK | 2001-07-23 | | 1545 | Russia | 2010-07-30 | +------+---------+------------+ 5 rows in set (0.00 sec) Now, suppose if want to get the details of only those colleges which established in the year 2010 then following query, having WHERE clause with YEAR(), can be used − mysql> Select * from Collegedetail WHERE YEAR(Estb) = '2010'; +------+---------+------------+ | ID | Country | Estb | +------+---------+------------+ | 111 | INDIA | 2010-05-01 | | 1545 | Russia | 2010-07-30 | +------+---------+------------+ 2 rows in set (0.07 sec)
[ { "code": null, "e": 1284, "s": 1062, "text": "By using the WHERE clause with any of the MySQL date functions, the query will filter the rows based on the condition provided in the WHERE clause. To understand it, consider the data from ‘Collegedetail’ table as follows" }, { "code": null, "e": 1633, "s": 1284, "text": "mysql> Select * from Collegedetail;\n+------+---------+------------+\n| ID | Country | Estb |\n+------+---------+------------+\n| 111 | INDIA | 2010-05-01 |\n| 130 | INDIA | 1995-10-25 |\n| 139 | USA | 1994-09-25 |\n| 1539 | UK | 2001-07-23 |\n| 1545 | Russia | 2010-07-30 |\n+------+---------+------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 1800, "s": 1633, "text": "Now, suppose if want to get the details of only those colleges which established in the year 2010 then following query, having WHERE clause with YEAR(), can be used −" }, { "code": null, "e": 2079, "s": 1800, "text": "mysql> Select * from Collegedetail WHERE YEAR(Estb) = '2010';\n+------+---------+------------+\n| ID | Country | Estb |\n+------+---------+------------+\n| 111 | INDIA | 2010-05-01 |\n| 1545 | Russia | 2010-07-30 |\n+------+---------+------------+\n2 rows in set (0.07 sec)" } ]
C++ Algorithm Library - count() Function
The C++ function std::algorithm::count() returns the number of occurrences of value in range. This function uses operator == for comparison. Following is the declaration for std::algorithm::count() function form std::algorithm header. template <class InputIterator, class T> typename iterator_traits<InputIterator>::difference_type count (InputIterator first, InputIterator last, const T& val); first − Input iterators to the initial positions of the searched sequence. first − Input iterators to the initial positions of the searched sequence. last − Input iterators to the final positions of the searched sequence. last − Input iterators to the final positions of the searched sequence. val − Value to search for in the range. val − Value to search for in the range. Returns the number of elements in the range of first to last. Throws an exception if either element assignment or an operation on an iterator throws exception. Please note that invalid parameters cause undefined behavior. Linear in the distance between first to last. The following example shows the usage of std::algorithm::count() function. #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(void) { vector<int> v = {1, 3, 3, 3, 3}; int cnt; cnt = count(v.begin(), v.end(), 3); cout << "Number 3 occurs " << cnt << " times." << endl; return 0; } Let us compile and run the above program, this will produce the following result − Number 3 occurs 4 times. Print Add Notes Bookmark this page
[ { "code": null, "e": 2744, "s": 2603, "text": "The C++ function std::algorithm::count() returns the number of occurrences of value in range. This function uses operator == for comparison." }, { "code": null, "e": 2838, "s": 2744, "text": "Following is the declaration for std::algorithm::count() function form std::algorithm header." }, { "code": null, "e": 2999, "s": 2838, "text": "template <class InputIterator, class T>\ntypename iterator_traits<InputIterator>::difference_type\ncount (InputIterator first, InputIterator last, const T& val);\n" }, { "code": null, "e": 3074, "s": 2999, "text": "first − Input iterators to the initial positions of the searched sequence." }, { "code": null, "e": 3149, "s": 3074, "text": "first − Input iterators to the initial positions of the searched sequence." }, { "code": null, "e": 3221, "s": 3149, "text": "last − Input iterators to the final positions of the searched sequence." }, { "code": null, "e": 3293, "s": 3221, "text": "last − Input iterators to the final positions of the searched sequence." }, { "code": null, "e": 3333, "s": 3293, "text": "val − Value to search for in the range." }, { "code": null, "e": 3373, "s": 3333, "text": "val − Value to search for in the range." }, { "code": null, "e": 3435, "s": 3373, "text": "Returns the number of elements in the range of first to last." }, { "code": null, "e": 3533, "s": 3435, "text": "Throws an exception if either element assignment or an operation on an iterator throws exception." }, { "code": null, "e": 3595, "s": 3533, "text": "Please note that invalid parameters cause undefined behavior." }, { "code": null, "e": 3641, "s": 3595, "text": "Linear in the distance between first to last." }, { "code": null, "e": 3716, "s": 3641, "text": "The following example shows the usage of std::algorithm::count() function." }, { "code": null, "e": 3979, "s": 3716, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v = {1, 3, 3, 3, 3};\n int cnt;\n\n cnt = count(v.begin(), v.end(), 3);\n\n cout << \"Number 3 occurs \" << cnt << \" times.\" << endl;\n\n return 0;\n}" }, { "code": null, "e": 4062, "s": 3979, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4088, "s": 4062, "text": "Number 3 occurs 4 times.\n" }, { "code": null, "e": 4095, "s": 4088, "text": " Print" }, { "code": null, "e": 4106, "s": 4095, "text": " Add Notes" } ]
Check replication type in MySQL?
To check replication type, you can use SHOW GLOBAL VARIABLES command. The syntax is as follows − SHOW GLOBAL VARIABLES LIKE 'binlog_format'; The above syntax returns either ROW, MIXED or STATEMENT. The default resultant is ROW. Now you can implement the above syntax to check replication type. The query is as follows − mysql> SHOW GLOBAL VARIABLES LIKE 'binlog_format'; Here is the output − +---------------+-------+ | Variable_name | Value | +---------------+-------+ | binlog_format | ROW | +---------------+-------+ 1 row in set (0.10 sec) Here is the query to switch from ROW to STATEMENT − mysql> SET GLOBAL binlog_format = 'STATEMENT'; Query OK, 0 rows affected (0.04 sec) Now check the replication type once again. The query is as follows − mysql> SHOW GLOBAL VARIABLES LIKE 'binlog_format'; Here is the output − +---------------+-----------+ | Variable_name | Value | +---------------+-----------+ | binlog_format | STATEMENT | +---------------+-----------+ 1 row in set (0.01 sec) Now the binlog_format is STATEMENT. You can change from STATEMENT to MIXED or MIXED to ROW and so on. Change by session also. The query is as follows − mysql> SET SESSION binlog_format = 'ROW'; Query OK, 0 rows affected (0.00 sec) Now check the value of binlog_format once again. The query is as follows − mysql> SHOW VARIABLES LIKE 'binlog_format'; The following is the output − +---------------+-------+ | Variable_name | Value | +---------------+-------+ | binlog_format | ROW | +---------------+-------+ 1 row in set (0.04 sec)
[ { "code": null, "e": 1159, "s": 1062, "text": "To check replication type, you can use SHOW GLOBAL VARIABLES command. The syntax is as follows −" }, { "code": null, "e": 1203, "s": 1159, "text": "SHOW GLOBAL VARIABLES LIKE 'binlog_format';" }, { "code": null, "e": 1290, "s": 1203, "text": "The above syntax returns either ROW, MIXED or STATEMENT. The default resultant is ROW." }, { "code": null, "e": 1382, "s": 1290, "text": "Now you can implement the above syntax to check replication type. The query is as follows −" }, { "code": null, "e": 1433, "s": 1382, "text": "mysql> SHOW GLOBAL VARIABLES LIKE 'binlog_format';" }, { "code": null, "e": 1454, "s": 1433, "text": "Here is the output −" }, { "code": null, "e": 1608, "s": 1454, "text": "+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| binlog_format | ROW |\n+---------------+-------+\n1 row in set (0.10 sec)" }, { "code": null, "e": 1660, "s": 1608, "text": "Here is the query to switch from ROW to STATEMENT −" }, { "code": null, "e": 1744, "s": 1660, "text": "mysql> SET GLOBAL binlog_format = 'STATEMENT';\nQuery OK, 0 rows affected (0.04 sec)" }, { "code": null, "e": 1813, "s": 1744, "text": "Now check the replication type once again. The query is as follows −" }, { "code": null, "e": 1864, "s": 1813, "text": "mysql> SHOW GLOBAL VARIABLES LIKE 'binlog_format';" }, { "code": null, "e": 1885, "s": 1864, "text": "Here is the output −" }, { "code": null, "e": 2059, "s": 1885, "text": "+---------------+-----------+\n| Variable_name | Value |\n+---------------+-----------+\n| binlog_format | STATEMENT |\n+---------------+-----------+\n1 row in set (0.01 sec)" }, { "code": null, "e": 2095, "s": 2059, "text": "Now the binlog_format is STATEMENT." }, { "code": null, "e": 2161, "s": 2095, "text": "You can change from STATEMENT to MIXED or MIXED to ROW and so on." }, { "code": null, "e": 2211, "s": 2161, "text": "Change by session also. The query is as follows −" }, { "code": null, "e": 2290, "s": 2211, "text": "mysql> SET SESSION binlog_format = 'ROW';\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 2365, "s": 2290, "text": "Now check the value of binlog_format once again. The query is as follows −" }, { "code": null, "e": 2409, "s": 2365, "text": "mysql> SHOW VARIABLES LIKE 'binlog_format';" }, { "code": null, "e": 2439, "s": 2409, "text": "The following is the output −" }, { "code": null, "e": 2593, "s": 2439, "text": "+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| binlog_format | ROW |\n+---------------+-------+\n1 row in set (0.04 sec)" } ]
Angular Google Charts - Quick Guide
Google Charts is a pure JavaScript based charting library meant to enhance web applications by adding interactive charting capability. It supports a wide range of charts. Charts are drawn using SVG in standard browsers like Chrome, Firefox, Safari, Internet Explorer(IE). In legacy IE 6, VML is used to draw the graphics. angular-google-charts is a open source angular based wrapper for Google Charts to provides an elegant and feature rich Google Charts visualizations within an Angular application and can be used along with Angular components seamlessly. There are chapters discussing all the basic components of Google Charts with suitable examples within a Angular application. Following are the salient features of Google Charts library. Compatability − Works seemlessly on all major browsers and mobile platforms like android and iOS. Compatability − Works seemlessly on all major browsers and mobile platforms like android and iOS. Multitouch Support − Supports multitouch on touch screen based platforms like android and iOS. Ideal for iPhone/iPad and android based smart phones/ tablets. Multitouch Support − Supports multitouch on touch screen based platforms like android and iOS. Ideal for iPhone/iPad and android based smart phones/ tablets. Free to Use − Open source and is free to use for non-commercial purpose. Free to Use − Open source and is free to use for non-commercial purpose. Lightweight − loader.js core library, is extremely lightweight library. Lightweight − loader.js core library, is extremely lightweight library. Simple Configurations − Uses json to define various configuration of the charts and very easy to learn and use. Simple Configurations − Uses json to define various configuration of the charts and very easy to learn and use. Dynamic − Allows to modify chart even after chart generation. Dynamic − Allows to modify chart even after chart generation. Multiple axes − Not restricted to x, y axis. Supports multiple axis on the charts. Multiple axes − Not restricted to x, y axis. Supports multiple axis on the charts. Configurable tooltips − Tooltip comes when a user hover over any point on a charts. googlecharts provides tooltip inbuilt formatter or callback formatter to control the tooltip programmatically. Configurable tooltips − Tooltip comes when a user hover over any point on a charts. googlecharts provides tooltip inbuilt formatter or callback formatter to control the tooltip programmatically. DateTime support − Handle date time specially. Provides numerous inbuilt controls over date wise categories. DateTime support − Handle date time specially. Provides numerous inbuilt controls over date wise categories. Print − Print chart using web page. Print − Print chart using web page. External data − Supports loading data dynamically from server. Provides control over data using callback functions. External data − Supports loading data dynamically from server. Provides control over data using callback functions. Text Rotation − Supports rotation of labels in any direction. Text Rotation − Supports rotation of labels in any direction. Google Charts library provides following types of charts: Line Charts Used to draw line/spline based charts. Area Charts Used to draw area wise charts. Pie Charts Used to draw pie charts. Sankey Charts, Scatter Charts, Stepped area charts, Table, Timelines, TreeMap, Trendlines Used to draw scattered charts. Bubble Charts Used to draw bubble based charts. Dynamic Charts Used to draw dynamic charts where user can modify charts. Combinations Used to draw combinations of variety of charts. 3D Charts Used to draw 3D charts. Angular Gauges Used to draw speedometer type charts. Heat Maps Used to draw heat maps. Tree Maps Used to draw tree maps. In next chapters, we're going to discuss each type of above mentioned charts in details with examples. Google Charts is open source and is free to use. Follow the link − Terms of Service. This tutorial will guide you on how to prepare a development environment to start your work with Google Charts and Angular Framework. In this chapter, we will discuss the Environment Setup required for Angular 6. To install Angular 6, we require the following − Nodejs Npm Angular CLI IDE for writing your code Nodejs has to be greater than 8.11 and npm has to be greater than 5.6. To check if nodejs is installed on your system, type node -v in the terminal. This will help you see the version of nodejs currently installed on your system. C:\>node -v v8.11.3 If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS. Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm -v in the terminal. It should display the version of the npm. C:\>npm -v 5.6.0 Angular 6 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command. Type npm install -g @angular/cli, to install angular cli on your system. You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc. Run the following command to install Google Charts Wrapper module in the project created. googleChartsApp> npm angular-google-charts + [email protected] added 2 packages in 20.526s Add the following entry in app.module.ts file import { GoogleChartsModule } from 'angular-google-charts'; imports: [ ... GoogleChartsModule ], In this chapter, we will showcase the configuration required to draw a chart using the Google Chart API in Angular. Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter − Following is the content of the modified module descriptor app.module.ts. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { GoogleChartsModule } from 'angular-google-charts'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule,GoogleChartsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Following is the content of the modified HTML host file app.component.html. <google-chart #chart [title]="title" [type]="type" [data]="data" [columnNames]="columnNames" [options]="options" [width]="width" [height]="height"> </google-chart> We'll see the updated app.component.ts in the end after understanding configurations. title = 'Browser market shares at a specific website, 2014'; type='PieChart'; Configure the data to be displayed on the chart. data = [ ['Firefox', 45.0], ['IE', 26.8], ['Chrome', 12.8], ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ]; Configure the column names to be displayed. columnNames = ['Browser', 'Percentage']; Configure the other options. options = { colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'], is3D: true }; Consider the following example to further understand the Configuration Syntax − app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Browser market shares at a specific website, 2014'; type = 'PieChart'; data = [ ['Firefox', 45.0], ['IE', 26.8], ['Chrome', 12.8], ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ]; columnNames = ['Browser', 'Percentage']; options = { }; width = 550; height = 400; } Verify the result. Area charts are used to draw area based charts. In this section we're going to discuss following types of area based charts. Basic area chart Area chart having negative values. Chart having areas stacked over one another. Chart with missing points in the data. Bar charts are used to draw bar based charts. In this section we're going to discuss following types of bar based charts. Basic bar chart Grouped Bar chart. Bar chart having bar stacked over one another. Bar chart with negative stack. Bubble charts are used to draw bubble based charts. In this section we're going to discuss following types of bubble based charts. Basic bubble chart. Bubble chart with data labels. Candlestick charts are used to show opening and closing value over a value variance and are normally used to represent stocks. In this section we're going to discuss following types of candlestick based charts. Basic Candlestick chart. Customized Candlestick Chart. Colummn charts are used to draw colummn based charts. In this section we're going to discuss following types of colummn based charts. Basic colummn chart Grouped Colummn chart. Colummn chart having colummn stacked over one another. Colummn chart with negative stack. Combination chart helps in rendering each series as a different marker type from the following list: line, area, bars, candlesticks, and stepped area. To assign a default marker type for series, use the seriesType property. Series property is to be used to specify properties of each series individually. Following is an example of a Column Chart showing differences. We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Column Chart showing differences. We've used ComboChart class to show a Combination Chart. type='ComboChart'; app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Fruits distribution'; type = 'ComboChart'; data = [ ["Apples", 3, 2, 2.5], ["Oranges",2, 3, 2.5], ["Pears", 1, 5, 3], ["Bananas", 3, 9, 6], ["Plums", 4, 2, 3] ]; columnNames = ['Fruits', 'Jane','Jone','Average']; options = { hAxis: { title: 'Person' }, vAxis:{ title: 'Fruits' }, seriesType: 'bars', series: {2: {type: 'line'}} }; width = 550; height = 400; } Verify the result. A histogram is a chart that groups numeric data into buckets, displaying the buckets as segmented columns. They're used to depict the distribution of a dataset as how often values fall into ranges. Google Charts automatically chooses the number of buckets for you. All buckets are equal width and have a height proportional to the number of data points in the bucket. Histograms are similar to column charts in other aspects. In this section we're going to discuss following types of histogram based charts. Basic Histogram chart. Customized Color of Histrogram Chart. Customized Buckets of Histrogram Chart. Histrogram Chart having multiple series. Line charts are used to draw line based charts. In this section we're going to discuss following types of line based charts. Basic line chart. Chart with visible data points. Chart with customized background color. Chart with customized line color. Chart with customized axis and tick labels. Line charts showing crosshairs at data point on selection. Chart with customized line color. Chart with smooth curve lines. A Google Map Chart uses Google Maps API to display Map. Data values are displayed as markers on the map. Data values may be coordinates (lat-long pairs) or actual addresses. The map will be scaled accordingly so that it includes all the identified points. Basic Google Map. Map having locations specified using Latitude and Longitude. Following is an example of a Organization Chart. Organization chart helps in rendering a hierarchy of nodes, used to portray superior/subordinate relationships in an organization. For example, A family tree is a type of org chart. We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Organization Chart. We've used OrgChart class to show a Organization Chart. type='OrgChart'; app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = ''; type = 'OrgChart'; data = [ [{v:'Mike', f:'Mike<div style="color:red; font-style:italic">President</div>'}, '', 'The President'], [{v:'Jim', f:'Jim<div style="color:red; font-style:italic">Vice President</div>'}, 'Mike', 'VP'], ['Alice', 'Mike', ''], ['Bob', 'Jim', 'Bob Sponge'], ['Carol', 'Bob', ''] ]; columnNames = ["Name","Manager","Tooltip"]; options = { allowHtml: true }; width = 550; height = 400; } Verify the result. Pie charts are used to draw pie based charts. In this section we're going to discuss following types of pie based charts. Basic pie chart. Donut Chart. 3D Pie chart. Pie chart with exploded slices. A sankey chart is a visualization tool and is used to depict a flow from one set of values to another. Connected objects are called nodes and the connections are called links. Sankeys are used to show a many-to-many mapping between two domains or multiple paths through a set of stages. Basic Sankey Chart. Multilevel Sankey Chart. Customized Sankey Chart. Following is an example of a Scatter Chart. We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Scatter Chart. We've used ScatterChart class to show a Scatter chart. type = 'ScatterChart'; app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Age vs Weight'; type='ScatterChart'; data = [ [8,12], [4, 5.5], [11,14], [4,5], [3,3.5], [6.5,7] ]; columnNames = ['Age', 'Weight']; options = { }; width = 550; height = 400; } Verify the result. A stepped area chart is a step based area chart. We're going to discuss following types of stepped area charts. Basic Stepped Area Chart. Stacked Stepped Area Chart. Table chart helps in rendering a table which can be sorted and paged. Table cells can be formatted using format strings, or by directly inserting HTML as cell values. Numeric values are right-aligned by default; boolean values are displayed as check marks or cross marks. Users can select single rows either with the keyboard or the mouse. Column headers can be used for sorting. The header row remains fixed during scrolling. The table fires events corresponding to user interaction. We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Table Chart. We've used Table class to show a Table chart. type = 'Table'; app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = ""; type = 'Table'; data = [ ['Mike', {v: 10000, f: '$10,000'}, true], ['Jim', {v:8000, f: '$8,000'}, false], ['Alice', {v: 12500, f: '$12,500'}, true], ['Bob', {v: 7000, f: '$7,000'}, true] ]; columnNames = ["Name", "Salary","Full Time Employee"]; options = { alternatingRowStyle:true, showRowNumber:true }; width = 550; height = 400; } Verify the result. TreeMap is a visual representation of a data tree, where each node may have zero or more children, and one parent (except for the root). Each node is displayed as a rectangle, can be sized and colored according to values that we assign. Sizes and colors are valued relative to all other nodes in the graph. Following is an example of a treemap chart. We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a TreeMap Chart. We've used TreeMap class to show a TreeMap chart. type = 'TreeMap'; app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = ''; type='TreeMap'; data = [ ["Global",null,0,0], ["America","Global",0,0], ["Europe","Global",0,0], ["Asia","Global",0,0], ["Australia","Global",0,0], ["Africa","Global",0,0], ["USA","America",52,31], ["Mexico","America",24,12], ["Canada","America",16,-23], ["France","Europe",42,-11], ["Germany","Europe",31,-2], ["Sweden","Europe",22,-13], ["China","Asia",36,4], ["Japan","Asia",20,-12], ["India","Asia",40,63], ["Egypt","Africa",21,0], ["Congo","Africa",10,12], ["Zaire","Africa",8,10], ]; columnNames = ["Location", "Parent","Market trade volume (size)","Market increase/decrease (color)"]; options = { minColor:"#ff7777", midColor:'#ffff77', maxColor:'#77ff77', headerHeight:15, showScale:true }; width = 550; height = 400; } Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2118, "s": 1796, "text": "Google Charts is a pure JavaScript based charting library meant to enhance web applications by adding interactive charting capability. It supports a wide range of charts. Charts are drawn using SVG in standard browsers like Chrome, Firefox, Safari, Internet Explorer(IE). In legacy IE 6, VML is used to draw the graphics." }, { "code": null, "e": 2479, "s": 2118, "text": "angular-google-charts is a open source angular based wrapper for Google Charts to provides an elegant and feature rich Google Charts visualizations within an Angular application and can be used along with Angular components seamlessly. There are chapters discussing all the basic components of Google Charts with suitable examples within a Angular application." }, { "code": null, "e": 2540, "s": 2479, "text": "Following are the salient features of Google Charts library." }, { "code": null, "e": 2638, "s": 2540, "text": "Compatability − Works seemlessly on all major browsers and mobile platforms like android and iOS." }, { "code": null, "e": 2736, "s": 2638, "text": "Compatability − Works seemlessly on all major browsers and mobile platforms like android and iOS." }, { "code": null, "e": 2894, "s": 2736, "text": "Multitouch Support − Supports multitouch on touch screen based platforms like android and iOS. Ideal for iPhone/iPad and android based smart phones/ tablets." }, { "code": null, "e": 3052, "s": 2894, "text": "Multitouch Support − Supports multitouch on touch screen based platforms like android and iOS. Ideal for iPhone/iPad and android based smart phones/ tablets." }, { "code": null, "e": 3125, "s": 3052, "text": "Free to Use − Open source and is free to use for non-commercial purpose." }, { "code": null, "e": 3198, "s": 3125, "text": "Free to Use − Open source and is free to use for non-commercial purpose." }, { "code": null, "e": 3270, "s": 3198, "text": "Lightweight − loader.js core library, is extremely lightweight library." }, { "code": null, "e": 3342, "s": 3270, "text": "Lightweight − loader.js core library, is extremely lightweight library." }, { "code": null, "e": 3454, "s": 3342, "text": "Simple Configurations − Uses json to define various configuration of the charts and very easy to learn and use." }, { "code": null, "e": 3566, "s": 3454, "text": "Simple Configurations − Uses json to define various configuration of the charts and very easy to learn and use." }, { "code": null, "e": 3628, "s": 3566, "text": "Dynamic − Allows to modify chart even after chart generation." }, { "code": null, "e": 3690, "s": 3628, "text": "Dynamic − Allows to modify chart even after chart generation." }, { "code": null, "e": 3773, "s": 3690, "text": "Multiple axes − Not restricted to x, y axis. Supports multiple axis on the charts." }, { "code": null, "e": 3856, "s": 3773, "text": "Multiple axes − Not restricted to x, y axis. Supports multiple axis on the charts." }, { "code": null, "e": 4051, "s": 3856, "text": "Configurable tooltips − Tooltip comes when a user hover over any point on a charts. googlecharts provides tooltip inbuilt formatter or callback formatter to control the tooltip programmatically." }, { "code": null, "e": 4246, "s": 4051, "text": "Configurable tooltips − Tooltip comes when a user hover over any point on a charts. googlecharts provides tooltip inbuilt formatter or callback formatter to control the tooltip programmatically." }, { "code": null, "e": 4355, "s": 4246, "text": "DateTime support − Handle date time specially. Provides numerous inbuilt controls over date wise categories." }, { "code": null, "e": 4464, "s": 4355, "text": "DateTime support − Handle date time specially. Provides numerous inbuilt controls over date wise categories." }, { "code": null, "e": 4500, "s": 4464, "text": "Print − Print chart using web page." }, { "code": null, "e": 4536, "s": 4500, "text": "Print − Print chart using web page." }, { "code": null, "e": 4652, "s": 4536, "text": "External data − Supports loading data dynamically from server. Provides control over data using callback functions." }, { "code": null, "e": 4768, "s": 4652, "text": "External data − Supports loading data dynamically from server. Provides control over data using callback functions." }, { "code": null, "e": 4830, "s": 4768, "text": "Text Rotation − Supports rotation of labels in any direction." }, { "code": null, "e": 4892, "s": 4830, "text": "Text Rotation − Supports rotation of labels in any direction." }, { "code": null, "e": 4950, "s": 4892, "text": "Google Charts library provides following types of charts:" }, { "code": null, "e": 4962, "s": 4950, "text": "Line Charts" }, { "code": null, "e": 5001, "s": 4962, "text": "Used to draw line/spline based charts." }, { "code": null, "e": 5013, "s": 5001, "text": "Area Charts" }, { "code": null, "e": 5044, "s": 5013, "text": "Used to draw area wise charts." }, { "code": null, "e": 5055, "s": 5044, "text": "Pie Charts" }, { "code": null, "e": 5080, "s": 5055, "text": "Used to draw pie charts." }, { "code": null, "e": 5170, "s": 5080, "text": "Sankey Charts, Scatter Charts, Stepped area charts, Table, Timelines, TreeMap, Trendlines" }, { "code": null, "e": 5201, "s": 5170, "text": "Used to draw scattered charts." }, { "code": null, "e": 5215, "s": 5201, "text": "Bubble Charts" }, { "code": null, "e": 5249, "s": 5215, "text": "Used to draw bubble based charts." }, { "code": null, "e": 5264, "s": 5249, "text": "Dynamic Charts" }, { "code": null, "e": 5322, "s": 5264, "text": "Used to draw dynamic charts where user can modify charts." }, { "code": null, "e": 5335, "s": 5322, "text": "Combinations" }, { "code": null, "e": 5383, "s": 5335, "text": "Used to draw combinations of variety of charts." }, { "code": null, "e": 5393, "s": 5383, "text": "3D Charts" }, { "code": null, "e": 5417, "s": 5393, "text": "Used to draw 3D charts." }, { "code": null, "e": 5432, "s": 5417, "text": "Angular Gauges" }, { "code": null, "e": 5470, "s": 5432, "text": "Used to draw speedometer type charts." }, { "code": null, "e": 5480, "s": 5470, "text": "Heat Maps" }, { "code": null, "e": 5504, "s": 5480, "text": "Used to draw heat maps." }, { "code": null, "e": 5514, "s": 5504, "text": "Tree Maps" }, { "code": null, "e": 5538, "s": 5514, "text": "Used to draw tree maps." }, { "code": null, "e": 5641, "s": 5538, "text": "In next chapters, we're going to discuss each type of above mentioned charts in details with examples." }, { "code": null, "e": 5726, "s": 5641, "text": "Google Charts is open source and is free to use. Follow the link − Terms of Service." }, { "code": null, "e": 5988, "s": 5726, "text": "This tutorial will guide you on how to prepare a development environment to start your work with Google Charts and Angular Framework. In this chapter, we will discuss the Environment Setup required for Angular 6. To install Angular 6, we require the following −" }, { "code": null, "e": 5995, "s": 5988, "text": "Nodejs" }, { "code": null, "e": 5999, "s": 5995, "text": "Npm" }, { "code": null, "e": 6011, "s": 5999, "text": "Angular CLI" }, { "code": null, "e": 6037, "s": 6011, "text": "IDE for writing your code" }, { "code": null, "e": 6108, "s": 6037, "text": "Nodejs has to be greater than 8.11 and npm has to be greater than 5.6." }, { "code": null, "e": 6267, "s": 6108, "text": "To check if nodejs is installed on your system, type node -v in the terminal. This will help you see the version of nodejs currently installed on your system." }, { "code": null, "e": 6288, "s": 6267, "text": "C:\\>node -v\nv8.11.3\n" }, { "code": null, "e": 6469, "s": 6288, "text": "If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS." }, { "code": null, "e": 6694, "s": 6469, "text": "Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm -v in the terminal. It should display the version of the npm." }, { "code": null, "e": 6712, "s": 6694, "text": "C:\\>npm -v\n5.6.0\n" }, { "code": null, "e": 6873, "s": 6712, "text": "Angular 6 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command." }, { "code": null, "e": 6946, "s": 6873, "text": "Type npm install -g @angular/cli, to install angular cli on your system." }, { "code": null, "e": 7114, "s": 6946, "text": "You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc." }, { "code": null, "e": 7204, "s": 7114, "text": "Run the following command to install Google Charts Wrapper module in the project created." }, { "code": null, "e": 7307, "s": 7204, "text": "googleChartsApp> npm angular-google-charts\n\n+ [email protected]\nadded 2 packages in 20.526s\n" }, { "code": null, "e": 7353, "s": 7307, "text": "Add the following entry in app.module.ts file" }, { "code": null, "e": 7457, "s": 7353, "text": "import { GoogleChartsModule } from 'angular-google-charts';\n\nimports: [\n ...\n GoogleChartsModule\n]," }, { "code": null, "e": 7573, "s": 7457, "text": "In this chapter, we will showcase the configuration required to draw a chart using the Google Chart API in Angular." }, { "code": null, "e": 7684, "s": 7573, "text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −" }, { "code": null, "e": 7758, "s": 7684, "text": "Following is the content of the modified module descriptor app.module.ts." }, { "code": null, "e": 8159, "s": 7758, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport { GoogleChartsModule } from 'angular-google-charts';\n@NgModule({\n declarations: [\n AppComponent \n ],\n imports: [\n BrowserModule,GoogleChartsModule\n ],\n providers: [], bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 8235, "s": 8159, "text": "Following is the content of the modified HTML host file app.component.html." }, { "code": null, "e": 8420, "s": 8235, "text": "<google-chart #chart\n [title]=\"title\"\n [type]=\"type\"\n [data]=\"data\"\n [columnNames]=\"columnNames\"\n [options]=\"options\"\n [width]=\"width\"\n [height]=\"height\">\n</google-chart>" }, { "code": null, "e": 8506, "s": 8420, "text": "We'll see the updated app.component.ts in the end after understanding configurations." }, { "code": null, "e": 8568, "s": 8506, "text": "title = 'Browser market shares at a specific website, 2014';\n" }, { "code": null, "e": 8586, "s": 8568, "text": "type='PieChart';\n" }, { "code": null, "e": 8636, "s": 8586, "text": "Configure the data to be displayed on the chart. " }, { "code": null, "e": 8767, "s": 8636, "text": "data = [\n ['Firefox', 45.0],\n ['IE', 26.8],\n ['Chrome', 12.8],\n ['Safari', 8.5],\n ['Opera', 6.2],\n ['Others', 0.7] \n];" }, { "code": null, "e": 8811, "s": 8767, "text": "Configure the column names to be displayed." }, { "code": null, "e": 8853, "s": 8811, "text": "columnNames = ['Browser', 'Percentage'];\n" }, { "code": null, "e": 8882, "s": 8853, "text": "Configure the other options." }, { "code": null, "e": 8977, "s": 8882, "text": "options = {\n colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'], is3D: true\n};\n" }, { "code": null, "e": 9057, "s": 8977, "text": "Consider the following example to further understand the Configuration Syntax −" }, { "code": null, "e": 9074, "s": 9057, "text": "app.component.ts" }, { "code": null, "e": 9609, "s": 9074, "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 = 'Browser market shares at a specific website, 2014';\n type = 'PieChart';\n data = [\n ['Firefox', 45.0],\n ['IE', 26.8],\n ['Chrome', 12.8],\n ['Safari', 8.5],\n ['Opera', 6.2],\n ['Others', 0.7] \n ];\n columnNames = ['Browser', 'Percentage'];\n options = { \n };\n width = 550;\n height = 400;\n}" }, { "code": null, "e": 9628, "s": 9609, "text": "Verify the result." }, { "code": null, "e": 9753, "s": 9628, "text": "Area charts are used to draw area based charts. In this section we're going to discuss following types of area based charts." }, { "code": null, "e": 9770, "s": 9753, "text": "Basic area chart" }, { "code": null, "e": 9805, "s": 9770, "text": "Area chart having negative values." }, { "code": null, "e": 9850, "s": 9805, "text": "Chart having areas stacked over one another." }, { "code": null, "e": 9889, "s": 9850, "text": "Chart with missing points in the data." }, { "code": null, "e": 10011, "s": 9889, "text": "Bar charts are used to draw bar based charts. In this section we're going to discuss following types of bar based charts." }, { "code": null, "e": 10027, "s": 10011, "text": "Basic bar chart" }, { "code": null, "e": 10046, "s": 10027, "text": "Grouped Bar chart." }, { "code": null, "e": 10093, "s": 10046, "text": "Bar chart having bar stacked over one another." }, { "code": null, "e": 10124, "s": 10093, "text": "Bar chart with negative stack." }, { "code": null, "e": 10255, "s": 10124, "text": "Bubble charts are used to draw bubble based charts. In this section we're going to discuss following types of bubble based charts." }, { "code": null, "e": 10275, "s": 10255, "text": "Basic bubble chart." }, { "code": null, "e": 10306, "s": 10275, "text": "Bubble chart with data labels." }, { "code": null, "e": 10517, "s": 10306, "text": "Candlestick charts are used to show opening and closing value over a value variance and are normally used to represent stocks. In this section we're going to discuss following types of candlestick based charts." }, { "code": null, "e": 10542, "s": 10517, "text": "Basic Candlestick chart." }, { "code": null, "e": 10572, "s": 10542, "text": "Customized Candlestick Chart." }, { "code": null, "e": 10706, "s": 10572, "text": "Colummn charts are used to draw colummn based charts. In this section we're going to discuss following types of colummn based charts." }, { "code": null, "e": 10726, "s": 10706, "text": "Basic colummn chart" }, { "code": null, "e": 10749, "s": 10726, "text": "Grouped Colummn chart." }, { "code": null, "e": 10804, "s": 10749, "text": "Colummn chart having colummn stacked over one another." }, { "code": null, "e": 10839, "s": 10804, "text": "Colummn chart with negative stack." }, { "code": null, "e": 11207, "s": 10839, "text": "Combination chart helps in rendering each series as a different marker type from the following list: line, area, bars, candlesticks, and stepped area. To assign a default marker type for series, use the seriesType property. Series property is to be used to specify properties of each series individually. Following is an example of a Column Chart showing differences." }, { "code": null, "e": 11381, "s": 11207, "text": "We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Column Chart showing differences." }, { "code": null, "e": 11438, "s": 11381, "text": "We've used ComboChart class to show a Combination Chart." }, { "code": null, "e": 11458, "s": 11438, "text": "type='ComboChart';\n" }, { "code": null, "e": 11475, "s": 11458, "text": "app.component.ts" }, { "code": null, "e": 12148, "s": 11475, "text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Fruits distribution';\n type = 'ComboChart';\n data = [\n [\"Apples\", 3, 2, 2.5],\n [\"Oranges\",2, 3, 2.5],\n [\"Pears\", 1, 5, 3],\n [\"Bananas\", 3, 9, 6],\n [\"Plums\", 4, 2, 3]\n ];\n columnNames = ['Fruits', 'Jane','Jone','Average'];\n options = { \n hAxis: {\n title: 'Person'\n },\n vAxis:{\n title: 'Fruits'\n },\n seriesType: 'bars',\n series: {2: {type: 'line'}}\n };\n width = 550;\n height = 400;\n}" }, { "code": null, "e": 12167, "s": 12148, "text": "Verify the result." }, { "code": null, "e": 12675, "s": 12167, "text": "A histogram is a chart that groups numeric data into buckets, displaying the buckets as segmented columns. They're used to depict the distribution of a dataset as how often values fall into ranges. Google Charts automatically chooses the number of buckets for you. All buckets are equal width and have a height proportional to the number of data points in the bucket. Histograms are similar to column charts in other aspects. In this section we're going to discuss following types of histogram based charts." }, { "code": null, "e": 12698, "s": 12675, "text": "Basic Histogram chart." }, { "code": null, "e": 12736, "s": 12698, "text": "Customized Color of Histrogram Chart." }, { "code": null, "e": 12776, "s": 12736, "text": "Customized Buckets of Histrogram Chart." }, { "code": null, "e": 12817, "s": 12776, "text": "Histrogram Chart having multiple series." }, { "code": null, "e": 12942, "s": 12817, "text": "Line charts are used to draw line based charts. In this section we're going to discuss following types of line based charts." }, { "code": null, "e": 12960, "s": 12942, "text": "Basic line chart." }, { "code": null, "e": 12992, "s": 12960, "text": "Chart with visible data points." }, { "code": null, "e": 13032, "s": 12992, "text": "Chart with customized background color." }, { "code": null, "e": 13066, "s": 13032, "text": "Chart with customized line color." }, { "code": null, "e": 13110, "s": 13066, "text": "Chart with customized axis and tick labels." }, { "code": null, "e": 13169, "s": 13110, "text": "Line charts showing crosshairs at data point on selection." }, { "code": null, "e": 13203, "s": 13169, "text": "Chart with customized line color." }, { "code": null, "e": 13234, "s": 13203, "text": "Chart with smooth curve lines." }, { "code": null, "e": 13490, "s": 13234, "text": "A Google Map Chart uses Google Maps API to display Map. Data values are displayed as markers on the map. Data values may be coordinates (lat-long pairs) or actual addresses. The map will be scaled accordingly so that it includes all the identified points." }, { "code": null, "e": 13508, "s": 13490, "text": "Basic Google Map." }, { "code": null, "e": 13569, "s": 13508, "text": "Map having locations specified using Latitude and Longitude." }, { "code": null, "e": 13618, "s": 13569, "text": "Following is an example of a Organization Chart." }, { "code": null, "e": 13960, "s": 13618, "text": "Organization chart helps in rendering a hierarchy of nodes, used to portray superior/subordinate relationships in an organization. For example, A family tree is a type of org chart. We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Organization Chart." }, { "code": null, "e": 14016, "s": 13960, "text": "We've used OrgChart class to show a Organization Chart." }, { "code": null, "e": 14034, "s": 14016, "text": "type='OrgChart';\n" }, { "code": null, "e": 14051, "s": 14034, "text": "app.component.ts" }, { "code": null, "e": 14746, "s": 14051, "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 = '';\n type = 'OrgChart';\n data = [\n [{v:'Mike', f:'Mike<div style=\"color:red; font-style:italic\">President</div>'},\n '', 'The President'],\n [{v:'Jim', f:'Jim<div style=\"color:red; font-style:italic\">Vice President</div>'},\n 'Mike', 'VP'],\n ['Alice', 'Mike', ''],\n ['Bob', 'Jim', 'Bob Sponge'],\n ['Carol', 'Bob', '']\n ];\n columnNames = [\"Name\",\"Manager\",\"Tooltip\"];\n options = { \n allowHtml: true\n };\n width = 550;\n height = 400;\n}" }, { "code": null, "e": 14765, "s": 14746, "text": "Verify the result." }, { "code": null, "e": 14887, "s": 14765, "text": "Pie charts are used to draw pie based charts. In this section we're going to discuss following types of pie based charts." }, { "code": null, "e": 14904, "s": 14887, "text": "Basic pie chart." }, { "code": null, "e": 14917, "s": 14904, "text": "Donut Chart." }, { "code": null, "e": 14931, "s": 14917, "text": "3D Pie chart." }, { "code": null, "e": 14963, "s": 14931, "text": "Pie chart with exploded slices." }, { "code": null, "e": 15250, "s": 14963, "text": "A sankey chart is a visualization tool and is used to depict a flow from one set of values to another. Connected objects are called nodes and the connections are called links. Sankeys are used to show a many-to-many mapping between two domains or multiple paths through a set of stages." }, { "code": null, "e": 15270, "s": 15250, "text": "Basic Sankey Chart." }, { "code": null, "e": 15295, "s": 15270, "text": "Multilevel Sankey Chart." }, { "code": null, "e": 15320, "s": 15295, "text": "Customized Sankey Chart." }, { "code": null, "e": 15364, "s": 15320, "text": "Following is an example of a Scatter Chart." }, { "code": null, "e": 15519, "s": 15364, "text": "We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Scatter Chart." }, { "code": null, "e": 15574, "s": 15519, "text": "We've used ScatterChart class to show a Scatter chart." }, { "code": null, "e": 15598, "s": 15574, "text": "type = 'ScatterChart';\n" }, { "code": null, "e": 15615, "s": 15598, "text": "app.component.ts" }, { "code": null, "e": 16057, "s": 15615, "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 = 'Age vs Weight';\n type='ScatterChart';\n data = [\n [8,12],\n [4, 5.5],\n [11,14],\n [4,5],\n [3,3.5],\n [6.5,7]\n ];\n columnNames = ['Age', 'Weight'];\n options = { \n };\n width = 550;\n height = 400;\n}" }, { "code": null, "e": 16076, "s": 16057, "text": "Verify the result." }, { "code": null, "e": 16188, "s": 16076, "text": "A stepped area chart is a step based area chart. We're going to discuss following types of stepped area charts." }, { "code": null, "e": 16214, "s": 16188, "text": "Basic Stepped Area Chart." }, { "code": null, "e": 16242, "s": 16214, "text": "Stacked Stepped Area Chart." }, { "code": null, "e": 16728, "s": 16242, "text": "Table chart helps in rendering a table which can be sorted and paged. Table cells can be formatted using format strings, or by directly inserting HTML as cell values. Numeric values are right-aligned by default; boolean values are displayed as check marks or cross marks. Users can select single rows either with the keyboard or the mouse. Column headers can be used for sorting. The header row remains fixed during scrolling. The table fires events corresponding to user interaction. " }, { "code": null, "e": 16881, "s": 16728, "text": "We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Table Chart." }, { "code": null, "e": 16927, "s": 16881, "text": "We've used Table class to show a Table chart." }, { "code": null, "e": 16944, "s": 16927, "text": "type = 'Table';\n" }, { "code": null, "e": 16961, "s": 16944, "text": "app.component.ts" }, { "code": null, "e": 17571, "s": 16961, "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 = \"\";\n type = 'Table';\n data = [\n ['Mike', {v: 10000, f: '$10,000'}, true],\n ['Jim', {v:8000, f: '$8,000'}, false],\n ['Alice', {v: 12500, f: '$12,500'}, true],\n ['Bob', {v: 7000, f: '$7,000'}, true]\n ];\n columnNames = [\"Name\", \"Salary\",\"Full Time Employee\"];\n options = { \n alternatingRowStyle:true,\n showRowNumber:true \n };\n width = 550;\n height = 400;\n}" }, { "code": null, "e": 17590, "s": 17571, "text": "Verify the result." }, { "code": null, "e": 17941, "s": 17590, "text": "TreeMap is a visual representation of a data tree, where each node may have zero or more children, and one parent (except for the root). Each node is displayed as a rectangle, can be sized and colored according to values that we assign. Sizes and colors are valued relative to all other nodes in the graph. Following is an example of a treemap chart." }, { "code": null, "e": 18096, "s": 17941, "text": "We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a TreeMap Chart." }, { "code": null, "e": 18146, "s": 18096, "text": "We've used TreeMap class to show a TreeMap chart." }, { "code": null, "e": 18165, "s": 18146, "text": "type = 'TreeMap';\n" }, { "code": null, "e": 18182, "s": 18165, "text": "app.component.ts" }, { "code": null, "e": 19293, "s": 18182, "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 = '';\n type='TreeMap';\n data = [\n [\"Global\",null,0,0],\n [\"America\",\"Global\",0,0],\n [\"Europe\",\"Global\",0,0],\n [\"Asia\",\"Global\",0,0],\n [\"Australia\",\"Global\",0,0],\n [\"Africa\",\"Global\",0,0],\n\n [\"USA\",\"America\",52,31],\n [\"Mexico\",\"America\",24,12],\n [\"Canada\",\"America\",16,-23],\n\n [\"France\",\"Europe\",42,-11],\n [\"Germany\",\"Europe\",31,-2],\n [\"Sweden\",\"Europe\",22,-13],\n\n [\"China\",\"Asia\",36,4],\n [\"Japan\",\"Asia\",20,-12],\n [\"India\",\"Asia\",40,63],\n\n [\"Egypt\",\"Africa\",21,0],\n [\"Congo\",\"Africa\",10,12],\n [\"Zaire\",\"Africa\",8,10],\n \n ];\n columnNames = [\"Location\", \"Parent\",\"Market trade volume (size)\",\"Market increase/decrease (color)\"];\n options = { \n minColor:\"#ff7777\",\n midColor:'#ffff77',\n maxColor:'#77ff77',\n headerHeight:15,\n showScale:true\n };\n width = 550;\n height = 400;\n}" }, { "code": null, "e": 19312, "s": 19293, "text": "Verify the result." }, { "code": null, "e": 19347, "s": 19312, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 19361, "s": 19347, "text": " Anadi Sharma" }, { "code": null, "e": 19396, "s": 19361, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 19410, "s": 19396, "text": " Anadi Sharma" }, { "code": null, "e": 19445, "s": 19410, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 19465, "s": 19445, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 19500, "s": 19465, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 19517, "s": 19500, "text": " Frahaan Hussain" }, { "code": null, "e": 19550, "s": 19517, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 19562, "s": 19550, "text": " Senol Atac" }, { "code": null, "e": 19597, "s": 19562, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 19609, "s": 19597, "text": " Senol Atac" }, { "code": null, "e": 19616, "s": 19609, "text": " Print" }, { "code": null, "e": 19627, "s": 19616, "text": " Add Notes" } ]
Machine Learning — Word Embedding & Sentiment Classification using Keras | by Javaid Nabi | Towards Data Science
In the previous post, we discussed various steps of text processing involved in Nature Language Processing (NLP) and also implemented a basic Sentiment Analyzer using some of the classical ML techniques. Deep learning has demonstrated superior performance on a wide variety of tasks including NLP, Computer Vision, and Games. To explore further, we will discuss and use some of the advanced NLP techniques, based on Deep Learning, to create an improved Sentiment Classifier. Sentiment classification is the task of looking at a piece of text and telling if someone likes or dislikes the thing they’re talking about. The input X is a piece of text and the output Y is the sentiment which we want to predict, such as the star rating of a movie review. If we can train a system to map from X to Y based on a labelled data set like above, then such a system can be used to predict sentiment of a reviewer after watching a movie. In this post we will focus on below tasks: Build a Deep Neural Network for Sentiment Classification. Learn Word Embedding : while training the network and using Word2Vec. Deep learning text classification model architectures generally consist of the following components connected in sequence: Embedding Layer Word Embedding is a representation of text where words that have the same meaning have a similar representation. In other words it represents words in a coordinate system where related words, based on a corpus of relationships, are placed closer together. In the deep learning frameworks such as TensorFlow, Keras, this part is usually handled by an embedding layer which stores a lookup table to map the words represented by numeric indexes to their dense vector representations. Deep Network Deep network takes the sequence of embedding vectors as input and converts them to a compressed representation. The compressed representation effectively captures all the information in the sequence of words in the text. The deep neywrok part is usually an RNN or some forms of it like LSTM/GRU. The dropout is added to overcome the tendency to overfit, a very common problem with RNN based networks. Please refer here for detailed discussion on LSTM,GRU. Fully Connected Layer The fully connected layer takes the deep representation from the RNN/LSTM/GRU and transforms it into the final output classes or class scores. This component is comprised of fully connected layers along with batch normalization and optionally dropout layers for regularization. Output Layer Based on the problem at hand, this layer can have either Sigmoid for binary classification or Softmax for both binary and multi classification output. The IMDB movie review set can be downloaded from here. This dataset for binary sentiment classification contains set of 25,000 highly polar movie reviews for training, and 25,000 for testing. The dataset after initial pre-processing is saved to movie_data.csv file. First we load the IMDb dataset, the text reviews are labelled as 1 or 0 for positive and negative sentiment respectively. The word embeddings of our dataset can be learned while training a neural network on the classification problem. Before it can be presented to the network, the text data is first encoded so that each word is represented by a unique integer. This data preparation step can be performed using the Tokenizer API provided with Keras. We add padding to make all the vectors of same length (max_length). Below code converts the text to integer indexes, now ready to be used in Keras embedding layer. The Embedding layer requires the specification of the vocabulary size (vocab_size), the size of the real-valued vector space EMBEDDING_DIM = 100, and the maximum length of input documents max_length . We are now ready to define our neural network model. The model will use an Embedding layer as the first hidden layer. The Embedding layer is initialized with random weights and will learn an embedding for all of the words in the training dataset during training of the model. The summary of the model is: We have used a simple deep network configuration for demonstration purpose. You can try out different configuration of the network and compare the performance. The embedding param count 12560200 = (vocab_size * EMBEDDING_DIM). Maximum input length max_length = 2678. The model during training shall learn the word embeddings from the input text. The total trainable params are 12,573,001. Now let us train the model on training set and cross validate on test set. We can see from below training epochs that the model after each epoch is improving the accuracy. After a few epochs we reach validation accuracy of around 84%. Not bad :) We can test our model with some sample reviews to check how it is predicting the sentiment of each review. First we will have to convert the text review to tokens and use model to predict as below. The output gives the prediction of the word either to be 1 (positive sentiment) or 0 (negative sentiment). Value closer to 1 is strong positive sentiment and a value close to 0 is a strong negative sentiment. I can clearly see that the model prediction is wrong for test_sample_7 and is doing reasonably well for rest of the samples. In the above approach we learn word embedding as part of fitting a neural network model. There is another approach to building the Sentiment clarification model. Instead of training the embedding layer, we can first separately learn word embeddings and then pass to the embedding layer. This approach also allows to use any pre-trained word embedding and also saves the time in training the classification model. We will use the Gensim implementation of Word2Vec. The first step is to prepare the text corpus for learning the embedding by creating word tokens, removing punctuation, removing stop words etc. The word2vec algorithm processes documents sentence by sentence. we have 50000 review lines in our text corpus. Gensim’s Word2Vec API requires some parameters for initialization. i. sentences – List of sentences; here we pass the list of review sentences. ii. size – The number of dimensions in which we wish to represent our word. This is the size of the word vector. iii. min_count – Word with frequency greater than min_count only are going to be included into the model. Usually, the bigger and more extensive your text, the higher this number can be. iv. window – Only terms that occur within a window-neighborhood of a term, in a sentence, are associated with it during training. The usual value is 4 or 5. v. workers– Number of threads used in training parallelization, to speed up training After we train the model on our IMDb dataset, it builds a vocabulary size = 134156 . Let us try some word embeddings the model learnt from the movie review dataset. The most similar words for word horrible are: Try some math on the word vectors — woman+king-man=? Let us find the odd word woman, king, queen, movie = ? This is very interesting to see the word embeddings learned by our word2vec model form the text corpus. The next step is to use the word embeddings directly in the embedding layer in our sentiment classification model. we can save the model to be used later. Since we have already trained word2vec model with IMDb dataset, we have the word embeddings ready to use. The next step is to load the word embedding as a directory of words to vectors. The word embedding was saved in file imdb_embedding_word2vec.txt. Let us extract the word embeddings from the stored file. The next step is to convert the word embedding into tokenized vector. Recall that the review documents are integer encoded prior to passing them to the Embedding layer. The integer maps to the index of a specific vector in the embedding layer. Therefore, it is important that we lay the vectors out in the Embedding layer such that the encoded words map to the correct vector. Now we will map embeddings from the loaded word2vec model for each word to the tokenizer_obj.word_index vocabulary and create a matrix with of word vectors. We are now ready with the trained embedding vector to be used directly in the embedding layer. In the below code, the only change from previous model is using the embedding_matrix as input to the Embedding layer and setting trainable = False, since the embedding is already learned. Look closely, you can see that model total params = 13,428,501 but trainable params = 12801. Since the model uses pre-trained word embedding it has very few trainable params and hence should train faster. To train the sentiment classification model, we use VALIDATION_SPLIT= 0.2, you can vary this to see effect on the accuracy of the model. Finally training the classification model on train and validation test set, we get improvement in accuracy with each epoch run. We reach 88% accuracy with just around 5 epochs. You can try to improve the accuracy of the model by changing hyper-parameters, running more epochs etc,. Also, you can use some other pre-trained embeddings prepared on very large corpus of text data that you can directly download. In this post we discussed in detail the architecture of Deep Learning model for sentiment classification. We also trained a word2vec model and used it as a per-trained embedding for sentiment classification. Thanks for reading, if you liked it, please give a clap to it. http://ruder.io/deep-learning-nlp-best-practices keras.io machinelearningmastery.com Hands-On NLP with Python, By Rajesh Arumugam, Rajalingappaa Shanmugamani July 2018
[ { "code": null, "e": 375, "s": 171, "text": "In the previous post, we discussed various steps of text processing involved in Nature Language Processing (NLP) and also implemented a basic Sentiment Analyzer using some of the classical ML techniques." }, { "code": null, "e": 646, "s": 375, "text": "Deep learning has demonstrated superior performance on a wide variety of tasks including NLP, Computer Vision, and Games. To explore further, we will discuss and use some of the advanced NLP techniques, based on Deep Learning, to create an improved Sentiment Classifier." }, { "code": null, "e": 787, "s": 646, "text": "Sentiment classification is the task of looking at a piece of text and telling if someone likes or dislikes the thing they’re talking about." }, { "code": null, "e": 921, "s": 787, "text": "The input X is a piece of text and the output Y is the sentiment which we want to predict, such as the star rating of a movie review." }, { "code": null, "e": 1096, "s": 921, "text": "If we can train a system to map from X to Y based on a labelled data set like above, then such a system can be used to predict sentiment of a reviewer after watching a movie." }, { "code": null, "e": 1139, "s": 1096, "text": "In this post we will focus on below tasks:" }, { "code": null, "e": 1197, "s": 1139, "text": "Build a Deep Neural Network for Sentiment Classification." }, { "code": null, "e": 1267, "s": 1197, "text": "Learn Word Embedding : while training the network and using Word2Vec." }, { "code": null, "e": 1390, "s": 1267, "text": "Deep learning text classification model architectures generally consist of the following components connected in sequence:" }, { "code": null, "e": 1406, "s": 1390, "text": "Embedding Layer" }, { "code": null, "e": 1887, "s": 1406, "text": "Word Embedding is a representation of text where words that have the same meaning have a similar representation. In other words it represents words in a coordinate system where related words, based on a corpus of relationships, are placed closer together. In the deep learning frameworks such as TensorFlow, Keras, this part is usually handled by an embedding layer which stores a lookup table to map the words represented by numeric indexes to their dense vector representations." }, { "code": null, "e": 1900, "s": 1887, "text": "Deep Network" }, { "code": null, "e": 2356, "s": 1900, "text": "Deep network takes the sequence of embedding vectors as input and converts them to a compressed representation. The compressed representation effectively captures all the information in the sequence of words in the text. The deep neywrok part is usually an RNN or some forms of it like LSTM/GRU. The dropout is added to overcome the tendency to overfit, a very common problem with RNN based networks. Please refer here for detailed discussion on LSTM,GRU." }, { "code": null, "e": 2378, "s": 2356, "text": "Fully Connected Layer" }, { "code": null, "e": 2656, "s": 2378, "text": "The fully connected layer takes the deep representation from the RNN/LSTM/GRU and transforms it into the final output classes or class scores. This component is comprised of fully connected layers along with batch normalization and optionally dropout layers for regularization." }, { "code": null, "e": 2669, "s": 2656, "text": "Output Layer" }, { "code": null, "e": 2820, "s": 2669, "text": "Based on the problem at hand, this layer can have either Sigmoid for binary classification or Softmax for both binary and multi classification output." }, { "code": null, "e": 3208, "s": 2820, "text": "The IMDB movie review set can be downloaded from here. This dataset for binary sentiment classification contains set of 25,000 highly polar movie reviews for training, and 25,000 for testing. The dataset after initial pre-processing is saved to movie_data.csv file. First we load the IMDb dataset, the text reviews are labelled as 1 or 0 for positive and negative sentiment respectively." }, { "code": null, "e": 3702, "s": 3208, "text": "The word embeddings of our dataset can be learned while training a neural network on the classification problem. Before it can be presented to the network, the text data is first encoded so that each word is represented by a unique integer. This data preparation step can be performed using the Tokenizer API provided with Keras. We add padding to make all the vectors of same length (max_length). Below code converts the text to integer indexes, now ready to be used in Keras embedding layer." }, { "code": null, "e": 3903, "s": 3702, "text": "The Embedding layer requires the specification of the vocabulary size (vocab_size), the size of the real-valued vector space EMBEDDING_DIM = 100, and the maximum length of input documents max_length ." }, { "code": null, "e": 4179, "s": 3903, "text": "We are now ready to define our neural network model. The model will use an Embedding layer as the first hidden layer. The Embedding layer is initialized with random weights and will learn an embedding for all of the words in the training dataset during training of the model." }, { "code": null, "e": 4208, "s": 4179, "text": "The summary of the model is:" }, { "code": null, "e": 4597, "s": 4208, "text": "We have used a simple deep network configuration for demonstration purpose. You can try out different configuration of the network and compare the performance. The embedding param count 12560200 = (vocab_size * EMBEDDING_DIM). Maximum input length max_length = 2678. The model during training shall learn the word embeddings from the input text. The total trainable params are 12,573,001." }, { "code": null, "e": 4843, "s": 4597, "text": "Now let us train the model on training set and cross validate on test set. We can see from below training epochs that the model after each epoch is improving the accuracy. After a few epochs we reach validation accuracy of around 84%. Not bad :)" }, { "code": null, "e": 5041, "s": 4843, "text": "We can test our model with some sample reviews to check how it is predicting the sentiment of each review. First we will have to convert the text review to tokens and use model to predict as below." }, { "code": null, "e": 5148, "s": 5041, "text": "The output gives the prediction of the word either to be 1 (positive sentiment) or 0 (negative sentiment)." }, { "code": null, "e": 5375, "s": 5148, "text": "Value closer to 1 is strong positive sentiment and a value close to 0 is a strong negative sentiment. I can clearly see that the model prediction is wrong for test_sample_7 and is doing reasonably well for rest of the samples." }, { "code": null, "e": 5464, "s": 5375, "text": "In the above approach we learn word embedding as part of fitting a neural network model." }, { "code": null, "e": 5788, "s": 5464, "text": "There is another approach to building the Sentiment clarification model. Instead of training the embedding layer, we can first separately learn word embeddings and then pass to the embedding layer. This approach also allows to use any pre-trained word embedding and also saves the time in training the classification model." }, { "code": null, "e": 6048, "s": 5788, "text": "We will use the Gensim implementation of Word2Vec. The first step is to prepare the text corpus for learning the embedding by creating word tokens, removing punctuation, removing stop words etc. The word2vec algorithm processes documents sentence by sentence." }, { "code": null, "e": 6162, "s": 6048, "text": "we have 50000 review lines in our text corpus. Gensim’s Word2Vec API requires some parameters for initialization." }, { "code": null, "e": 6239, "s": 6162, "text": "i. sentences – List of sentences; here we pass the list of review sentences." }, { "code": null, "e": 6352, "s": 6239, "text": "ii. size – The number of dimensions in which we wish to represent our word. This is the size of the word vector." }, { "code": null, "e": 6539, "s": 6352, "text": "iii. min_count – Word with frequency greater than min_count only are going to be included into the model. Usually, the bigger and more extensive your text, the higher this number can be." }, { "code": null, "e": 6696, "s": 6539, "text": "iv. window – Only terms that occur within a window-neighborhood of a term, in a sentence, are associated with it during training. The usual value is 4 or 5." }, { "code": null, "e": 6781, "s": 6696, "text": "v. workers– Number of threads used in training parallelization, to speed up training" }, { "code": null, "e": 6946, "s": 6781, "text": "After we train the model on our IMDb dataset, it builds a vocabulary size = 134156 . Let us try some word embeddings the model learnt from the movie review dataset." }, { "code": null, "e": 6992, "s": 6946, "text": "The most similar words for word horrible are:" }, { "code": null, "e": 7045, "s": 6992, "text": "Try some math on the word vectors — woman+king-man=?" }, { "code": null, "e": 7100, "s": 7045, "text": "Let us find the odd word woman, king, queen, movie = ?" }, { "code": null, "e": 7359, "s": 7100, "text": "This is very interesting to see the word embeddings learned by our word2vec model form the text corpus. The next step is to use the word embeddings directly in the embedding layer in our sentiment classification model. we can save the model to be used later." }, { "code": null, "e": 7668, "s": 7359, "text": "Since we have already trained word2vec model with IMDb dataset, we have the word embeddings ready to use. The next step is to load the word embedding as a directory of words to vectors. The word embedding was saved in file imdb_embedding_word2vec.txt. Let us extract the word embeddings from the stored file." }, { "code": null, "e": 8045, "s": 7668, "text": "The next step is to convert the word embedding into tokenized vector. Recall that the review documents are integer encoded prior to passing them to the Embedding layer. The integer maps to the index of a specific vector in the embedding layer. Therefore, it is important that we lay the vectors out in the Embedding layer such that the encoded words map to the correct vector." }, { "code": null, "e": 8202, "s": 8045, "text": "Now we will map embeddings from the loaded word2vec model for each word to the tokenizer_obj.word_index vocabulary and create a matrix with of word vectors." }, { "code": null, "e": 8485, "s": 8202, "text": "We are now ready with the trained embedding vector to be used directly in the embedding layer. In the below code, the only change from previous model is using the embedding_matrix as input to the Embedding layer and setting trainable = False, since the embedding is already learned." }, { "code": null, "e": 8690, "s": 8485, "text": "Look closely, you can see that model total params = 13,428,501 but trainable params = 12801. Since the model uses pre-trained word embedding it has very few trainable params and hence should train faster." }, { "code": null, "e": 8827, "s": 8690, "text": "To train the sentiment classification model, we use VALIDATION_SPLIT= 0.2, you can vary this to see effect on the accuracy of the model." }, { "code": null, "e": 9004, "s": 8827, "text": "Finally training the classification model on train and validation test set, we get improvement in accuracy with each epoch run. We reach 88% accuracy with just around 5 epochs." }, { "code": null, "e": 9236, "s": 9004, "text": "You can try to improve the accuracy of the model by changing hyper-parameters, running more epochs etc,. Also, you can use some other pre-trained embeddings prepared on very large corpus of text data that you can directly download." }, { "code": null, "e": 9444, "s": 9236, "text": "In this post we discussed in detail the architecture of Deep Learning model for sentiment classification. We also trained a word2vec model and used it as a per-trained embedding for sentiment classification." }, { "code": null, "e": 9507, "s": 9444, "text": "Thanks for reading, if you liked it, please give a clap to it." }, { "code": null, "e": 9556, "s": 9507, "text": "http://ruder.io/deep-learning-nlp-best-practices" }, { "code": null, "e": 9565, "s": 9556, "text": "keras.io" }, { "code": null, "e": 9592, "s": 9565, "text": "machinelearningmastery.com" } ]
Linked Lists in Python. Linked List Data Structures in Python | by Sadrach Pierre, Ph.D. | Towards Data Science
Data structures provide ways of organizing data such that we can perform operations on the data efficiently. One important data structure is the linked list. A linked list is a linear collection of nodes, where each node contains a data value and a reference to the next node in the list. In this post, we will discuss how to implement linked lists in python. Let’s get started! We begin by creating two classes, a ‘Node’ class and a ‘LinkedList’ class. For the Node class we have: class Node: def __init__(self, data): self.data = data self.next = None Here we assign data values and initialize the next node as null. And for the ‘LinkedList’ class we initialize the head node as null: class LinkedList: def __init__(self): self.head = None The linked list class, which will contain a reference of the Node class type, is used to initialize the linked list object. We can now write an instance of a linked list and print the result: if __name__=='__main__': linkedlist = LinkedList() print(linked list) We see we have a linked list object at the specified address. Next we can define a few nodes. Let’s work towards a real life example. Music players typically have doubly linked lists containing songs linked to previous and next songs. For simplicity, let’s consider singly linked list of songs, where each song will be only linked to the next song. Let’s create a linked list of the songs on first half of the album Dark Side of the Moon, by Pink Floyd. To start, we define the values of each node: if __name__=='__main__': linkedlist = LinkedList() linkedlist.head = Node('Speak to Me') second = Node('Breathe') third = Node('On the Run') fourth = Node('Time') fifth = Node('The Great Gig in the Sky') Now we need to link all of the nodes. First we define the ‘next’ value of the head node: linkedlist.head.next = second Then the ‘next’ value of the ‘second’ node: second.next = third And so forth: third.next = fourthfourth.next = fifth Now that our linked list is defined, we can traverse the linked list. Let’s define a method, in the ‘LinkedList’ class, that will allow us to do so: def printLinkedList(self): value = self.head while (value): print(value.data) value = value.next We can now traverse the list : if __name__=='__main__': #initialize linked list object linkedlist = LinkedList() print(linkedlist) #assign values to nodes linkedlist.head = Node('Speak to Me') second = Node('Breathe') third = Node('On the Run') fourth = Node('Time') fifth = Node('The Great Gig in the Sky') #link nodes linkedlist.head.next = second second.next = third third.next = fourth fourth.next = fifth linkedlist.printLinkedList() To summarize, in this post we discussed how to implement a singly linked list in python. We developed a singly linked list for a music player, where each song is linked to the next song in the list. In practice, songs in a music player are linked to previous and next songs (doubly linked list implementation). I encourage you to modify the code in this post to implement a doubly linked list for the songs we used. The code in this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 532, "s": 172, "text": "Data structures provide ways of organizing data such that we can perform operations on the data efficiently. One important data structure is the linked list. A linked list is a linear collection of nodes, where each node contains a data value and a reference to the next node in the list. In this post, we will discuss how to implement linked lists in python." }, { "code": null, "e": 551, "s": 532, "text": "Let’s get started!" }, { "code": null, "e": 654, "s": 551, "text": "We begin by creating two classes, a ‘Node’ class and a ‘LinkedList’ class. For the Node class we have:" }, { "code": null, "e": 746, "s": 654, "text": "class Node: def __init__(self, data): self.data = data self.next = None" }, { "code": null, "e": 879, "s": 746, "text": "Here we assign data values and initialize the next node as null. And for the ‘LinkedList’ class we initialize the head node as null:" }, { "code": null, "e": 947, "s": 879, "text": "class LinkedList: def __init__(self): self.head = None" }, { "code": null, "e": 1139, "s": 947, "text": "The linked list class, which will contain a reference of the Node class type, is used to initialize the linked list object. We can now write an instance of a linked list and print the result:" }, { "code": null, "e": 1215, "s": 1139, "text": "if __name__=='__main__': linkedlist = LinkedList() print(linked list)" }, { "code": null, "e": 1564, "s": 1215, "text": "We see we have a linked list object at the specified address. Next we can define a few nodes. Let’s work towards a real life example. Music players typically have doubly linked lists containing songs linked to previous and next songs. For simplicity, let’s consider singly linked list of songs, where each song will be only linked to the next song." }, { "code": null, "e": 1714, "s": 1564, "text": "Let’s create a linked list of the songs on first half of the album Dark Side of the Moon, by Pink Floyd. To start, we define the values of each node:" }, { "code": null, "e": 1941, "s": 1714, "text": "if __name__=='__main__': linkedlist = LinkedList() linkedlist.head = Node('Speak to Me') second = Node('Breathe') third = Node('On the Run') fourth = Node('Time') fifth = Node('The Great Gig in the Sky')" }, { "code": null, "e": 2030, "s": 1941, "text": "Now we need to link all of the nodes. First we define the ‘next’ value of the head node:" }, { "code": null, "e": 2060, "s": 2030, "text": "linkedlist.head.next = second" }, { "code": null, "e": 2104, "s": 2060, "text": "Then the ‘next’ value of the ‘second’ node:" }, { "code": null, "e": 2124, "s": 2104, "text": "second.next = third" }, { "code": null, "e": 2138, "s": 2124, "text": "And so forth:" }, { "code": null, "e": 2177, "s": 2138, "text": "third.next = fourthfourth.next = fifth" }, { "code": null, "e": 2326, "s": 2177, "text": "Now that our linked list is defined, we can traverse the linked list. Let’s define a method, in the ‘LinkedList’ class, that will allow us to do so:" }, { "code": null, "e": 2463, "s": 2326, "text": "def printLinkedList(self): value = self.head while (value): print(value.data) value = value.next" }, { "code": null, "e": 2494, "s": 2463, "text": "We can now traverse the list :" }, { "code": null, "e": 2970, "s": 2494, "text": "if __name__=='__main__': #initialize linked list object linkedlist = LinkedList() print(linkedlist) #assign values to nodes linkedlist.head = Node('Speak to Me') second = Node('Breathe') third = Node('On the Run') fourth = Node('Time') fifth = Node('The Great Gig in the Sky') #link nodes linkedlist.head.next = second second.next = third third.next = fourth fourth.next = fifth linkedlist.printLinkedList()" } ]
The intersection of two arrays in Python (Lambda expression and filter function )
In this article, we will learn about the intersection of two arrays in Python with the help of Lambda expression and filter function. The problem is that we are given two arrays we have to find out common elements in both of them. 1. Declaring an intersection function with two arguments. 2. Now we use the lambda expression to create an inline function for selection of elements with the help of filter function checking that element is contained in both the list or not. 3. Finally, we convert all the common elements in the form of a list by the help of typecasting. 4. And then we display the output by the help of the print statement. Now let’s take a look at its implementation: def interSection(arr1,arr2): # finding common elements # using filter method oto find identical values via lambda function values = list(filter(lambda x: x in arr1, arr2)) print ("Intersection of arr1 & arr2 is: ",values) # Driver program if __name__ == "__main__": arr1 = ['t','u','t','o','r','i','a','l'] arr2 = ['p','o','i','n','t'] interSection(arr1,arr2) Intersection of arr1 & arr2 is: ['o', 'i', 't'] In this article, we learned about the intersection of two arrays in Python with the help of Lambda expression and filter function and its implementation.
[ { "code": null, "e": 1196, "s": 1062, "text": "In this article, we will learn about the intersection of two arrays in Python with the help of Lambda expression and filter function." }, { "code": null, "e": 1293, "s": 1196, "text": "The problem is that we are given two arrays we have to find out common elements in both of them." }, { "code": null, "e": 1702, "s": 1293, "text": "1. Declaring an intersection function with two arguments.\n2. Now we use the lambda expression to create an inline function for selection of elements with the help of filter function checking that element is contained in both the list or not.\n3. Finally, we convert all the common elements in the form of a list by the help of typecasting.\n4. And then we display the output by the help of the print statement." }, { "code": null, "e": 1747, "s": 1702, "text": "Now let’s take a look at its implementation:" }, { "code": null, "e": 2118, "s": 1747, "text": "def interSection(arr1,arr2): # finding common elements\n\n# using filter method oto find identical values via lambda function\nvalues = list(filter(lambda x: x in arr1, arr2))\nprint (\"Intersection of arr1 & arr2 is: \",values)\n\n# Driver program\nif __name__ == \"__main__\":\n arr1 = ['t','u','t','o','r','i','a','l']\n arr2 = ['p','o','i','n','t']\n interSection(arr1,arr2)" }, { "code": null, "e": 2166, "s": 2118, "text": "Intersection of arr1 & arr2 is: ['o', 'i', 't']" }, { "code": null, "e": 2320, "s": 2166, "text": "In this article, we learned about the intersection of two arrays in Python with the help of Lambda expression and filter function and its implementation." } ]
ReactJS | Lifecycle of Components - GeeksforGeeks
14 Mar, 2022 Prerequisite : Introduction to ReactJs We have seen so far that React web apps are actually a collection of independent components that run according to the interactions made with them. Every React Component has a lifecycle of its own, lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence. The definition is pretty straightforward but what do we mean by different stages? A React Component can go through four stages of its life as follows. Initialization: This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class. Mounting: Mounting is the stage of rendering the JSX returned by the render method itself. Updating: Updating is the stage when the state of a component is updated and the application is repainted. Unmounting: As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page. React provides the developers a set of predefined functions that if present is invoked around specific events in the lifetime of the component. Developers are supposed to override the functions with desired logic to execute accordingly. We have illustrated the gist in the following diagram. Now let us describe each phase and its corresponding functions.Functions of each Phase of Lifecycle Initialization: In this phase, the developer has to define the props and initial state of the component this is generally done in the constructor of the component. The following code snippet describes the initialization process. Initialization: In this phase, the developer has to define the props and initial state of the component this is generally done in the constructor of the component. The following code snippet describes the initialization process. Javascript class Clock extends React.Component { constructor(props) { // Calling the constructor of // Parent Class React.Component super(props); // Setting the initial state this.state = { date : new Date() }; } } 2. Mounting: Mounting is the phase of the component lifecycle when the initialization of the component is completed and the component is mounted on the DOM and rendered for the first time on the webpage. Now React follows a default procedure in the Naming Conventions of these predefined functions where the functions containing “Will” represents before some specific phase and “Did” represents after the completion of that phase. The mounting phase consists of two such predefined functions as described below. componentWillMount() Function: As the name clearly suggests, this function is invoked right before the component is mounted on the DOM i.e. this function gets invoked once before the render() function is executed for the first time. componentDidMount() Function: Similarly as the previous one this function is invoked right after the component is mounted on the DOM i.e. this function gets invoked once after the render() function is executed for the first time 3. Updation: React is a JS library that helps create Active web pages easily. Now active web pages are specific pages that behave according to their user. For example, let’s take the GeeksforGeeks {IDE} webpage, the webpage acts differently with each user. User A might write some code in C in the Light Theme while another User may write a Python code in the Dark Theme all at the same time. This dynamic behavior that partially depends upon the user itself makes the webpage an Active webpage. Now how can this be related to Updation? Updation is the phase where the states and props of a component are updated followed by some user events such as clicking, pressing a key on the keyboard, etc. The following are the descriptions of functions that are invoked at different points of Updation phase. componentWillReceiveProps() Function: This is a Props exclusive Function and is independent of States. This function is invoked before a mounted component gets its props reassigned. The function is passed the new set of Props which may or may not be identical to the original Props. Thus checking is a mandatory step in this regard. The following code snippet shows a sample use-case. Javascript componentWillReceiveProps(newProps) { if (this.props !== newProps) { console.log(" New Props have been assigned "); // Use this.setState() to rerender the page. } } setState() Function: This is not particularly a Lifecycle function and can be invoked explicitly at any instant. This function is used to update the state of a component. You may refer to this article for detailed information. shouldComponentUpdate() Function: By default, every state or props update re-render the page but this may not always be the desired outcome, sometimes it is desired that updating the page will not be repainted. The shouldComponentUpdate() Function fulfills the requirement by letting React know whether the component’s output will be affected by the update or not. shouldComponentUpdate() is invoked before rendering an already mounted component when new props or state are being received. If returned false then the subsequent steps of rendering will not be carried out. This function can’t be used in the case of forceUpdate(). The Function takes the new Props and new State as the arguments and returns whether to re-render or not. componentWillUpdate() Function: As the name clearly suggests, this function is invoked before the component is rerendered i.e. this function gets invoked once before the render() function is executed after the updation of State or Props. componentDidUpdate() Function: Similarly this function is invoked after the component is rerendered i.e. this function gets invoked once after the render() function is executed after the updation of State or Props. 4. Unmounting: This is the final phase of the lifecycle of the component that is the phase of unmounting the component from the DOM. The following function is the sole member of this phase. componentWillUnmount() Function: This function is invoked before the component is finally unmounted from the DOM i.e. this function gets invoked once before the component is removed from the page and this denotes the end of the lifecycle. We have so far discussed every predefined function there was in the lifecycle of the component, and we have also specified the order of execution of the function. Let us now see one final example to finish the article while revising what’s discussed above. First, create a react app and edit your index.js file from the src folder. src index.js: Javascript import React from 'react'; import ReactDOM from 'react-dom'; class Test extends React.Component { constructor(props) { super(props); this.state = { hello : "World!" }; } componentWillMount() { console.log("componentWillMount()"); } componentDidMount() { console.log("componentDidMount()"); } changeState() { this.setState({ hello : "Geek!" }); } render() { return ( <div> <h1>GeeksForGeeks.org, Hello{ this.state.hello }</h1> <h2> <a onClick={this.changeState.bind(this)}>Press Here!</a> </h2> </div>); } shouldComponentUpdate(nextProps, nextState) { console.log("shouldComponentUpdate()"); return true; } componentWillUpdate() { console.log("componentWillUpdate()"); } componentDidUpdate() { console.log("componentDidUpdate()"); } } ReactDOM.render( <Test />, document.getElementById('root')); Output: shubhamyadav4 akshitsaxenaa09 react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 27166, "s": 27138, "text": "\n14 Mar, 2022" }, { "code": null, "e": 27687, "s": 27166, "text": "Prerequisite : Introduction to ReactJs We have seen so far that React web apps are actually a collection of independent components that run according to the interactions made with them. Every React Component has a lifecycle of its own, lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence. The definition is pretty straightforward but what do we mean by different stages? A React Component can go through four stages of its life as follows. " }, { "code": null, "e": 27850, "s": 27687, "text": "Initialization: This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class." }, { "code": null, "e": 27941, "s": 27850, "text": "Mounting: Mounting is the stage of rendering the JSX returned by the render method itself." }, { "code": null, "e": 28048, "s": 27941, "text": "Updating: Updating is the stage when the state of a component is updated and the application is repainted." }, { "code": null, "e": 28183, "s": 28048, "text": "Unmounting: As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page." }, { "code": null, "e": 28476, "s": 28183, "text": "React provides the developers a set of predefined functions that if present is invoked around specific events in the lifetime of the component. Developers are supposed to override the functions with desired logic to execute accordingly. We have illustrated the gist in the following diagram. " }, { "code": null, "e": 28576, "s": 28476, "text": "Now let us describe each phase and its corresponding functions.Functions of each Phase of Lifecycle" }, { "code": null, "e": 28805, "s": 28576, "text": "Initialization: In this phase, the developer has to define the props and initial state of the component this is generally done in the constructor of the component. The following code snippet describes the initialization process." }, { "code": null, "e": 29034, "s": 28805, "text": "Initialization: In this phase, the developer has to define the props and initial state of the component this is generally done in the constructor of the component. The following code snippet describes the initialization process." }, { "code": null, "e": 29045, "s": 29034, "text": "Javascript" }, { "code": "class Clock extends React.Component { constructor(props) { // Calling the constructor of // Parent Class React.Component super(props); // Setting the initial state this.state = { date : new Date() }; } } ", "e": 29312, "s": 29045, "text": null }, { "code": null, "e": 29833, "s": 29318, "text": " 2. Mounting: Mounting is the phase of the component lifecycle when the initialization of the component is completed and the component is mounted on the DOM and rendered for the first time on the webpage. Now React follows a default procedure in the Naming Conventions of these predefined functions where the functions containing “Will” represents before some specific phase and “Did” represents after the completion of that phase. The mounting phase consists of two such predefined functions as described below." }, { "code": null, "e": 30066, "s": 29833, "text": "componentWillMount() Function: As the name clearly suggests, this function is invoked right before the component is mounted on the DOM i.e. this function gets invoked once before the render() function is executed for the first time." }, { "code": null, "e": 30295, "s": 30066, "text": "componentDidMount() Function: Similarly as the previous one this function is invoked right after the component is mounted on the DOM i.e. this function gets invoked once after the render() function is executed for the first time" }, { "code": null, "e": 31103, "s": 30295, "text": " 3. Updation: React is a JS library that helps create Active web pages easily. Now active web pages are specific pages that behave according to their user. For example, let’s take the GeeksforGeeks {IDE} webpage, the webpage acts differently with each user. User A might write some code in C in the Light Theme while another User may write a Python code in the Dark Theme all at the same time. This dynamic behavior that partially depends upon the user itself makes the webpage an Active webpage. Now how can this be related to Updation? Updation is the phase where the states and props of a component are updated followed by some user events such as clicking, pressing a key on the keyboard, etc. The following are the descriptions of functions that are invoked at different points of Updation phase." }, { "code": null, "e": 31488, "s": 31103, "text": "componentWillReceiveProps() Function: This is a Props exclusive Function and is independent of States. This function is invoked before a mounted component gets its props reassigned. The function is passed the new set of Props which may or may not be identical to the original Props. Thus checking is a mandatory step in this regard. The following code snippet shows a sample use-case." }, { "code": null, "e": 31499, "s": 31488, "text": "Javascript" }, { "code": "componentWillReceiveProps(newProps) { if (this.props !== newProps) { console.log(\" New Props have been assigned \"); // Use this.setState() to rerender the page. } } ", "e": 31689, "s": 31499, "text": null }, { "code": null, "e": 31916, "s": 31689, "text": "setState() Function: This is not particularly a Lifecycle function and can be invoked explicitly at any instant. This function is used to update the state of a component. You may refer to this article for detailed information." }, { "code": null, "e": 32651, "s": 31916, "text": "shouldComponentUpdate() Function: By default, every state or props update re-render the page but this may not always be the desired outcome, sometimes it is desired that updating the page will not be repainted. The shouldComponentUpdate() Function fulfills the requirement by letting React know whether the component’s output will be affected by the update or not. shouldComponentUpdate() is invoked before rendering an already mounted component when new props or state are being received. If returned false then the subsequent steps of rendering will not be carried out. This function can’t be used in the case of forceUpdate(). The Function takes the new Props and new State as the arguments and returns whether to re-render or not." }, { "code": null, "e": 32889, "s": 32651, "text": "componentWillUpdate() Function: As the name clearly suggests, this function is invoked before the component is rerendered i.e. this function gets invoked once before the render() function is executed after the updation of State or Props." }, { "code": null, "e": 33104, "s": 32889, "text": "componentDidUpdate() Function: Similarly this function is invoked after the component is rerendered i.e. this function gets invoked once after the render() function is executed after the updation of State or Props." }, { "code": null, "e": 33313, "s": 33104, "text": " 4. Unmounting: This is the final phase of the lifecycle of the component that is the phase of unmounting the component from the DOM. The following function is the sole member of this phase." }, { "code": null, "e": 33552, "s": 33313, "text": "componentWillUnmount() Function: This function is invoked before the component is finally unmounted from the DOM i.e. this function gets invoked once before the component is removed from the page and this denotes the end of the lifecycle." }, { "code": null, "e": 33809, "s": 33552, "text": "We have so far discussed every predefined function there was in the lifecycle of the component, and we have also specified the order of execution of the function. Let us now see one final example to finish the article while revising what’s discussed above." }, { "code": null, "e": 33884, "s": 33809, "text": "First, create a react app and edit your index.js file from the src folder." }, { "code": null, "e": 33898, "s": 33884, "text": "src index.js:" }, { "code": null, "e": 33909, "s": 33898, "text": "Javascript" }, { "code": "import React from 'react'; import ReactDOM from 'react-dom'; class Test extends React.Component { constructor(props) { super(props); this.state = { hello : \"World!\" }; } componentWillMount() { console.log(\"componentWillMount()\"); } componentDidMount() { console.log(\"componentDidMount()\"); } changeState() { this.setState({ hello : \"Geek!\" }); } render() { return ( <div> <h1>GeeksForGeeks.org, Hello{ this.state.hello }</h1> <h2> <a onClick={this.changeState.bind(this)}>Press Here!</a> </h2> </div>); } shouldComponentUpdate(nextProps, nextState) { console.log(\"shouldComponentUpdate()\"); return true; } componentWillUpdate() { console.log(\"componentWillUpdate()\"); } componentDidUpdate() { console.log(\"componentDidUpdate()\"); } } ReactDOM.render( <Test />, document.getElementById('root')); ", "e": 34979, "s": 33909, "text": null }, { "code": null, "e": 34987, "s": 34979, "text": "Output:" }, { "code": null, "e": 35001, "s": 34987, "text": "shubhamyadav4" }, { "code": null, "e": 35017, "s": 35001, "text": "akshitsaxenaa09" }, { "code": null, "e": 35026, "s": 35017, "text": "react-js" }, { "code": null, "e": 35043, "s": 35026, "text": "Web Technologies" }, { "code": null, "e": 35141, "s": 35043, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35150, "s": 35141, "text": "Comments" }, { "code": null, "e": 35163, "s": 35150, "text": "Old Comments" }, { "code": null, "e": 35205, "s": 35163, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 35238, "s": 35205, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35281, "s": 35238, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 35343, "s": 35281, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 35393, "s": 35343, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 35438, "s": 35393, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35507, "s": 35438, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 35568, "s": 35507, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35626, "s": 35568, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Synchronizing Threads in Python
The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock. The acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock. If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released. The release() method of the new lock object is used to release the lock when it is no longer required. #!/usr/bin/python import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name # Get lock to synchronize threads threadLock.acquire() print_time(self.name, self.counter, 3) # Free lock to release next thread threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 threadLock = threading.Lock() threads = [] # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread" When the above code is executed, it produces the following result − Starting Thread-1 Starting Thread-2 Thread-1: Thu Mar 21 09:11:28 2013 Thread-1: Thu Mar 21 09:11:29 2013 Thread-1: Thu Mar 21 09:11:30 2013 Thread-2: Thu Mar 21 09:11:32 2013 Thread-2: Thu Mar 21 09:11:34 2013 Thread-2: Thu Mar 21 09:11:36 2013 Exiting Main Thread
[ { "code": null, "e": 1273, "s": 1062, "text": "The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock." }, { "code": null, "e": 1473, "s": 1273, "text": "The acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock." }, { "code": null, "e": 1695, "s": 1473, "text": "If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released." }, { "code": null, "e": 1798, "s": 1695, "text": "The release() method of the new lock object is used to release the lock when it is no longer required." }, { "code": null, "e": 2806, "s": 1798, "text": "#!/usr/bin/python\nimport threading\nimport time\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print \"Starting \" + self.name\n # Get lock to synchronize threads\n threadLock.acquire()\n print_time(self.name, self.counter, 3)\n # Free lock to release next thread\n threadLock.release()\ndef print_time(threadName, delay, counter):\n while counter:\n time.sleep(delay)\n print \"%s: %s\" % (threadName, time.ctime(time.time()))\n counter -= 1\nthreadLock = threading.Lock()\nthreads = []\n# Create new threads\nthread1 = myThread(1, \"Thread-1\", 1)\nthread2 = myThread(2, \"Thread-2\", 2)\n# Start new Threads\nthread1.start()\nthread2.start()\n# Add threads to thread list\nthreads.append(thread1)\nthreads.append(thread2)\n# Wait for all threads to complete\nfor t in threads:\n t.join()\nprint \"Exiting Main Thread\"" }, { "code": null, "e": 2874, "s": 2806, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3140, "s": 2874, "text": "Starting Thread-1\nStarting Thread-2\nThread-1: Thu Mar 21 09:11:28 2013\nThread-1: Thu Mar 21 09:11:29 2013\nThread-1: Thu Mar 21 09:11:30 2013\nThread-2: Thu Mar 21 09:11:32 2013\nThread-2: Thu Mar 21 09:11:34 2013\nThread-2: Thu Mar 21 09:11:36 2013\nExiting Main Thread" } ]
Markov Clustering Algorithm. In this post, we describe an... | by Arun Jagota | Towards Data Science
In this post, we describe an interesting and effective graph-based clustering algorithm called Markov clustering. Like other graph-based clustering algorithms and unlike K-means clustering, this algorithm does not require the number of clusters to be known in advance. (For more on this, see [1].) This algorithm is very popular in clustering bioinformatics data, specifically to cluster protein sequences and to cluster genes from co-expression data [2]. This algorithm also lends itself to distributed computing [2]. As discussed there, the algorithm was able to utilize 2000 compute nodes to cluster a graph of about 70 million nodes and about 68 billion edges in less than 21⁄2 hours. In this post, we have just one aim: to describe the algorithm at an intuitive level, with suitably chosen examples that bring out its distinguishing features. The Random Walk Principle The motivating idea in MCL is that if you start walking randomly from a node, you are more likely to move around in the same cluster than to cross clusters. This is because by definition clusters are internally dense while being separated by sparse regions. In graph clustering, density and sparsity is defined in terms of the proportion of edge slots that have edges in them. Let’s see an example. The random walk will remain within the connected component where it starts, i.e. with {a, b} or within {c, d, e}. There is no way to get across. We could interpret this behavior as discovering the connected components as clusters. Okay, that’s a very simple example just to get us started. MCL would not be interesting if that’s all it could do. Let’s see a more interesting example. Say we start the walk at node a. The walker will meander around but will eventually get to node e. Once it arrives at e, it is likely to revisit e soon. To see this, note that from e the next step is either to d, f, g, h, or i. In 3 of these 5, the step that follows will bring the walker back to e. You could say that the walker has discovered a core node in a cluster, in this case e. How could it record this information? By just maintaining a counter for each node which records the number of times that node has been visited in a certain unit of time. As we will see soon, there is a more efficient way to record this information. Random walking is just a convenient way to explain the algorithm’s behavior. That said, we’ll stick with random walking for a while longer, as it has more insights to offer. Let’s continue walking where we left off. Because e gets visited frequently, at some point we will walk from e to i. And at some point shortly thereafter, from i to j. Once j has been visited for the first time, it will get visited frequently again for the same reason that e was. j is a second core node we have discovered. Beyond Discovering Core Nodes Encouraged by our finding that we can discover core nodes by walking randomly, let’s dig deeper to see what else we can do. Consider the example below. Think of the two 4-cliques (fully connected subgraphs on 4 nodes) as the clusters. The edge a-b crosses the two clusters. Ignore the nodes of degree 1 for now. Consider starting from node a and walking k steps. What is the probability distribution over the various nodes we end up at? Before looking at this, let’s define a key term, as it will keep cropping up in our discussion. The degree of a node is the number of edges that it touches. When k is 1, the probability of ending up at node e is 1⁄4 since a’s degree is 4. When k is 2, the probability of ending up at e is 0 because there is no way to reach e from a in exactly two hops. When k is 3, the walks of length 3 that end at e have one of two structures a → { b or c or d } → a → ea → e → { f or g or h } → e So there are 6 such walks. The total number of distinct walks from node a of length 3 are 4*4*4 = 64 since every interior node on any of these walks has degree 4. So the probability of walking from a to e in exactly 3 steps is 6/64. Way less than 1⁄4. We can think of it this way. When we took just one step from a, all we see is a’s neighbors. So the 1-step probability of ending up at e, while low, is not very low. If we walk a few more steps, we discover the cluster structure of a and realize that we are much more likely to stay within there than end up at e. That said, if we walk too long, say k=20 steps, the situation gets more diffuse. Simply put whereas the first walk from a to e is a rare event, once we have walked to e, the probability of visiting e again in the next few steps increases as we are now in e’s cluster. How can we take advantage of this behavior? At this point, we’ll bring in Markov chains. Consider, for every pair of nodes u and v, Puv(k), the probability of starting from node u and ending up at node v after walking k steps. Puv(1) is easily computed: it is just 1 divided by u’s degree. Now comes the key point. If we multiply the matrix P(1)=P with itself, we get P(2) = P2. More generally, P(k) = P^k. This suggests the following procedure. We initialize P. We then compute P(k) by multiplying P with itself k times. (k is typically 2 or 3.) If some transition probability Puv(k) is especially low, way lower than Puv(1) is, we drive it further towards 0. A way to do this is to take each probability in P(k), raise it to a power greater than 1, and renormalize. In MCL, this process is called inflation. It enhances differences. The rich get richer. Putting this all together, the algorithm goes as follows: Initialize P from the graphrepeat Q = P^k P = inflate(Q)until happyPrune away especially low-probability transitionsFind (strongly) connected components in the remaining directed graph We can interpret this algorithm as trying to find transitions that cross cluster boundaries and reduce their probabilities. Why do we iterate then? Because there is a risk of pruning away edges in the same cluster if we don’t iterate enough first. On the other hand, if we iterate without doing an inflation inside an iteration, we may diffuse the transition probabilities too rapidly and lose whatever we gained in the first few iterations. (We already saw an example of this.) Inflating seems to make the algorithm somewhat robust against this. Specifically, by deflating low probability transitions, we are forcing the algorithm to explore regions of the graph it might not yet have explored. Take an extreme form of this. Say we block a low-probability transition u → v, i.e. truncate the probability to 0. We are forcing the algorithm to try to find a different way to get from u to v if it can. If it can’t, we now gain more confidence that the transition from u to v crosses cluster boundaries. Ideally, after all the iterations have ended, the especially low-probability transitions are the ones that cross cluster boundaries. We can then clip these. This results in a directed graph whose strongly connected components are the clusters. In our example, the probabilities of the transitions from a to e and e to a would both reduce. We can interpret this as deleting the edge a-e in the undirected graph. The clusters are now the connected components, which can be found by a connected-components finding graph algorithm. Summary In this post, we explained, with suitably chosen examples, how the Markov clustering algorithm works. We started by explaining how random walks on a graph can discover core nodes within clusters. We then discussed how taking powers of the Markov matrix helps us distinguish between within-cluster transitions and across-cluster transitions. We discussed how doing inflation further enhances these distinctions. Interspersing inflation allows us to continue exploring the graph without risking diluting the transition probabilities too much. This algorithm is also attractive from the point of view of implementation. At its core, it uses very simple algebraic operations: powers of a matrix, and inflation. Consequently, it is very easy to implement for small-to-moderate size problems. For especially large problems, we can take advantage of the existence of efficient parallel algorithms for taking powers of a sparse matrix as mentioned in [2] below. Further Reading Density-based and Graph-based Clustering | by Arun Jagota | Dec, 2020 | Towards Data Sciencehttps://pubmed.ncbi.nlm.nih.gov/29315405/ Density-based and Graph-based Clustering | by Arun Jagota | Dec, 2020 | Towards Data Science
[ { "code": null, "e": 470, "s": 172, "text": "In this post, we describe an interesting and effective graph-based clustering algorithm called Markov clustering. Like other graph-based clustering algorithms and unlike K-means clustering, this algorithm does not require the number of clusters to be known in advance. (For more on this, see [1].)" }, { "code": null, "e": 861, "s": 470, "text": "This algorithm is very popular in clustering bioinformatics data, specifically to cluster protein sequences and to cluster genes from co-expression data [2]. This algorithm also lends itself to distributed computing [2]. As discussed there, the algorithm was able to utilize 2000 compute nodes to cluster a graph of about 70 million nodes and about 68 billion edges in less than 21⁄2 hours." }, { "code": null, "e": 1020, "s": 861, "text": "In this post, we have just one aim: to describe the algorithm at an intuitive level, with suitably chosen examples that bring out its distinguishing features." }, { "code": null, "e": 1046, "s": 1020, "text": "The Random Walk Principle" }, { "code": null, "e": 1423, "s": 1046, "text": "The motivating idea in MCL is that if you start walking randomly from a node, you are more likely to move around in the same cluster than to cross clusters. This is because by definition clusters are internally dense while being separated by sparse regions. In graph clustering, density and sparsity is defined in terms of the proportion of edge slots that have edges in them." }, { "code": null, "e": 1445, "s": 1423, "text": "Let’s see an example." }, { "code": null, "e": 1590, "s": 1445, "text": "The random walk will remain within the connected component where it starts, i.e. with {a, b} or within {c, d, e}. There is no way to get across." }, { "code": null, "e": 1676, "s": 1590, "text": "We could interpret this behavior as discovering the connected components as clusters." }, { "code": null, "e": 1829, "s": 1676, "text": "Okay, that’s a very simple example just to get us started. MCL would not be interesting if that’s all it could do. Let’s see a more interesting example." }, { "code": null, "e": 2216, "s": 1829, "text": "Say we start the walk at node a. The walker will meander around but will eventually get to node e. Once it arrives at e, it is likely to revisit e soon. To see this, note that from e the next step is either to d, f, g, h, or i. In 3 of these 5, the step that follows will bring the walker back to e. You could say that the walker has discovered a core node in a cluster, in this case e." }, { "code": null, "e": 2386, "s": 2216, "text": "How could it record this information? By just maintaining a counter for each node which records the number of times that node has been visited in a certain unit of time." }, { "code": null, "e": 2639, "s": 2386, "text": "As we will see soon, there is a more efficient way to record this information. Random walking is just a convenient way to explain the algorithm’s behavior. That said, we’ll stick with random walking for a while longer, as it has more insights to offer." }, { "code": null, "e": 2964, "s": 2639, "text": "Let’s continue walking where we left off. Because e gets visited frequently, at some point we will walk from e to i. And at some point shortly thereafter, from i to j. Once j has been visited for the first time, it will get visited frequently again for the same reason that e was. j is a second core node we have discovered." }, { "code": null, "e": 2994, "s": 2964, "text": "Beyond Discovering Core Nodes" }, { "code": null, "e": 3118, "s": 2994, "text": "Encouraged by our finding that we can discover core nodes by walking randomly, let’s dig deeper to see what else we can do." }, { "code": null, "e": 3306, "s": 3118, "text": "Consider the example below. Think of the two 4-cliques (fully connected subgraphs on 4 nodes) as the clusters. The edge a-b crosses the two clusters. Ignore the nodes of degree 1 for now." }, { "code": null, "e": 3431, "s": 3306, "text": "Consider starting from node a and walking k steps. What is the probability distribution over the various nodes we end up at?" }, { "code": null, "e": 3588, "s": 3431, "text": "Before looking at this, let’s define a key term, as it will keep cropping up in our discussion. The degree of a node is the number of edges that it touches." }, { "code": null, "e": 3861, "s": 3588, "text": "When k is 1, the probability of ending up at node e is 1⁄4 since a’s degree is 4. When k is 2, the probability of ending up at e is 0 because there is no way to reach e from a in exactly two hops. When k is 3, the walks of length 3 that end at e have one of two structures" }, { "code": null, "e": 3916, "s": 3861, "text": "a → { b or c or d } → a → ea → e → { f or g or h } → e" }, { "code": null, "e": 4168, "s": 3916, "text": "So there are 6 such walks. The total number of distinct walks from node a of length 3 are 4*4*4 = 64 since every interior node on any of these walks has degree 4. So the probability of walking from a to e in exactly 3 steps is 6/64. Way less than 1⁄4." }, { "code": null, "e": 4482, "s": 4168, "text": "We can think of it this way. When we took just one step from a, all we see is a’s neighbors. So the 1-step probability of ending up at e, while low, is not very low. If we walk a few more steps, we discover the cluster structure of a and realize that we are much more likely to stay within there than end up at e." }, { "code": null, "e": 4750, "s": 4482, "text": "That said, if we walk too long, say k=20 steps, the situation gets more diffuse. Simply put whereas the first walk from a to e is a rare event, once we have walked to e, the probability of visiting e again in the next few steps increases as we are now in e’s cluster." }, { "code": null, "e": 4794, "s": 4750, "text": "How can we take advantage of this behavior?" }, { "code": null, "e": 5040, "s": 4794, "text": "At this point, we’ll bring in Markov chains. Consider, for every pair of nodes u and v, Puv(k), the probability of starting from node u and ending up at node v after walking k steps. Puv(1) is easily computed: it is just 1 divided by u’s degree." }, { "code": null, "e": 5157, "s": 5040, "text": "Now comes the key point. If we multiply the matrix P(1)=P with itself, we get P(2) = P2. More generally, P(k) = P^k." }, { "code": null, "e": 5606, "s": 5157, "text": "This suggests the following procedure. We initialize P. We then compute P(k) by multiplying P with itself k times. (k is typically 2 or 3.) If some transition probability Puv(k) is especially low, way lower than Puv(1) is, we drive it further towards 0. A way to do this is to take each probability in P(k), raise it to a power greater than 1, and renormalize. In MCL, this process is called inflation. It enhances differences. The rich get richer." }, { "code": null, "e": 5664, "s": 5606, "text": "Putting this all together, the algorithm goes as follows:" }, { "code": null, "e": 5852, "s": 5664, "text": "Initialize P from the graphrepeat Q = P^k P = inflate(Q)until happyPrune away especially low-probability transitionsFind (strongly) connected components in the remaining directed graph" }, { "code": null, "e": 5976, "s": 5852, "text": "We can interpret this algorithm as trying to find transitions that cross cluster boundaries and reduce their probabilities." }, { "code": null, "e": 6100, "s": 5976, "text": "Why do we iterate then? Because there is a risk of pruning away edges in the same cluster if we don’t iterate enough first." }, { "code": null, "e": 6399, "s": 6100, "text": "On the other hand, if we iterate without doing an inflation inside an iteration, we may diffuse the transition probabilities too rapidly and lose whatever we gained in the first few iterations. (We already saw an example of this.) Inflating seems to make the algorithm somewhat robust against this." }, { "code": null, "e": 6854, "s": 6399, "text": "Specifically, by deflating low probability transitions, we are forcing the algorithm to explore regions of the graph it might not yet have explored. Take an extreme form of this. Say we block a low-probability transition u → v, i.e. truncate the probability to 0. We are forcing the algorithm to try to find a different way to get from u to v if it can. If it can’t, we now gain more confidence that the transition from u to v crosses cluster boundaries." }, { "code": null, "e": 7098, "s": 6854, "text": "Ideally, after all the iterations have ended, the especially low-probability transitions are the ones that cross cluster boundaries. We can then clip these. This results in a directed graph whose strongly connected components are the clusters." }, { "code": null, "e": 7382, "s": 7098, "text": "In our example, the probabilities of the transitions from a to e and e to a would both reduce. We can interpret this as deleting the edge a-e in the undirected graph. The clusters are now the connected components, which can be found by a connected-components finding graph algorithm." }, { "code": null, "e": 7390, "s": 7382, "text": "Summary" }, { "code": null, "e": 7931, "s": 7390, "text": "In this post, we explained, with suitably chosen examples, how the Markov clustering algorithm works. We started by explaining how random walks on a graph can discover core nodes within clusters. We then discussed how taking powers of the Markov matrix helps us distinguish between within-cluster transitions and across-cluster transitions. We discussed how doing inflation further enhances these distinctions. Interspersing inflation allows us to continue exploring the graph without risking diluting the transition probabilities too much." }, { "code": null, "e": 8344, "s": 7931, "text": "This algorithm is also attractive from the point of view of implementation. At its core, it uses very simple algebraic operations: powers of a matrix, and inflation. Consequently, it is very easy to implement for small-to-moderate size problems. For especially large problems, we can take advantage of the existence of efficient parallel algorithms for taking powers of a sparse matrix as mentioned in [2] below." }, { "code": null, "e": 8360, "s": 8344, "text": "Further Reading" }, { "code": null, "e": 8494, "s": 8360, "text": "Density-based and Graph-based Clustering | by Arun Jagota | Dec, 2020 | Towards Data Sciencehttps://pubmed.ncbi.nlm.nih.gov/29315405/" } ]
Instruction type MOV r, M in 8085 Microprocessor
In 8085 Instruction set, MOV r, M is an instruction where the 8-bit data content of the memory location as pointed by HL register pair will be moved to the register r. Thus this is an instruction to load register r with the 8-bit value from a specified memory location whose 16-bit address is in HL register pair. As r can have any of the seven values, there are seven opcodes for this type of instruction. r = A, B, C, D, E, H, or L It occupies only 1-Byte in memory. MOV E, M is an example instruction of this type. It is a 1-Byte instruction. Suppose E register content is DBH, H register content is 40H, and L register content is 50H. Let us say location 4050H has the data value AAH. When the 8085 executes this instruction, the contents of E register will change to AAH, as shown below. (E) (HL) (4050H) The timing diagram for this MOV E, M instruction is as follows − Summary − So this instruction MOV E, M requires 1-Byte, 2-Machine Cycles (Opcode Fetch, Memory Read) and 7 T-States for execution as shown in the timing diagram.
[ { "code": null, "e": 1376, "s": 1062, "text": "In 8085 Instruction set, MOV r, M is an instruction where the 8-bit data content of the memory location as pointed by HL register pair will be moved to the register r. Thus this is an instruction to load register r with the 8-bit value from a specified memory location whose 16-bit address is in HL register pair." }, { "code": null, "e": 1469, "s": 1376, "text": "As r can have any of the seven values, there are seven opcodes for this type of instruction." }, { "code": null, "e": 1497, "s": 1469, "text": "r = A, B, C, D, E, H, or L\n" }, { "code": null, "e": 1856, "s": 1497, "text": "It occupies only 1-Byte in memory. MOV E, M is an example instruction of this type. It is a 1-Byte instruction. Suppose E register content is DBH, H register content is 40H, and L register content is 50H. Let us say location 4050H has the data value AAH. When the 8085 executes this instruction, the contents of E register will change to AAH, as shown below." }, { "code": null, "e": 1860, "s": 1856, "text": "(E)" }, { "code": null, "e": 1865, "s": 1860, "text": "(HL)" }, { "code": null, "e": 1873, "s": 1865, "text": "(4050H)" }, { "code": null, "e": 1938, "s": 1873, "text": "The timing diagram for this MOV E, M instruction is as follows −" }, { "code": null, "e": 2100, "s": 1938, "text": "Summary − So this instruction MOV E, M requires 1-Byte, 2-Machine Cycles (Opcode Fetch, Memory Read) and 7 T-States for execution as shown in the timing diagram." } ]
MySQL query to check how to get time difference
Let us first create a table − mysql> create table DemoTable1570 -> ( -> ArrivalTime datetime -> ); Query OK, 0 rows affected (0.87 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1570 values('2019-10-15 5:10:00'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable1570 values('2019-10-15 23:00:00'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1570 values('2019-10-15 23:10:00'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1570 values('2019-10-15 16:10:00'); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement − mysql> select * from DemoTable1570; This will produce the following output +---------------------+ | ArrivalTime | +---------------------+ | 2019-10-15 05:10:00 | | 2019-10-15 23:00:00 | | 2019-10-15 23:10:00 | | 2019-10-15 16:10:00 | +---------------------+ 4 rows in set (0.00 sec) The current date is as follows − mysql> select now(); +---------------------+ | now() | +---------------------+ | 2019-10-15 22:26:14 | +---------------------+ 1 row in set (0.00 sec) Following is the query to get time difference − mysql> select * from DemoTable1570 -> where ArrivalTime > now() - interval 5 hour; This will produce the following output +---------------------+ | ArrivalTime | +---------------------+ | 2019-10-15 23:00:00 | | 2019-10-15 23:10:00 | +---------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1207, "s": 1092, "text": "mysql> create table DemoTable1570\n -> (\n -> ArrivalTime datetime\n -> );\nQuery OK, 0 rows affected (0.87 sec)" }, { "code": null, "e": 1263, "s": 1207, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1662, "s": 1263, "text": "mysql> insert into DemoTable1570 values('2019-10-15 5:10:00');\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into DemoTable1570 values('2019-10-15 23:00:00');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1570 values('2019-10-15 23:10:00');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1570 values('2019-10-15 16:10:00');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1722, "s": 1662, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1758, "s": 1722, "text": "mysql> select * from DemoTable1570;" }, { "code": null, "e": 1797, "s": 1758, "text": "This will produce the following output" }, { "code": null, "e": 2014, "s": 1797, "text": "+---------------------+\n| ArrivalTime |\n+---------------------+\n| 2019-10-15 05:10:00 |\n| 2019-10-15 23:00:00 |\n| 2019-10-15 23:10:00 |\n| 2019-10-15 16:10:00 |\n+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2047, "s": 2014, "text": "The current date is as follows −" }, { "code": null, "e": 2212, "s": 2047, "text": "mysql> select now();\n+---------------------+\n| now() |\n+---------------------+\n| 2019-10-15 22:26:14 |\n+---------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2260, "s": 2212, "text": "Following is the query to get time difference −" }, { "code": null, "e": 2346, "s": 2260, "text": "mysql> select * from DemoTable1570\n -> where ArrivalTime > now() - interval 5 hour;" }, { "code": null, "e": 2385, "s": 2346, "text": "This will produce the following output" }, { "code": null, "e": 2554, "s": 2385, "text": "+---------------------+\n| ArrivalTime |\n+---------------------+\n| 2019-10-15 23:00:00 |\n| 2019-10-15 23:10:00 |\n+---------------------+\n2 rows in set (0.00 sec)" } ]