title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Multi Threading Models in Process Management - GeeksforGeeks
31 May, 2021 Multi threading-It is a process of multiple threads executes at same time. Many operating systems support kernel thread and user thread in a combined way. Example of such system is Solaris. Multi threading model are of three types. Many to many model. Many to one model. one to one model. Many to Many Model In this model, we have multiple user threads multiplex to same or lesser number of kernel level threads. Number of kernel level threads are specific to the machine, advantage of this model is if a user thread is blocked we can schedule others user thread to other kernel thread. Thus, System doesn’t block if a particular thread is blocked. It is the best multi threading model. Many to One Model In this model, we have multiple user threads mapped to one kernel thread. In this model when a user thread makes a blocking system call entire process blocks. As we have only one kernel thread and only one user thread can access kernel at a time, so multiple threads are not able access multiprocessor at the same time. The thread management is done on the user level so it is more efficient. One to One Model In this model, one to one relationship between kernel and user thread. In this model multiple thread can run on multiple processor. Problem with this model is that creating a user thread requires the corresponding kernel thread. As each user thread is connected to different kernel , if any user thread makes a blocking system call, the other user threads won’t be blocked. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above akshittrivedi1005 Processes & Threads Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System Program for Round Robin scheduling | Set 1 Introduction of Deadlock in Operating System Introduction of Operating System - Set 1 CPU Scheduling in Operating Systems Disk Scheduling Algorithms Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Preemptive and Non-Preemptive Scheduling
[ { "code": null, "e": 24508, "s": 24480, "text": "\n31 May, 2021" }, { "code": null, "e": 24583, "s": 24508, "text": "Multi threading-It is a process of multiple threads executes at same time." }, { "code": null, "e": 24742, "s": 24583, "text": "Many operating systems support kernel thread and user thread in a combined way. Example of such system is Solaris. Multi threading model are of three types. " }, { "code": null, "e": 24799, "s": 24742, "text": "Many to many model.\nMany to one model.\none to one model." }, { "code": null, "e": 24819, "s": 24799, "text": "Many to Many Model " }, { "code": null, "e": 25161, "s": 24819, "text": "In this model, we have multiple user threads multiplex to same or lesser number of kernel level threads. Number of kernel level threads are specific to the machine, advantage of this model is if a user thread is blocked we can schedule others user thread to other kernel thread. Thus, System doesn’t block if a particular thread is blocked. " }, { "code": null, "e": 25199, "s": 25161, "text": "It is the best multi threading model." }, { "code": null, "e": 25220, "s": 25201, "text": "Many to One Model " }, { "code": null, "e": 25541, "s": 25220, "text": "In this model, we have multiple user threads mapped to one kernel thread. In this model when a user thread makes a blocking system call entire process blocks. As we have only one kernel thread and only one user thread can access kernel at a time, so multiple threads are not able access multiprocessor at the same time. " }, { "code": null, "e": 25614, "s": 25541, "text": "The thread management is done on the user level so it is more efficient." }, { "code": null, "e": 25863, "s": 25616, "text": "One to One Model In this model, one to one relationship between kernel and user thread. In this model multiple thread can run on multiple processor. Problem with this model is that creating a user thread requires the corresponding kernel thread. " }, { "code": null, "e": 26008, "s": 25863, "text": "As each user thread is connected to different kernel , if any user thread makes a blocking system call, the other user threads won’t be blocked." }, { "code": null, "e": 26135, "s": 26010, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 26153, "s": 26135, "text": "akshittrivedi1005" }, { "code": null, "e": 26173, "s": 26153, "text": "Processes & Threads" }, { "code": null, "e": 26191, "s": 26173, "text": "Operating Systems" }, { "code": null, "e": 26209, "s": 26191, "text": "Operating Systems" }, { "code": null, "e": 26307, "s": 26209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26356, "s": 26307, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 26396, "s": 26356, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 26423, "s": 26396, "text": "Paging in Operating System" }, { "code": null, "e": 26466, "s": 26423, "text": "Program for Round Robin scheduling | Set 1" }, { "code": null, "e": 26511, "s": 26466, "text": "Introduction of Deadlock in Operating System" }, { "code": null, "e": 26552, "s": 26511, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 26588, "s": 26552, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 26615, "s": 26588, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 26696, "s": 26615, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" } ]
How to Solve java.lang.ClassNotFoundException in Java? - GeeksforGeeks
30 Sep, 2021 ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. In older days, there are no editors like Eclipse are available. Even in Notepad, people have done java coding and by using the “javac” command to compile the java files, and they will create a ‘.class’ file. Sometimes accidentally the generated class files might be lost or set in different locations and hence there are a lot of chances of “ClassNotFoundException” occurs. After the existence of editors like Eclipse, Netbeans, etc., IDE creates a “ClassPath” file kind of entries. From the above image, we can see that many jar files are present. They are absolutely necessary if the java code wants to interact with MySQL, MongoDB, etc., kind of databases, and also few functionalities need these jar files to be present in the build path. If they are not added, first editors show the errors themselves and provide the option of corrections too. Implementation: Sample program of connecting to MySQL database and get the contents Example Java // Java Program to check for MySQL connectivity Issue // Importing database (SQL) librariesimport java.sql.*; // Main Classpublic class MySQLConnectivityCheck { public static void main(String[] args) { // Display message for better readability System.out.println( "---------------------------------------------"); // Initially setting connection object // and result set to null Connection con = null; ResultSet res = null; // Try block to check for exceptions try { // We need to have mysql-connector-java-8.0.22 // or relevant jars in build path of project // Loading drivers // This driver is the latest one Class.forName("com.mysql.cj.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", ""); // Try block to check for exceptions try { // Set of statements to be checked } // Catch block 1 catch (SQLException s) { // Display message when SQLException is // encountered System.out.println( "SQL statement is not executed!"); } } catch (Exception e) { // In case of general Exception // print and display the line number where the // exception occurred e.printStackTrace(); } finally { // Finally for all cases indirectly closing the // connections & making the resultset and // connection object to null res = null; con = null; } }} Output: Case 1: In the above code, we are using com.mysql.cj.jdbc.Driver and in that case if we are not having mysql-connector-java-8.0.22.jar, then we will be getting ClassNotFoundException. Case 2: So, keep the jar in the build path as shown below. Note: Similarly for any database connectivity, we need to have the respective jars for connecting to that database. The list of database driver jars required by java to overcome ClassNotFoundException is given below in a tabular format Note: When we are developing Web based applications, the jars must be present in ‘WEB-INF/lib directory’. In Maven projects, jar dependency should be present in pom.xml Sample snippet of pom.xml for spring boot Example 1 With Spring boot XML <!-- Spring boot mongodb dependency --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId></dependency> Example 2 Without spring boot XML <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver --><dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.6.3</version></dependency> Example 3 Gradle based dependencies (MongoDB) XML dependencies { compile 'org.mongodb:mongodb-driver:3.2.2' } Similarly, other DB drivers can be specified in this way. It depends upon the project nature, the dependencies has to be fixed. For ordinary class level projects, all the classes i.e parent class, child class, etc should be available in the classpath. If there are errors, then also .class file will not be created which leads to ClassNotFoundException, and hence in order to get the whole code working, one should correct the errors first by fixing the dependencies. IDE is much helpful to overcome such sort scenarios such as when the program throws ClassNotFoundException, it will provide suggestions to users about the necessity of inclusion of jar files(which contains necessary functionalities like connecting to database. adnanirshad158 gabaa406 Java-Exceptions Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25347, "s": 25319, "text": "\n30 Sep, 2021" }, { "code": null, "e": 25531, "s": 25347, "text": "ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath." }, { "code": null, "e": 26014, "s": 25531, "text": "In older days, there are no editors like Eclipse are available. Even in Notepad, people have done java coding and by using the “javac” command to compile the java files, and they will create a ‘.class’ file. Sometimes accidentally the generated class files might be lost or set in different locations and hence there are a lot of chances of “ClassNotFoundException” occurs. After the existence of editors like Eclipse, Netbeans, etc., IDE creates a “ClassPath” file kind of entries." }, { "code": null, "e": 26381, "s": 26014, "text": "From the above image, we can see that many jar files are present. They are absolutely necessary if the java code wants to interact with MySQL, MongoDB, etc., kind of databases, and also few functionalities need these jar files to be present in the build path. If they are not added, first editors show the errors themselves and provide the option of corrections too." }, { "code": null, "e": 26465, "s": 26381, "text": "Implementation: Sample program of connecting to MySQL database and get the contents" }, { "code": null, "e": 26473, "s": 26465, "text": "Example" }, { "code": null, "e": 26478, "s": 26473, "text": "Java" }, { "code": "// Java Program to check for MySQL connectivity Issue // Importing database (SQL) librariesimport java.sql.*; // Main Classpublic class MySQLConnectivityCheck { public static void main(String[] args) { // Display message for better readability System.out.println( \"---------------------------------------------\"); // Initially setting connection object // and result set to null Connection con = null; ResultSet res = null; // Try block to check for exceptions try { // We need to have mysql-connector-java-8.0.22 // or relevant jars in build path of project // Loading drivers // This driver is the latest one Class.forName(\"com.mysql.cj.jdbc.Driver\"); con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/test?serverTimezone=UTC\", \"root\", \"\"); // Try block to check for exceptions try { // Set of statements to be checked } // Catch block 1 catch (SQLException s) { // Display message when SQLException is // encountered System.out.println( \"SQL statement is not executed!\"); } } catch (Exception e) { // In case of general Exception // print and display the line number where the // exception occurred e.printStackTrace(); } finally { // Finally for all cases indirectly closing the // connections & making the resultset and // connection object to null res = null; con = null; } }}", "e": 28240, "s": 26478, "text": null }, { "code": null, "e": 28248, "s": 28240, "text": "Output:" }, { "code": null, "e": 28432, "s": 28248, "text": "Case 1: In the above code, we are using com.mysql.cj.jdbc.Driver and in that case if we are not having mysql-connector-java-8.0.22.jar, then we will be getting ClassNotFoundException." }, { "code": null, "e": 28493, "s": 28434, "text": "Case 2: So, keep the jar in the build path as shown below." }, { "code": null, "e": 28730, "s": 28493, "text": "Note: Similarly for any database connectivity, we need to have the respective jars for connecting to that database. The list of database driver jars required by java to overcome ClassNotFoundException is given below in a tabular format " }, { "code": null, "e": 28737, "s": 28730, "text": "Note: " }, { "code": null, "e": 28837, "s": 28737, "text": "When we are developing Web based applications, the jars must be present in ‘WEB-INF/lib directory’." }, { "code": null, "e": 28900, "s": 28837, "text": "In Maven projects, jar dependency should be present in pom.xml" }, { "code": null, "e": 28942, "s": 28900, "text": "Sample snippet of pom.xml for spring boot" }, { "code": null, "e": 28969, "s": 28942, "text": "Example 1 With Spring boot" }, { "code": null, "e": 28973, "s": 28969, "text": "XML" }, { "code": "<!-- Spring boot mongodb dependency --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>", "e": 29162, "s": 28973, "text": null }, { "code": null, "e": 29192, "s": 29162, "text": "Example 2 Without spring boot" }, { "code": null, "e": 29196, "s": 29192, "text": "XML" }, { "code": "<!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver --><dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.6.3</version></dependency>", "e": 29397, "s": 29196, "text": null }, { "code": null, "e": 29444, "s": 29397, "text": "Example 3 Gradle based dependencies (MongoDB) " }, { "code": null, "e": 29448, "s": 29444, "text": "XML" }, { "code": "dependencies { compile 'org.mongodb:mongodb-driver:3.2.2' }", "e": 29514, "s": 29448, "text": null }, { "code": null, "e": 30246, "s": 29517, "text": "Similarly, other DB drivers can be specified in this way. It depends upon the project nature, the dependencies has to be fixed. For ordinary class level projects, all the classes i.e parent class, child class, etc should be available in the classpath. If there are errors, then also .class file will not be created which leads to ClassNotFoundException, and hence in order to get the whole code working, one should correct the errors first by fixing the dependencies. IDE is much helpful to overcome such sort scenarios such as when the program throws ClassNotFoundException, it will provide suggestions to users about the necessity of inclusion of jar files(which contains necessary functionalities like connecting to database." }, { "code": null, "e": 30263, "s": 30248, "text": "adnanirshad158" }, { "code": null, "e": 30272, "s": 30263, "text": "gabaa406" }, { "code": null, "e": 30288, "s": 30272, "text": "Java-Exceptions" }, { "code": null, "e": 30295, "s": 30288, "text": "Picked" }, { "code": null, "e": 30300, "s": 30295, "text": "Java" }, { "code": null, "e": 30305, "s": 30300, "text": "Java" }, { "code": null, "e": 30403, "s": 30305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30418, "s": 30403, "text": "Stream In Java" }, { "code": null, "e": 30437, "s": 30418, "text": "Exceptions in Java" }, { "code": null, "e": 30458, "s": 30437, "text": "Constructors in Java" }, { "code": null, "e": 30488, "s": 30458, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30534, "s": 30488, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30551, "s": 30534, "text": "Generics in Java" }, { "code": null, "e": 30572, "s": 30551, "text": "Introduction to Java" }, { "code": null, "e": 30615, "s": 30572, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30637, "s": 30615, "text": "PriorityQueue in Java" } ]
Scala Set intersect() method with example - GeeksforGeeks
18 Oct, 2019 The intersect() method is utilized to compute the intersection between two sets. Method Definition: def intersect(that: Set[A]): Set[A] Return Type: It returns a set containing the elements present in both the sets. Example #1: // Scala program of intersect() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 5) val s2 = Set(11, 12, 13, 4, 5) // Applying intersect method val s3 = s1.intersect(s2) s3.foreach(x => println(x)) } } 5 4 Example #2: // Scala program of intersect() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 5) val s2 = Set(11, 2, 3, 4, 5) // Applying intersect method val s3 = s1.intersect(s2) s3.foreach(x => println(x)) } } 5 2 3 4 Scala scala-collection Scala-Method Scala-Set Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Class and Object in Scala Operators in Scala Scala Constructors Scala Tutorial – Learn Scala with Step By Step Guide Scala Map get() method with example Scala String substring() method with example Scala String replace() method with example Lambda Expression in Scala Break statement in Scala
[ { "code": null, "e": 24047, "s": 24019, "text": "\n18 Oct, 2019" }, { "code": null, "e": 24128, "s": 24047, "text": "The intersect() method is utilized to compute the intersection between two sets." }, { "code": null, "e": 24183, "s": 24128, "text": "Method Definition: def intersect(that: Set[A]): Set[A]" }, { "code": null, "e": 24263, "s": 24183, "text": "Return Type: It returns a set containing the elements present in both the sets." }, { "code": null, "e": 24275, "s": 24263, "text": "Example #1:" }, { "code": "// Scala program of intersect() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 5) val s2 = Set(11, 12, 13, 4, 5) // Applying intersect method val s3 = s1.intersect(s2) s3.foreach(x => println(x)) } } ", "e": 24657, "s": 24275, "text": null }, { "code": null, "e": 24662, "s": 24657, "text": "5\n4\n" }, { "code": null, "e": 24674, "s": 24662, "text": "Example #2:" }, { "code": "// Scala program of intersect() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 5) val s2 = Set(11, 2, 3, 4, 5) // Applying intersect method val s3 = s1.intersect(s2) s3.foreach(x => println(x)) } } ", "e": 25054, "s": 24674, "text": null }, { "code": null, "e": 25063, "s": 25054, "text": "5\n2\n3\n4\n" }, { "code": null, "e": 25069, "s": 25063, "text": "Scala" }, { "code": null, "e": 25086, "s": 25069, "text": "scala-collection" }, { "code": null, "e": 25099, "s": 25086, "text": "Scala-Method" }, { "code": null, "e": 25109, "s": 25099, "text": "Scala-Set" }, { "code": null, "e": 25115, "s": 25109, "text": "Scala" }, { "code": null, "e": 25213, "s": 25115, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25235, "s": 25213, "text": "Type Casting in Scala" }, { "code": null, "e": 25261, "s": 25235, "text": "Class and Object in Scala" }, { "code": null, "e": 25280, "s": 25261, "text": "Operators in Scala" }, { "code": null, "e": 25299, "s": 25280, "text": "Scala Constructors" }, { "code": null, "e": 25352, "s": 25299, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 25388, "s": 25352, "text": "Scala Map get() method with example" }, { "code": null, "e": 25433, "s": 25388, "text": "Scala String substring() method with example" }, { "code": null, "e": 25476, "s": 25433, "text": "Scala String replace() method with example" }, { "code": null, "e": 25503, "s": 25476, "text": "Lambda Expression in Scala" } ]
Program to find the kth character after decrypting a string - GeeksforGeeks
08 Nov, 2021 Given a string str consisting of characters and numbers and an integer k, the task is to decrypt the string and the return the kth character in the decrypted string.In order to decrypt the string, traverse the string character by character and if the current character is an alphabet then append it to the resultant string else if it is a numeric digit then parse the number and repeat the resultant string this parsed number of times and continue with the original string. For example, str = “ab2c3” will be decrypted as “ababcababcababc”.Examples: Input: str = “ab2c3”, k = 5 Output: c Decrypted string will be “ababcababcababc” and ‘c’ is the fifth character.Input: str = “x2y3”, k = 3 Output: y Approach: Initialize starting index i = 0 and total_len = 0. Loop while i is less then the length of the input string and check if current character is an alphabet or not. If yes then increment total_len by 1 and check if total length is less then or equal to k if yes then return the string else increment i. Initialize n = 0 again loop while i is less then length of input string and i is not an alphabet and parse the number and increment i and find the next_total_len = total_len * n. If k < total_len then get the position of the character by initializing pos = k % total_len.If position is not found then update position = total_len and finally return the character at kth position. If not found then return -1. If k < total_len then get the position of the character by initializing pos = k % total_len. If position is not found then update position = total_len and finally return the character at kth position. If not found then return -1. Below is the implementation of the above approach: C++ Java Python3 C# // C++ implementation of the approach#include <cstdlib>#include <iostream>using namespace std; // Function to print kth character of// String s after decrypting itchar findKthChar(string s, int k){ // Get the length of string int len = s.length(); // Initialise pointer to character // of input string to zero int i = 0; // Total length of resultant string int total_len = 0; // Traverse the string from starting // and check if each character is // alphabet then increment total_len while (i < len) { if (isalpha(s[i])) { total_len++; // If total_leg equal to k then // return string else increment i if (total_len == k) return s[i]; i++; } else { // Parse the number int n = 0; while (i < len && !isalpha(s[i])) { n = n * 10 + (s[i] - '0'); i++; } // Update next_total_len int next_total_len = total_len * n; // Get the position of kth character if (k <= next_total_len) { int pos = k % total_len; // Position not found then update // position with total_len if (!pos) { pos = total_len; } // Recursively find the kth position return findKthChar(s, pos); } else { // Else update total_len // by next_total_len total_len = next_total_len; } } } // Return -1 if character not found return -1;} // Driver codeint main(){ string s = "ab2c3"; int k = 5; cout << findKthChar(s, k); return 0;} // Java implementation of the approachimport java.util.*;class GfG{ // Function to print kth character of// String s after decrypting itstatic Character findKthChar(String s, int k){ // Get the length of string int len = s.length(); // Initialise pointer to character // of input string to zero int i = 0; // Total length of resultant string int total_len = 0; // Traverse the string from starting // and check if each character is // alphabet then increment total_len while (i < len) { if (Character.isLetter(s.charAt(i))) { total_len++; // If total_leg equal to k then // return string else increment i if (total_len == k) return s.charAt(i); i++; } else { // Parse the number int n = 0; while (i < len && !Character.isLetter(s.charAt(i))) { n = n * 10 + (s.charAt(i) - '0'); i++; } // Update next_total_len int next_total_len = total_len * n; // Get the position of kth character if (k <= next_total_len) { int pos = k % total_len; // Position not found then update // position with total_len if (pos == 0) { pos = total_len; } // Recursively find the kth position return findKthChar(s, pos); } else { // Else update total_len // by next_total_len total_len = next_total_len; } } } // Return -1 if character not found return ' ';} // Driver codepublic static void main(String[] args){ String s = "ab2c3"; int k = 5; System.out.println(findKthChar(s, k));}} // This code is contributed by Prerna Saini. # Python 3 implementation of the approach # Function to print kth character of# String s after decrypting itdef findKthChar(s, k): # Get the length of string len1 = len(s) # Initialise pointer to character # of input string to zero i = 0 # Total length of resultant string total_len = 0 # Traverse the string from starting # and check if each character is # alphabet then increment total_len while (i < len1): if (s[i].isalpha()): total_len += 1 # If total_leg equal to k then # return string else increment i if (total_len == k): return s[i] i += 1 else: # Parse the number n = 0 while (i < len1 and s[i].isalpha() == False): n = n * 10 + (ord(s[i]) - ord('0')) i += 1 # Update next_total_len next_total_len = total_len * n # Get the position of kth character if (k <= next_total_len): pos = k % total_len # Position not found then update # position with total_len if (pos == 0): pos = total_len # Recursively find the kth position return findKthChar(s, pos) else: # Else update total_len # by next_total_len total_len = next_total_len # Return -1 if character not found return -1 # Driver codeif __name__ == '__main__': s = "ab2c3" k = 5 print(findKthChar(s, k)) # This code is contributed by# Surendra_Gangwar // C# implementation of the approachusing System; class GFG{ // Function to print kth character of// String s after decrypting itstatic char findKthChar(String s, int k){ // Get the length of string int len = s.Length; // Initialise pointer to character // of input string to zero int i = 0; // Total length of resultant string int total_len = 0; // Traverse the string from starting // and check if each character is // alphabet then increment total_len while (i < len) { if (char.IsLetter(s[i])) { total_len++; // If total_leg equal to k then // return string else increment i if (total_len == k) return s[i]; i++; } else { // Parse the number int n = 0; while (i < len && !char.IsLetter(s[i])) { n = n * 10 + (s[i] - '0'); i++; } // Update next_total_len int next_total_len = total_len * n; // Get the position of kth character if (k <= next_total_len) { int pos = k % total_len; // Position not found then update // position with total_len if (pos == 0) { pos = total_len; } // Recursively find the kth position return findKthChar(s, pos); } else { // Else update total_len // by next_total_len total_len = next_total_len; } } } // Return -1 if character not found return ' ';} // Driver codepublic static void Main(String[] args){ String s = "ab2c3"; int k = 5; Console.WriteLine(findKthChar(s, k));}} // This code is contributed by PrinciRaj1992 c Time Complexity: O(N) Auxiliary Space: O(1) prerna saini HarshPanchal SURENDRA_GANGWAR princiraj1992 shubham_singh anikaseth98 rohan07 Amazon Constructive Algorithms C++ Programs Competitive Programming Strings Amazon Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Handling the Divide by Zero Exception in C++ Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Competitive Programming - A Complete Guide Modulo 10^9+7 (1000000007) Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 24552, "s": 24524, "text": "\n08 Nov, 2021" }, { "code": null, "e": 25104, "s": 24552, "text": "Given a string str consisting of characters and numbers and an integer k, the task is to decrypt the string and the return the kth character in the decrypted string.In order to decrypt the string, traverse the string character by character and if the current character is an alphabet then append it to the resultant string else if it is a numeric digit then parse the number and repeat the resultant string this parsed number of times and continue with the original string. For example, str = “ab2c3” will be decrypted as “ababcababcababc”.Examples: " }, { "code": null, "e": 25255, "s": 25104, "text": "Input: str = “ab2c3”, k = 5 Output: c Decrypted string will be “ababcababcababc” and ‘c’ is the fifth character.Input: str = “x2y3”, k = 3 Output: y " }, { "code": null, "e": 25269, "s": 25257, "text": "Approach: " }, { "code": null, "e": 25320, "s": 25269, "text": "Initialize starting index i = 0 and total_len = 0." }, { "code": null, "e": 25569, "s": 25320, "text": "Loop while i is less then the length of the input string and check if current character is an alphabet or not. If yes then increment total_len by 1 and check if total length is less then or equal to k if yes then return the string else increment i." }, { "code": null, "e": 25977, "s": 25569, "text": "Initialize n = 0 again loop while i is less then length of input string and i is not an alphabet and parse the number and increment i and find the next_total_len = total_len * n. If k < total_len then get the position of the character by initializing pos = k % total_len.If position is not found then update position = total_len and finally return the character at kth position. If not found then return -1." }, { "code": null, "e": 26070, "s": 25977, "text": "If k < total_len then get the position of the character by initializing pos = k % total_len." }, { "code": null, "e": 26207, "s": 26070, "text": "If position is not found then update position = total_len and finally return the character at kth position. If not found then return -1." }, { "code": null, "e": 26260, "s": 26207, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26264, "s": 26260, "text": "C++" }, { "code": null, "e": 26269, "s": 26264, "text": "Java" }, { "code": null, "e": 26277, "s": 26269, "text": "Python3" }, { "code": null, "e": 26280, "s": 26277, "text": "C#" }, { "code": "// C++ implementation of the approach#include <cstdlib>#include <iostream>using namespace std; // Function to print kth character of// String s after decrypting itchar findKthChar(string s, int k){ // Get the length of string int len = s.length(); // Initialise pointer to character // of input string to zero int i = 0; // Total length of resultant string int total_len = 0; // Traverse the string from starting // and check if each character is // alphabet then increment total_len while (i < len) { if (isalpha(s[i])) { total_len++; // If total_leg equal to k then // return string else increment i if (total_len == k) return s[i]; i++; } else { // Parse the number int n = 0; while (i < len && !isalpha(s[i])) { n = n * 10 + (s[i] - '0'); i++; } // Update next_total_len int next_total_len = total_len * n; // Get the position of kth character if (k <= next_total_len) { int pos = k % total_len; // Position not found then update // position with total_len if (!pos) { pos = total_len; } // Recursively find the kth position return findKthChar(s, pos); } else { // Else update total_len // by next_total_len total_len = next_total_len; } } } // Return -1 if character not found return -1;} // Driver codeint main(){ string s = \"ab2c3\"; int k = 5; cout << findKthChar(s, k); return 0;}", "e": 28058, "s": 26280, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GfG{ // Function to print kth character of// String s after decrypting itstatic Character findKthChar(String s, int k){ // Get the length of string int len = s.length(); // Initialise pointer to character // of input string to zero int i = 0; // Total length of resultant string int total_len = 0; // Traverse the string from starting // and check if each character is // alphabet then increment total_len while (i < len) { if (Character.isLetter(s.charAt(i))) { total_len++; // If total_leg equal to k then // return string else increment i if (total_len == k) return s.charAt(i); i++; } else { // Parse the number int n = 0; while (i < len && !Character.isLetter(s.charAt(i))) { n = n * 10 + (s.charAt(i) - '0'); i++; } // Update next_total_len int next_total_len = total_len * n; // Get the position of kth character if (k <= next_total_len) { int pos = k % total_len; // Position not found then update // position with total_len if (pos == 0) { pos = total_len; } // Recursively find the kth position return findKthChar(s, pos); } else { // Else update total_len // by next_total_len total_len = next_total_len; } } } // Return -1 if character not found return ' ';} // Driver codepublic static void main(String[] args){ String s = \"ab2c3\"; int k = 5; System.out.println(findKthChar(s, k));}} // This code is contributed by Prerna Saini.", "e": 30013, "s": 28058, "text": null }, { "code": "# Python 3 implementation of the approach # Function to print kth character of# String s after decrypting itdef findKthChar(s, k): # Get the length of string len1 = len(s) # Initialise pointer to character # of input string to zero i = 0 # Total length of resultant string total_len = 0 # Traverse the string from starting # and check if each character is # alphabet then increment total_len while (i < len1): if (s[i].isalpha()): total_len += 1 # If total_leg equal to k then # return string else increment i if (total_len == k): return s[i] i += 1 else: # Parse the number n = 0 while (i < len1 and s[i].isalpha() == False): n = n * 10 + (ord(s[i]) - ord('0')) i += 1 # Update next_total_len next_total_len = total_len * n # Get the position of kth character if (k <= next_total_len): pos = k % total_len # Position not found then update # position with total_len if (pos == 0): pos = total_len # Recursively find the kth position return findKthChar(s, pos) else: # Else update total_len # by next_total_len total_len = next_total_len # Return -1 if character not found return -1 # Driver codeif __name__ == '__main__': s = \"ab2c3\" k = 5 print(findKthChar(s, k)) # This code is contributed by# Surendra_Gangwar", "e": 31682, "s": 30013, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to print kth character of// String s after decrypting itstatic char findKthChar(String s, int k){ // Get the length of string int len = s.Length; // Initialise pointer to character // of input string to zero int i = 0; // Total length of resultant string int total_len = 0; // Traverse the string from starting // and check if each character is // alphabet then increment total_len while (i < len) { if (char.IsLetter(s[i])) { total_len++; // If total_leg equal to k then // return string else increment i if (total_len == k) return s[i]; i++; } else { // Parse the number int n = 0; while (i < len && !char.IsLetter(s[i])) { n = n * 10 + (s[i] - '0'); i++; } // Update next_total_len int next_total_len = total_len * n; // Get the position of kth character if (k <= next_total_len) { int pos = k % total_len; // Position not found then update // position with total_len if (pos == 0) { pos = total_len; } // Recursively find the kth position return findKthChar(s, pos); } else { // Else update total_len // by next_total_len total_len = next_total_len; } } } // Return -1 if character not found return ' ';} // Driver codepublic static void Main(String[] args){ String s = \"ab2c3\"; int k = 5; Console.WriteLine(findKthChar(s, k));}} // This code is contributed by PrinciRaj1992", "e": 33583, "s": 31682, "text": null }, { "code": null, "e": 33585, "s": 33583, "text": "c" }, { "code": null, "e": 33609, "s": 33587, "text": "Time Complexity: O(N)" }, { "code": null, "e": 33631, "s": 33609, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 33644, "s": 33631, "text": "prerna saini" }, { "code": null, "e": 33657, "s": 33644, "text": "HarshPanchal" }, { "code": null, "e": 33674, "s": 33657, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33688, "s": 33674, "text": "princiraj1992" }, { "code": null, "e": 33702, "s": 33688, "text": "shubham_singh" }, { "code": null, "e": 33714, "s": 33702, "text": "anikaseth98" }, { "code": null, "e": 33722, "s": 33714, "text": "rohan07" }, { "code": null, "e": 33729, "s": 33722, "text": "Amazon" }, { "code": null, "e": 33753, "s": 33729, "text": "Constructive Algorithms" }, { "code": null, "e": 33766, "s": 33753, "text": "C++ Programs" }, { "code": null, "e": 33790, "s": 33766, "text": "Competitive Programming" }, { "code": null, "e": 33798, "s": 33790, "text": "Strings" }, { "code": null, "e": 33805, "s": 33798, "text": "Amazon" }, { "code": null, "e": 33813, "s": 33805, "text": "Strings" }, { "code": null, "e": 33911, "s": 33813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33920, "s": 33911, "text": "Comments" }, { "code": null, "e": 33933, "s": 33920, "text": "Old Comments" }, { "code": null, "e": 33974, "s": 33933, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 34033, "s": 33974, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 34054, "s": 34033, "text": "Const keyword in C++" }, { "code": null, "e": 34066, "s": 34054, "text": "cout in C++" }, { "code": null, "e": 34111, "s": 34066, "text": "Handling the Divide by Zero Exception in C++" }, { "code": null, "e": 34154, "s": 34111, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 34195, "s": 34154, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 34238, "s": 34195, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 34265, "s": 34238, "text": "Modulo 10^9+7 (1000000007)" } ]
C# Program For Implementing IEnumerable Interface Using LINQ - GeeksforGeeks
01 Nov, 2021 LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we are going to implement an IEnumerable interface using LINQ. This interface is used to iterate over the collections like list, stack, queue, etc. Or we can say that this interface is the base interface for all non-generic collections that can be enumerated. Syntax: IEnumerable<TSource> Using IEnumerable we will display employee data whose name starts with ‘D’. Example: Input : List of Employees: {{id = 201, name = "Druva", age = 12}, {id = 202, name = "Deepu", age = 15}, {id = 203, name = "Manoja", age = 13}, {id = 204, name = "Sathwik", age = 12}, {id = 205, name = "Suraj", age = 15}} Output : {{id = 201, name = "Druva", age = 12}, {id = 202, name = "Deepu", age = 15}} Input : List of Employees: {{id = 301, name = "Sathwik", age = 12}, {id = 302, name = "Saran", age = 15}} Output : No Output Approach: To find the list of employees whose name starts with letter ‘D’ follow the following steps: Create a list of employees with four variables(Id, name, department, and salary).Iterate through the employee details by using Where() function and get the employee details by choosing employee whose name starts with ‘D’ using s => s.name[0] == ‘D’.Now call the ToString() method.Display the employee details. Create a list of employees with four variables(Id, name, department, and salary). Iterate through the employee details by using Where() function and get the employee details by choosing employee whose name starts with ‘D’ using s => s.name[0] == ‘D’. Now call the ToString() method. Display the employee details. Example: C# // C# program to display the details of those // employees whose name starts with character "D"using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class Employee{ // Declare 4 variables - id, name, // department, and salaryint id; int salary;string name;string department; // Get the to string method that returns // id, name, department, and salarypublic override string ToString(){ return id + " " + name + " " + salary + " " + department;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Employee> emp = new List<Employee>() { // Create 5 Employee details new Employee{ id = 201, name = "Druva", salary = 12000, department = "HR" }, new Employee{ id = 202, name = "Deepu", salary = 15000, department = "Development" }, new Employee{ id = 203, name = "Manoja", salary = 13000, department = "HR" }, new Employee{ id = 204, name = "Sathwik", salary = 12000, department = "Designing" }, new Employee{ id = 205, name = "Suraj", salary = 15000, department = "Development" } }; // Iterate the Employee by selecting Employee // name starts with D // Using IEnumerable interface IEnumerable<Employee> result = emp.Where(x => x.name[0] == 'D'); // Display employee details Console.WriteLine("ID Name Salary Department"); Console.WriteLine("++++++++++++++++++++++++++++"); foreach (Employee e in result) { // Call the to string method Console.WriteLine(e.ToString()); } }} Output: ID Name Salary Department ++++++++++++++++++++++++++++ 201 Druva 12000 HR 202 Deepu 15000 Development CSharp LINQ CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Partial Classes in C# Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | List Class C# | Inheritance Linked List Implementation in C# Lambda Expressions in C# Convert String to Character Array in C#
[ { "code": null, "e": 24222, "s": 24194, "text": "\n01 Nov, 2021" }, { "code": null, "e": 24837, "s": 24222, "text": "LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we are going to implement an IEnumerable interface using LINQ. This interface is used to iterate over the collections like list, stack, queue, etc. Or we can say that this interface is the base interface for all non-generic collections that can be enumerated." }, { "code": null, "e": 24845, "s": 24837, "text": "Syntax:" }, { "code": null, "e": 24866, "s": 24845, "text": "IEnumerable<TSource>" }, { "code": null, "e": 24942, "s": 24866, "text": "Using IEnumerable we will display employee data whose name starts with ‘D’." }, { "code": null, "e": 24951, "s": 24942, "text": "Example:" }, { "code": null, "e": 25456, "s": 24951, "text": "Input : List of Employees:\n {{id = 201, name = \"Druva\", age = 12},\n {id = 202, name = \"Deepu\", age = 15},\n {id = 203, name = \"Manoja\", age = 13},\n {id = 204, name = \"Sathwik\", age = 12},\n {id = 205, name = \"Suraj\", age = 15}}\nOutput : {{id = 201, name = \"Druva\", age = 12},\n {id = 202, name = \"Deepu\", age = 15}}\n \nInput : List of Employees:\n {{id = 301, name = \"Sathwik\", age = 12},\n {id = 302, name = \"Saran\", age = 15}}\nOutput : No Output" }, { "code": null, "e": 25466, "s": 25456, "text": "Approach:" }, { "code": null, "e": 25558, "s": 25466, "text": "To find the list of employees whose name starts with letter ‘D’ follow the following steps:" }, { "code": null, "e": 25868, "s": 25558, "text": "Create a list of employees with four variables(Id, name, department, and salary).Iterate through the employee details by using Where() function and get the employee details by choosing employee whose name starts with ‘D’ using s => s.name[0] == ‘D’.Now call the ToString() method.Display the employee details." }, { "code": null, "e": 25950, "s": 25868, "text": "Create a list of employees with four variables(Id, name, department, and salary)." }, { "code": null, "e": 26119, "s": 25950, "text": "Iterate through the employee details by using Where() function and get the employee details by choosing employee whose name starts with ‘D’ using s => s.name[0] == ‘D’." }, { "code": null, "e": 26151, "s": 26119, "text": "Now call the ToString() method." }, { "code": null, "e": 26181, "s": 26151, "text": "Display the employee details." }, { "code": null, "e": 26190, "s": 26181, "text": "Example:" }, { "code": null, "e": 26193, "s": 26190, "text": "C#" }, { "code": "// C# program to display the details of those // employees whose name starts with character \"D\"using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class Employee{ // Declare 4 variables - id, name, // department, and salaryint id; int salary;string name;string department; // Get the to string method that returns // id, name, department, and salarypublic override string ToString(){ return id + \" \" + name + \" \" + salary + \" \" + department;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Employee> emp = new List<Employee>() { // Create 5 Employee details new Employee{ id = 201, name = \"Druva\", salary = 12000, department = \"HR\" }, new Employee{ id = 202, name = \"Deepu\", salary = 15000, department = \"Development\" }, new Employee{ id = 203, name = \"Manoja\", salary = 13000, department = \"HR\" }, new Employee{ id = 204, name = \"Sathwik\", salary = 12000, department = \"Designing\" }, new Employee{ id = 205, name = \"Suraj\", salary = 15000, department = \"Development\" } }; // Iterate the Employee by selecting Employee // name starts with D // Using IEnumerable interface IEnumerable<Employee> result = emp.Where(x => x.name[0] == 'D'); // Display employee details Console.WriteLine(\"ID Name Salary Department\"); Console.WriteLine(\"++++++++++++++++++++++++++++\"); foreach (Employee e in result) { // Call the to string method Console.WriteLine(e.ToString()); } }}", "e": 27921, "s": 26193, "text": null }, { "code": null, "e": 27929, "s": 27921, "text": "Output:" }, { "code": null, "e": 28034, "s": 27929, "text": "ID Name Salary Department\n++++++++++++++++++++++++++++\n201 Druva 12000 HR\n202 Deepu 15000 Development" }, { "code": null, "e": 28046, "s": 28034, "text": "CSharp LINQ" }, { "code": null, "e": 28062, "s": 28046, "text": "CSharp-programs" }, { "code": null, "e": 28069, "s": 28062, "text": "Picked" }, { "code": null, "e": 28072, "s": 28069, "text": "C#" }, { "code": null, "e": 28170, "s": 28072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28179, "s": 28170, "text": "Comments" }, { "code": null, "e": 28192, "s": 28179, "text": "Old Comments" }, { "code": null, "e": 28215, "s": 28192, "text": "Extension Method in C#" }, { "code": null, "e": 28243, "s": 28215, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28265, "s": 28243, "text": "Partial Classes in C#" }, { "code": null, "e": 28305, "s": 28265, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28348, "s": 28305, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28364, "s": 28348, "text": "C# | List Class" }, { "code": null, "e": 28381, "s": 28364, "text": "C# | Inheritance" }, { "code": null, "e": 28414, "s": 28381, "text": "Linked List Implementation in C#" }, { "code": null, "e": 28439, "s": 28414, "text": "Lambda Expressions in C#" } ]
How to declare Block-Scoped Variables in JavaScript?
To declare block scoped variables, we use the keyword let and const introduced in ES2015. Following is the code showing declaring black scoped variables in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Declaring block scoped variables</h1> <div class="sample"></div> <div style="color: green;" class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to declare and display block scoped variables</h3> <script> let resEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample");{ let a = 22; const b = 44; sampleEle.innerHTML = "let a = " + a + "<br>"; sampleEle.innerHTML += "const b = " + b + "<br>"; } document.querySelector(".Btn").addEventListener("click", () => { try { a + b; } catch (err) { resEle.innerHTML = "a+b = " + err; } }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1152, "s": 1062, "text": "To declare block scoped variables, we use the keyword let and const introduced in ES2015." }, { "code": null, "e": 1231, "s": 1152, "text": "Following is the code showing declaring black scoped variables in JavaScript −" }, { "code": null, "e": 1242, "s": 1231, "text": " Live Demo" }, { "code": null, "e": 2307, "s": 1242, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result,.sample {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Declaring block scoped variables</h1>\n<div class=\"sample\"></div>\n<div style=\"color: green;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to declare and display block scoped variables</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let sampleEle = document.querySelector(\".sample\");{\n let a = 22;\n const b = 44;\n sampleEle.innerHTML = \"let a = \" + a + \"<br>\";\n sampleEle.innerHTML += \"const b = \" + b + \"<br>\";\n }\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n try {\n a + b;\n }\n catch (err) {\n resEle.innerHTML = \"a+b = \" + err;\n }\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2358, "s": 2307, "text": "The above code will produce the following output −" }, { "code": null, "e": 2396, "s": 2358, "text": "On clicking the ‘CLICK HERE’ button −" } ]
‘Simpsonize’ Yourself using CycleGAN and PyTorch | by Neel Iyer | Towards Data Science
Cyclegan is a framework that is capable of unpaired image to image translation. It’s been applied in some really interesting cases. Such as converting horses to zebras (and back again) and converting photos of the winter to photos of the summer. I thought this could be potentially applied to The Simpsons. I was inspired by sites like turnedyellow and makemeyellow. The idea is that you upload a photo of your face. Cyclegan would translate that into a Simpsons Character. It’s worth noting that the paper explicitly mentions that large geometric changes are usually unsuccessful. So this isn’t likely to turn out well. But I’m going to attempt this anyway. First we need to install CycleGAN. !git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2piximport osos.chdir('pytorch-CycleGAN-and-pix2pix/')!pip install -r requirements.txt Creating the dataset is harder than you would initially think. To create this dataset I needed to find close up shots of Simpsons characters and close up shots of regular people. Initially my thinking was to scrape images from google images. Unfortunately to do that it looks like you need a developer key from google console. So instead I scraped images from Bing. This worked to an extent. But it took so long to download all the images. And after I looked at the images I noticed that some of them didn’t include any faces at all. Thankfully, I stumbled across a dataset on kaggle that had everything I needed. It contains Simpsons faces extracted from a few seasons. Each image is 200x200 pixels and contains one face. This dataset will be stored in the trainA folder. def create_training_dataset_simpson_faces(download_dir): %cd $download_dir # download dataset and unzip !kaggle datasets download kostastokis/simpsons-faces --force !unzip \*.zip !rm *.zip !cp -a $download_dir/cropped/. $download_dir # remove unnecessary folders !rm -Rf $download_dir/cropped !rm -Rf $download_dir/simplified # go back to orig directory %cd /content/pytorch-CycleGAN-and-pix2pixcreate_training_dataset_simpson_faces(TRAIN_A) To create the dataset of real faces I got a little bit experimental. Will Kwan recently using stylegan2 to generate a dataset in one of his recent videos. It seemed to work fairly well for him. So I thought I could do the same thing. Here’s some example faces taken from Nvidia’s stylegan2 github repository. As you can see the output from this GAN is fairly photorealistic. This could turn out far better than scraping the internet for faces. I could create as many faces as I needed for my model. Plus I wouldn’t have to download cumbersome large files. This dataset will be stored in the trainB folder import matplotlib.pyplot as pltfrom tqdm.notebook import tqdm# see Github for full code: https://github.com/spiyer99/spiyer99.github.io/blob/master/nbs/cyclegan_simpsonify.ipynbdef create_training_dataset_real_faces_stylegan(download_dir): # create in batches of 100 # reduces RAM requirements counter = 0 pbar = tqdm(total = LIMIT) while counter < LIMIT: seeds = np.random.randint(10000000, size=100) imgs = generate_images_from_seeds(seeds, 0.7) for img in imgs: img.save(download_dir/'real_face_{}.jpg'.format(counter), 'JPEG', quality=100) counter+=1 pbar.update(1) del imgscreate_training_dataset_real_faces_stylegan(TRAIN_B) Next we’ll need to split the data into training and testing. testB will contain real faces that we want to convert into Simpsons characters. testA will contain simpsons characters that we want to convert into real people. # move images to a new folder# `images` is the existing image directory: # `new_dir` is the path that the images will be moved to# `files_limit` is the limit of files that will be moveddef move_all_images_to_new_folder(images, new_dir, files_limit = None): files = glob.glob(str(images/'*.*g')) if(files_limit is not None): files = files[:files_limit] for file in files: shutil.move(file, new_dir/os.path.basename(file))move_all_images_to_new_folder(TRAIN_A, new_dir = TEST_A, files_limit = int(min(LIMIT*0.1, 25)))move_all_images_to_new_folder(TRAIN_B, new_dir = TEST_B, files_limit = int(min(LIMIT*0.1, 25))) Let’s see the images we’re working with. import PILimport randomdef plot_from_image_path(path, title): all_imgs = glob.glob(str(path/'*.*g')) print(f'{len(all_imgs)} imgs in {title} directory') img_path = random.choice(all_imgs) img = PIL.Image.open(img_path) plt.imshow(img) plt.title(title) plt.show()plot_from_image_path(TRAIN_A, 'TRAIN_A')plot_from_image_path(TRAIN_B, 'TRAIN_B')plot_from_image_path(TEST_A, 'TEST_A')plot_from_image_path(TEST_B, 'TEST_B') Everything looks pretty good! Now we can create the model. I’ve made a few adjustments to the existing script. Let’s create a few helper functions. These functions help me copy the saved models to my google drive. It also helps test the model and store the output images to google drive. import osfrom pathlib import Pathfrom distutils.dir_util import copy_treeimport matplotlib.pyplot as pltimport randomdef copy_to_drive(folder = 'cyclegan_simpsonify'): drive_folder = Path('/content/drive/My Drive/')/folder if(drive_folder.exists()): shutil.rmtree(drive_folder) shutil.copytree('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/'+NAME+'/', str(drive_folder))def get_corresponding_photo(file_path): return file_path.replace('fake', 'real')def plot_results(number): for i in range(number): img_path = random.choice(glob.glob('./results/'+NAME+'/test_latest/images/*fake.*g')) print(img_path) img = plt.imread(img_path) plt.imshow(img) plt.title('fake') plt.show() print(get_corresponding_photo(img_path)) img = plt.imread(get_corresponding_photo(img_path)) plt.imshow(img) plt.title('real') plt.show()def get_model(src, dst): # copy across model try: os.remove(dst) except: pass shutil.copyfile(src, dst)def copy_from_drive(folder = 'cyclegan_simpsonify'): drive_folder = Path('/content/drive/My Drive/')/folder if(not Path('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/').exists()): os.mkdir('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/') if(Path('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/'+NAME+'/').exists()): shutil.rmtree('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/'+NAME+'/') shutil.copytree(str(drive_folder), '/content/pytorch-CycleGAN-and-pix2pix/checkpoints/'+NAME+'/')def test_model (number_results = 5, direction = 'BtoA', src = None, dst = None): # delete results folder and recrete shutil.rmtree('./results') os.mkdir('./results') # get appropriate model if (src is None): src = './checkpoints/'+NAME+'/latest_net_G_'+direction.split('to')[-1]+'.pth' if (dst is None): dst = './checkpoints/'+NAME+'/latest_net_G.pth' get_model(src, dst) if (direction == 'BtoA'): test = TEST_B else: test = TEST_A cmd = 'python test.py --dataroot '+str(test)+' --name '+str(NAME)+' --model test --no_dropout' os.system(cmd) plot_results(number_results) Let’s create the options for training. import timefrom options.train_options import TrainOptionsfrom data import create_datasetfrom models import create_modelfrom util.visualizer import Visualizerimport shutilimport osfrom pathlib import Pathfrom tqdm.notebook import tqdmoptions_list = ['--name', NAME,\ '--dataroot', TRAIN_A.parent,\ '--batch_size', BATCH_SIZE,\ '--checkpoints_dir', './checkpoints',\ '--lr', 2e-4,\ '--n_epochs', EPOCHS,\ '--n_epochs_decay', EPOCHS//2,\ '--name', NAME]opt = TrainOptions().parse(options_list) First we create the dataset using the options we specified earlier. dataset = create_dataset(opt)dataset_size = len(dataset)print('The number of training images = %d' % dataset_size) Then we create the model and run the setup call. model = create_model(opt)model.setup(opt)visualizer = Visualizer(opt)total_iters = 0 Let’s see the generator from A to B. The naming convention is slightly different from the paper. In the paper the generator was called G. In the code they refer to this mapping function as G_A. The meaning is still the same. This generator function maps from A to B. In our case it maps from Simpsons to Real Life. model.netG_A We can see here that the model uses Resnets. We have Conv2d, Batchnorm, ReLU, InstanceNorm2d and ReflectionPad2d. InstanceNorm2d and ReflectionPad2d are new to me. InstanceNorm2d: This is very similar to batch norm but it is applied to one image at a time. ReflectionPad2d: This will pad the tensor using the reflection of the input boundary. Now we can look at the discriminator as well. model.netD_A The discriminator uses LeakyReLU, Conv2d and InstanceNorm2d. LeakyReLU is interesting. ReLU is an activation that adds non-linearity to the network. But what is LeakyReLU? ReLU converts all negative values to 0. Since, the gradient of 0 is 0 neurons that reach large negative values effectively neuron cancel out to 0. They effectively 'die'. This means that your network eventually stops learning. This effect is known as the dying ReLU problem. LeakyReLU aims to fix this problem. The function is as follows: ​ This function essentially translates to: if a value is negative multiply it by negative_slope otherwise do nothing. negative_slope is usually 0.01, but you can vary it. So LeakyReLU significantly reduces the magnitude of negative values rather than sending them to 0. But the jury is still out on whether this really works well. Now we can train the model over a number of epochs. I’ve specified 10 epochs here. Here’s the code for training: model.optimize_parameters() is where all the magic happens. It runs the loss functions, gets the gradients and updates the weights. By doing so it optimises the generators and the discriminators. Let’s train it! I let the model train overnight on google colab and copied the .pth model to my google drive. Let’s see the output. test_model(10, 'BtoA') It’s a good start. I particularly like this image: It could use some improvement, to be honest. Let’s try running the AtoB cycle. So we'll convert simpsons characters into human faces. test_model(10, 'AtoB') The authors of Cyclegan noted that tasks requiring large geometric changes aren’t likely to be successful. I’ve just confirmed this. The network seems to struggle with the large geometric shifts required to convert a simpsons character to a real person (and vice-versa). I’m unsure if more training would rectify this issue. The tricky thing with GANs is figuring out when to stop training. Visual inspection seems to be the answer for Cyclegan. It might be worthwhile to train for another few days and see what happens. The full jupyter notebook can be found on Github Originally published at https://spiyer99.github.io on August 30, 2020.
[ { "code": null, "e": 293, "s": 47, "text": "Cyclegan is a framework that is capable of unpaired image to image translation. It’s been applied in some really interesting cases. Such as converting horses to zebras (and back again) and converting photos of the winter to photos of the summer." }, { "code": null, "e": 521, "s": 293, "text": "I thought this could be potentially applied to The Simpsons. I was inspired by sites like turnedyellow and makemeyellow. The idea is that you upload a photo of your face. Cyclegan would translate that into a Simpsons Character." }, { "code": null, "e": 668, "s": 521, "text": "It’s worth noting that the paper explicitly mentions that large geometric changes are usually unsuccessful. So this isn’t likely to turn out well." }, { "code": null, "e": 706, "s": 668, "text": "But I’m going to attempt this anyway." }, { "code": null, "e": 741, "s": 706, "text": "First we need to install CycleGAN." }, { "code": null, "e": 890, "s": 741, "text": "!git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2piximport osos.chdir('pytorch-CycleGAN-and-pix2pix/')!pip install -r requirements.txt" }, { "code": null, "e": 953, "s": 890, "text": "Creating the dataset is harder than you would initially think." }, { "code": null, "e": 1069, "s": 953, "text": "To create this dataset I needed to find close up shots of Simpsons characters and close up shots of regular people." }, { "code": null, "e": 1217, "s": 1069, "text": "Initially my thinking was to scrape images from google images. Unfortunately to do that it looks like you need a developer key from google console." }, { "code": null, "e": 1256, "s": 1217, "text": "So instead I scraped images from Bing." }, { "code": null, "e": 1424, "s": 1256, "text": "This worked to an extent. But it took so long to download all the images. And after I looked at the images I noticed that some of them didn’t include any faces at all." }, { "code": null, "e": 1613, "s": 1424, "text": "Thankfully, I stumbled across a dataset on kaggle that had everything I needed. It contains Simpsons faces extracted from a few seasons. Each image is 200x200 pixels and contains one face." }, { "code": null, "e": 1663, "s": 1613, "text": "This dataset will be stored in the trainA folder." }, { "code": null, "e": 2116, "s": 1663, "text": "def create_training_dataset_simpson_faces(download_dir): %cd $download_dir # download dataset and unzip !kaggle datasets download kostastokis/simpsons-faces --force !unzip \\*.zip !rm *.zip !cp -a $download_dir/cropped/. $download_dir # remove unnecessary folders !rm -Rf $download_dir/cropped !rm -Rf $download_dir/simplified # go back to orig directory %cd /content/pytorch-CycleGAN-and-pix2pixcreate_training_dataset_simpson_faces(TRAIN_A)" }, { "code": null, "e": 2185, "s": 2116, "text": "To create the dataset of real faces I got a little bit experimental." }, { "code": null, "e": 2350, "s": 2185, "text": "Will Kwan recently using stylegan2 to generate a dataset in one of his recent videos. It seemed to work fairly well for him. So I thought I could do the same thing." }, { "code": null, "e": 2491, "s": 2350, "text": "Here’s some example faces taken from Nvidia’s stylegan2 github repository. As you can see the output from this GAN is fairly photorealistic." }, { "code": null, "e": 2672, "s": 2491, "text": "This could turn out far better than scraping the internet for faces. I could create as many faces as I needed for my model. Plus I wouldn’t have to download cumbersome large files." }, { "code": null, "e": 2721, "s": 2672, "text": "This dataset will be stored in the trainB folder" }, { "code": null, "e": 3384, "s": 2721, "text": "import matplotlib.pyplot as pltfrom tqdm.notebook import tqdm# see Github for full code: https://github.com/spiyer99/spiyer99.github.io/blob/master/nbs/cyclegan_simpsonify.ipynbdef create_training_dataset_real_faces_stylegan(download_dir): # create in batches of 100 # reduces RAM requirements counter = 0 pbar = tqdm(total = LIMIT) while counter < LIMIT: seeds = np.random.randint(10000000, size=100) imgs = generate_images_from_seeds(seeds, 0.7) for img in imgs: img.save(download_dir/'real_face_{}.jpg'.format(counter), 'JPEG', quality=100) counter+=1 pbar.update(1) del imgscreate_training_dataset_real_faces_stylegan(TRAIN_B)" }, { "code": null, "e": 3606, "s": 3384, "text": "Next we’ll need to split the data into training and testing. testB will contain real faces that we want to convert into Simpsons characters. testA will contain simpsons characters that we want to convert into real people." }, { "code": null, "e": 4223, "s": 3606, "text": "# move images to a new folder# `images` is the existing image directory: # `new_dir` is the path that the images will be moved to# `files_limit` is the limit of files that will be moveddef move_all_images_to_new_folder(images, new_dir, files_limit = None): files = glob.glob(str(images/'*.*g')) if(files_limit is not None): files = files[:files_limit] for file in files: shutil.move(file, new_dir/os.path.basename(file))move_all_images_to_new_folder(TRAIN_A, new_dir = TEST_A, files_limit = int(min(LIMIT*0.1, 25)))move_all_images_to_new_folder(TRAIN_B, new_dir = TEST_B, files_limit = int(min(LIMIT*0.1, 25)))" }, { "code": null, "e": 4264, "s": 4223, "text": "Let’s see the images we’re working with." }, { "code": null, "e": 4690, "s": 4264, "text": "import PILimport randomdef plot_from_image_path(path, title): all_imgs = glob.glob(str(path/'*.*g')) print(f'{len(all_imgs)} imgs in {title} directory') img_path = random.choice(all_imgs) img = PIL.Image.open(img_path) plt.imshow(img) plt.title(title) plt.show()plot_from_image_path(TRAIN_A, 'TRAIN_A')plot_from_image_path(TRAIN_B, 'TRAIN_B')plot_from_image_path(TEST_A, 'TEST_A')plot_from_image_path(TEST_B, 'TEST_B')" }, { "code": null, "e": 4720, "s": 4690, "text": "Everything looks pretty good!" }, { "code": null, "e": 4801, "s": 4720, "text": "Now we can create the model. I’ve made a few adjustments to the existing script." }, { "code": null, "e": 4838, "s": 4801, "text": "Let’s create a few helper functions." }, { "code": null, "e": 4978, "s": 4838, "text": "These functions help me copy the saved models to my google drive. It also helps test the model and store the output images to google drive." }, { "code": null, "e": 7055, "s": 4978, "text": "import osfrom pathlib import Pathfrom distutils.dir_util import copy_treeimport matplotlib.pyplot as pltimport randomdef copy_to_drive(folder = 'cyclegan_simpsonify'): drive_folder = Path('/content/drive/My Drive/')/folder if(drive_folder.exists()): shutil.rmtree(drive_folder) shutil.copytree('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/'+NAME+'/', str(drive_folder))def get_corresponding_photo(file_path): return file_path.replace('fake', 'real')def plot_results(number): for i in range(number): img_path = random.choice(glob.glob('./results/'+NAME+'/test_latest/images/*fake.*g')) print(img_path) img = plt.imread(img_path) plt.imshow(img) plt.title('fake') plt.show() print(get_corresponding_photo(img_path)) img = plt.imread(get_corresponding_photo(img_path)) plt.imshow(img) plt.title('real') plt.show()def get_model(src, dst): # copy across model try: os.remove(dst) except: pass shutil.copyfile(src, dst)def copy_from_drive(folder = 'cyclegan_simpsonify'): drive_folder = Path('/content/drive/My Drive/')/folder if(not Path('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/').exists()): os.mkdir('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/') if(Path('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/'+NAME+'/').exists()): shutil.rmtree('/content/pytorch-CycleGAN-and-pix2pix/checkpoints/'+NAME+'/') shutil.copytree(str(drive_folder), '/content/pytorch-CycleGAN-and-pix2pix/checkpoints/'+NAME+'/')def test_model (number_results = 5, direction = 'BtoA', src = None, dst = None): # delete results folder and recrete shutil.rmtree('./results') os.mkdir('./results') # get appropriate model if (src is None): src = './checkpoints/'+NAME+'/latest_net_G_'+direction.split('to')[-1]+'.pth' if (dst is None): dst = './checkpoints/'+NAME+'/latest_net_G.pth' get_model(src, dst) if (direction == 'BtoA'): test = TEST_B else: test = TEST_A cmd = 'python test.py --dataroot '+str(test)+' --name '+str(NAME)+' --model test --no_dropout' os.system(cmd) plot_results(number_results)" }, { "code": null, "e": 7094, "s": 7055, "text": "Let’s create the options for training." }, { "code": null, "e": 7592, "s": 7094, "text": "import timefrom options.train_options import TrainOptionsfrom data import create_datasetfrom models import create_modelfrom util.visualizer import Visualizerimport shutilimport osfrom pathlib import Pathfrom tqdm.notebook import tqdmoptions_list = ['--name', NAME,\\\t\t'--dataroot', TRAIN_A.parent,\\\t\t'--batch_size', BATCH_SIZE,\\\t\t'--checkpoints_dir', './checkpoints',\\\t\t'--lr', 2e-4,\\\t\t'--n_epochs', EPOCHS,\\\t\t'--n_epochs_decay', EPOCHS//2,\\\t\t'--name', NAME]opt = TrainOptions().parse(options_list)" }, { "code": null, "e": 7660, "s": 7592, "text": "First we create the dataset using the options we specified earlier." }, { "code": null, "e": 7775, "s": 7660, "text": "dataset = create_dataset(opt)dataset_size = len(dataset)print('The number of training images = %d' % dataset_size)" }, { "code": null, "e": 7824, "s": 7775, "text": "Then we create the model and run the setup call." }, { "code": null, "e": 7909, "s": 7824, "text": "model = create_model(opt)model.setup(opt)visualizer = Visualizer(opt)total_iters = 0" }, { "code": null, "e": 8047, "s": 7909, "text": "Let’s see the generator from A to B. The naming convention is slightly different from the paper. In the paper the generator was called G." }, { "code": null, "e": 8134, "s": 8047, "text": "In the code they refer to this mapping function as G_A. The meaning is still the same." }, { "code": null, "e": 8176, "s": 8134, "text": "This generator function maps from A to B." }, { "code": null, "e": 8224, "s": 8176, "text": "In our case it maps from Simpsons to Real Life." }, { "code": null, "e": 8237, "s": 8224, "text": "model.netG_A" }, { "code": null, "e": 8282, "s": 8237, "text": "We can see here that the model uses Resnets." }, { "code": null, "e": 8401, "s": 8282, "text": "We have Conv2d, Batchnorm, ReLU, InstanceNorm2d and ReflectionPad2d. InstanceNorm2d and ReflectionPad2d are new to me." }, { "code": null, "e": 8494, "s": 8401, "text": "InstanceNorm2d: This is very similar to batch norm but it is applied to one image at a time." }, { "code": null, "e": 8580, "s": 8494, "text": "ReflectionPad2d: This will pad the tensor using the reflection of the input boundary." }, { "code": null, "e": 8626, "s": 8580, "text": "Now we can look at the discriminator as well." }, { "code": null, "e": 8639, "s": 8626, "text": "model.netD_A" }, { "code": null, "e": 8700, "s": 8639, "text": "The discriminator uses LeakyReLU, Conv2d and InstanceNorm2d." }, { "code": null, "e": 8811, "s": 8700, "text": "LeakyReLU is interesting. ReLU is an activation that adds non-linearity to the network. But what is LeakyReLU?" }, { "code": null, "e": 9038, "s": 8811, "text": "ReLU converts all negative values to 0. Since, the gradient of 0 is 0 neurons that reach large negative values effectively neuron cancel out to 0. They effectively 'die'. This means that your network eventually stops learning." }, { "code": null, "e": 9086, "s": 9038, "text": "This effect is known as the dying ReLU problem." }, { "code": null, "e": 9150, "s": 9086, "text": "LeakyReLU aims to fix this problem. The function is as follows:" }, { "code": null, "e": 9321, "s": 9150, "text": "​ This function essentially translates to: if a value is negative multiply it by negative_slope otherwise do nothing. negative_slope is usually 0.01, but you can vary it." }, { "code": null, "e": 9481, "s": 9321, "text": "So LeakyReLU significantly reduces the magnitude of negative values rather than sending them to 0. But the jury is still out on whether this really works well." }, { "code": null, "e": 9564, "s": 9481, "text": "Now we can train the model over a number of epochs. I’ve specified 10 epochs here." }, { "code": null, "e": 9594, "s": 9564, "text": "Here’s the code for training:" }, { "code": null, "e": 9790, "s": 9594, "text": "model.optimize_parameters() is where all the magic happens. It runs the loss functions, gets the gradients and updates the weights. By doing so it optimises the generators and the discriminators." }, { "code": null, "e": 9806, "s": 9790, "text": "Let’s train it!" }, { "code": null, "e": 9900, "s": 9806, "text": "I let the model train overnight on google colab and copied the .pth model to my google drive." }, { "code": null, "e": 9922, "s": 9900, "text": "Let’s see the output." }, { "code": null, "e": 9945, "s": 9922, "text": "test_model(10, 'BtoA')" }, { "code": null, "e": 9996, "s": 9945, "text": "It’s a good start. I particularly like this image:" }, { "code": null, "e": 10041, "s": 9996, "text": "It could use some improvement, to be honest." }, { "code": null, "e": 10130, "s": 10041, "text": "Let’s try running the AtoB cycle. So we'll convert simpsons characters into human faces." }, { "code": null, "e": 10153, "s": 10130, "text": "test_model(10, 'AtoB')" }, { "code": null, "e": 10286, "s": 10153, "text": "The authors of Cyclegan noted that tasks requiring large geometric changes aren’t likely to be successful. I’ve just confirmed this." }, { "code": null, "e": 10674, "s": 10286, "text": "The network seems to struggle with the large geometric shifts required to convert a simpsons character to a real person (and vice-versa). I’m unsure if more training would rectify this issue. The tricky thing with GANs is figuring out when to stop training. Visual inspection seems to be the answer for Cyclegan. It might be worthwhile to train for another few days and see what happens." }, { "code": null, "e": 10723, "s": 10674, "text": "The full jupyter notebook can be found on Github" } ]
Matplotlib.figure.Figure.set_frameon() in Python - GeeksforGeeks
03 May, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The set_frameon() method figure module of matplotlib library is used to set the width of the figure in inches. Syntax: set_frameon(self, b) Parameters: This method accept the following parameters that are discussed below: b : This parameter contains the boolean value. Returns: This method does not returns any value. Below examples illustrate the matplotlib.figure.Figure.set_frameon() function in matplotlib.figure: Example 1: # Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) fig.set_frameon(True) fig.suptitle("""matplotlib.figure.Figure.set_frameon()function Example\n\n""", fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.set_frameon(False) fig.suptitle("""matplotlib.figure.Figure.set_frameon()function Example\n\n""", fontweight ="bold") plt.show() Output: Matplotlib figure-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n03 May, 2020" }, { "code": null, "e": 24523, "s": 24212, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 24634, "s": 24523, "text": "The set_frameon() method figure module of matplotlib library is used to set the width of the figure in inches." }, { "code": null, "e": 24663, "s": 24634, "text": "Syntax: set_frameon(self, b)" }, { "code": null, "e": 24745, "s": 24663, "text": "Parameters: This method accept the following parameters that are discussed below:" }, { "code": null, "e": 24792, "s": 24745, "text": "b : This parameter contains the boolean value." }, { "code": null, "e": 24841, "s": 24792, "text": "Returns: This method does not returns any value." }, { "code": null, "e": 24941, "s": 24841, "text": "Below examples illustrate the matplotlib.figure.Figure.set_frameon() function in matplotlib.figure:" }, { "code": null, "e": 24952, "s": 24941, "text": "Example 1:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) fig.set_frameon(True) fig.suptitle(\"\"\"matplotlib.figure.Figure.set_frameon()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show()", "e": 25351, "s": 24952, "text": null }, { "code": null, "e": 25359, "s": 25351, "text": "Output:" }, { "code": null, "e": 25370, "s": 25359, "text": "Example 2:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.set_frameon(False) fig.suptitle(\"\"\"matplotlib.figure.Figure.set_frameon()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ", "e": 25797, "s": 25370, "text": null }, { "code": null, "e": 25805, "s": 25797, "text": "Output:" }, { "code": null, "e": 25829, "s": 25805, "text": "Matplotlib figure-class" }, { "code": null, "e": 25847, "s": 25829, "text": "Python-matplotlib" }, { "code": null, "e": 25854, "s": 25847, "text": "Python" }, { "code": null, "e": 25952, "s": 25854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25961, "s": 25952, "text": "Comments" }, { "code": null, "e": 25974, "s": 25961, "text": "Old Comments" }, { "code": null, "e": 26006, "s": 25974, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26062, "s": 26006, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26083, "s": 26062, "text": "Python OOPs Concepts" }, { "code": null, "e": 26122, "s": 26083, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26164, "s": 26122, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26191, "s": 26164, "text": "Python Classes and Objects" }, { "code": null, "e": 26222, "s": 26191, "text": "Python | os.path.join() method" }, { "code": null, "e": 26264, "s": 26222, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26300, "s": 26264, "text": "Python | Pandas dataframe.groupby()" } ]
A Peek at Data Sampling Methods | by Kurtis Pykes | Towards Data Science
Sampling Bias is one of the most common types of biases observed in real-world scenarios. It occurs when the data used to train a model doesn’t reflect the distribution of the samples that the model will receive whilst in production. towardsdatascience.com Generally, whenever we work on Machine Learning projects, it’s vital that the correct research is done about the real proportions of various properties in the data that will be observed in a production environment. Additionally, when we are actually working on a problem and the data set is very large, it’s usually not practical, nor necessary, to work with the entire data set — unless you want to be waiting hours whilst your processing transformations and feature engineering take place. A more effective strategy, which would still allow you to draw valid conclusions from your results, is to draw a sample from your data that is informative enough for learning valuable insights. This technique is known as Data Sampling. We refer to a subset of observations from a larger population as a sample. Sampling, however, is used in reference to the group of observations that data will be collected from for our research. Therefore, Data Sampling may be defined as a technique leveraged by practitioners to select a subset of observations that is representative of the larger population. Typically, people that work with data (i.e. Data Scientists, Data Analysts, etc.) use data sampling techniques to reduce a large data set to a smaller, more manageable amount of data without sacrificing the accuracy of their insights. There are 2 main data sampling strategies: Probability sampling involves random selection. All of the observations within the data have a chance to be selected, therefore strong statistical inferences could be made about the entire group. Non-probability sampling does not involve random selection. Instead, it’s based on convenience or other criteria. As a result, some observations do not have a chance of being selected regardless of the number of samples that are built. A major pitfall of the non-probability sampling methods is that they include non-representative samples and it is possible that important observations are excluded from the sample. Consequently, it’s usually recommended to consider probability sampling methods first which is why I will only be focusing on such sampling methods for the remainder of this article. As mentioned prior, we typically leverage data sampling methods in situations where it’s impractical to study an entire population because the data is too large, among other reasons (i.e. time, costs, etc.). For this demonstration, we will be using synthetic data I’ve created in Python — See code below. import numpy as npimport pandas as pd# create synthetic dataid = np.arange(0, 10).tolist()distance = np.round(np.random.normal(loc=100, scale =5, size=len(id)), 2)# convert to pandas dataframedata = {"id":id, "distance": distance}df = pd.DataFrame(data=data)df The most straightforward way to sample data is with simple random sampling. Essentially, the subset is built of observations that were chosen from a larger set purely by chance; Each observation has the same chance of being selected from the larger set. # simple sampling examplesimple_random_sample = df.sample(n=5, random_state=24)simple_random_sample Simple random sampling is extremely simple and easy to implement. On the other hand, it’s possible that we can still introduce bias into our sample data. For instance, consider an event where we have a large dataset with imbalanced labels. By performing simple random sampling, we may accidentally fail to capture enough examples to represent the minority class — if we catch any of them at all. Interval sampling is a technique that creates a subset by selecting observations from a larger set at a regular interval. For instance, we could decide to select every 31st observation from the larger set. # interval sampling exampleidx = np.arange(0, len(df), step=2)interval_sample = df.iloc[idx]interval_sample If the observations are randomized, then interval sampling typically tends to return a better sample than simple random sampling. However, if there is periodicity or repetitive patterns within our data then interval sampling is quite inappropriate. Stratified random sampling divides the larger data set into groups known as strata. From these groups, we randomly select the observations we want to create the new subset. The number of examples to select from each stratum is proportional to the size of the stratum. from sklearn.model_selection import StratifiedKFold# dividing the data into groupsdf["strata"] = np.repeat([1, 2], len(df)/2).tolist()# instantiating stratified samplingstratified = StratifiedKFold(n_splits=2)1qfor x, y in stratified.split(df, df["strata"]): stratified_random_sample = df.iloc[x]stratified_random_sample This sampling strategy tends to improve the representativeness of the sample by reducing the amount of bias we introduce; In the worst-case scenario, our resulting sample would be of no less quality than that of simple random sampling. On the other hand, defining the strata can be a difficult task because it requires good knowledge of the properties of the data. It’s also the slowest of the methods presented. When we do not know how to define the strata of the data, cluster random sampling is a good alternative. Upon deciding the number of clusters we’d like our data to have, we then divide the larger set into these smaller clusters, then randomly select from among them to form a sample. # cluster sampling example# removing the stratadf.drop("strata", axis=1, inplace=True)# Divide the units into 5 clusters of equal sizedf['cluster_id'] = np.repeat([range(1,6)], len(df)/5)# Append the indexes from the clusters that meet the criteriaidx = []# add all observations with an even cluster_id to idxfor i in range(0, len(df)): if df['cluster_id'].iloc[i] % 2 == 0: idx.append(i)cluster_random_sample = df.iloc[idx]cluster_random_sample Cluster sampling is much more time and cost-efficient than the other probability sampling methods. However, it’s difficult to ensure that your clusters are representative of the larger set, therefore, it often provides less statistical certainty than other methods like simple random sampling. Data sampling is an effective technique to use when working with a large data set. By leveraging data sampling techniques, we can sample a smaller, easier manage subset of the larger set to perform our analysis and modeling whilst ensuring we still draw valid conclusions from this subset. In this article, we covered the 2 main ways to perform data sampling, why it may be better to start with probability sampling techniques, and implemented 4 probability sample techniques in python. Thank you for reading! If you enjoyed this article, connect with me by subscribing to my FREE weekly newsletter. Never miss a post I make about Artificial Intelligence, Data Science, and Freelancing.
[ { "code": null, "e": 406, "s": 172, "text": "Sampling Bias is one of the most common types of biases observed in real-world scenarios. It occurs when the data used to train a model doesn’t reflect the distribution of the samples that the model will receive whilst in production." }, { "code": null, "e": 429, "s": 406, "text": "towardsdatascience.com" }, { "code": null, "e": 644, "s": 429, "text": "Generally, whenever we work on Machine Learning projects, it’s vital that the correct research is done about the real proportions of various properties in the data that will be observed in a production environment." }, { "code": null, "e": 921, "s": 644, "text": "Additionally, when we are actually working on a problem and the data set is very large, it’s usually not practical, nor necessary, to work with the entire data set — unless you want to be waiting hours whilst your processing transformations and feature engineering take place." }, { "code": null, "e": 1157, "s": 921, "text": "A more effective strategy, which would still allow you to draw valid conclusions from your results, is to draw a sample from your data that is informative enough for learning valuable insights. This technique is known as Data Sampling." }, { "code": null, "e": 1518, "s": 1157, "text": "We refer to a subset of observations from a larger population as a sample. Sampling, however, is used in reference to the group of observations that data will be collected from for our research. Therefore, Data Sampling may be defined as a technique leveraged by practitioners to select a subset of observations that is representative of the larger population." }, { "code": null, "e": 1753, "s": 1518, "text": "Typically, people that work with data (i.e. Data Scientists, Data Analysts, etc.) use data sampling techniques to reduce a large data set to a smaller, more manageable amount of data without sacrificing the accuracy of their insights." }, { "code": null, "e": 1796, "s": 1753, "text": "There are 2 main data sampling strategies:" }, { "code": null, "e": 1992, "s": 1796, "text": "Probability sampling involves random selection. All of the observations within the data have a chance to be selected, therefore strong statistical inferences could be made about the entire group." }, { "code": null, "e": 2228, "s": 1992, "text": "Non-probability sampling does not involve random selection. Instead, it’s based on convenience or other criteria. As a result, some observations do not have a chance of being selected regardless of the number of samples that are built." }, { "code": null, "e": 2592, "s": 2228, "text": "A major pitfall of the non-probability sampling methods is that they include non-representative samples and it is possible that important observations are excluded from the sample. Consequently, it’s usually recommended to consider probability sampling methods first which is why I will only be focusing on such sampling methods for the remainder of this article." }, { "code": null, "e": 2800, "s": 2592, "text": "As mentioned prior, we typically leverage data sampling methods in situations where it’s impractical to study an entire population because the data is too large, among other reasons (i.e. time, costs, etc.)." }, { "code": null, "e": 2897, "s": 2800, "text": "For this demonstration, we will be using synthetic data I’ve created in Python — See code below." }, { "code": null, "e": 3158, "s": 2897, "text": "import numpy as npimport pandas as pd# create synthetic dataid = np.arange(0, 10).tolist()distance = np.round(np.random.normal(loc=100, scale =5, size=len(id)), 2)# convert to pandas dataframedata = {\"id\":id, \"distance\": distance}df = pd.DataFrame(data=data)df" }, { "code": null, "e": 3412, "s": 3158, "text": "The most straightforward way to sample data is with simple random sampling. Essentially, the subset is built of observations that were chosen from a larger set purely by chance; Each observation has the same chance of being selected from the larger set." }, { "code": null, "e": 3512, "s": 3412, "text": "# simple sampling examplesimple_random_sample = df.sample(n=5, random_state=24)simple_random_sample" }, { "code": null, "e": 3908, "s": 3512, "text": "Simple random sampling is extremely simple and easy to implement. On the other hand, it’s possible that we can still introduce bias into our sample data. For instance, consider an event where we have a large dataset with imbalanced labels. By performing simple random sampling, we may accidentally fail to capture enough examples to represent the minority class — if we catch any of them at all." }, { "code": null, "e": 4114, "s": 3908, "text": "Interval sampling is a technique that creates a subset by selecting observations from a larger set at a regular interval. For instance, we could decide to select every 31st observation from the larger set." }, { "code": null, "e": 4222, "s": 4114, "text": "# interval sampling exampleidx = np.arange(0, len(df), step=2)interval_sample = df.iloc[idx]interval_sample" }, { "code": null, "e": 4471, "s": 4222, "text": "If the observations are randomized, then interval sampling typically tends to return a better sample than simple random sampling. However, if there is periodicity or repetitive patterns within our data then interval sampling is quite inappropriate." }, { "code": null, "e": 4739, "s": 4471, "text": "Stratified random sampling divides the larger data set into groups known as strata. From these groups, we randomly select the observations we want to create the new subset. The number of examples to select from each stratum is proportional to the size of the stratum." }, { "code": null, "e": 5063, "s": 4739, "text": "from sklearn.model_selection import StratifiedKFold# dividing the data into groupsdf[\"strata\"] = np.repeat([1, 2], len(df)/2).tolist()# instantiating stratified samplingstratified = StratifiedKFold(n_splits=2)1qfor x, y in stratified.split(df, df[\"strata\"]): stratified_random_sample = df.iloc[x]stratified_random_sample" }, { "code": null, "e": 5476, "s": 5063, "text": "This sampling strategy tends to improve the representativeness of the sample by reducing the amount of bias we introduce; In the worst-case scenario, our resulting sample would be of no less quality than that of simple random sampling. On the other hand, defining the strata can be a difficult task because it requires good knowledge of the properties of the data. It’s also the slowest of the methods presented." }, { "code": null, "e": 5760, "s": 5476, "text": "When we do not know how to define the strata of the data, cluster random sampling is a good alternative. Upon deciding the number of clusters we’d like our data to have, we then divide the larger set into these smaller clusters, then randomly select from among them to form a sample." }, { "code": null, "e": 6216, "s": 5760, "text": "# cluster sampling example# removing the stratadf.drop(\"strata\", axis=1, inplace=True)# Divide the units into 5 clusters of equal sizedf['cluster_id'] = np.repeat([range(1,6)], len(df)/5)# Append the indexes from the clusters that meet the criteriaidx = []# add all observations with an even cluster_id to idxfor i in range(0, len(df)): if df['cluster_id'].iloc[i] % 2 == 0: idx.append(i)cluster_random_sample = df.iloc[idx]cluster_random_sample" }, { "code": null, "e": 6510, "s": 6216, "text": "Cluster sampling is much more time and cost-efficient than the other probability sampling methods. However, it’s difficult to ensure that your clusters are representative of the larger set, therefore, it often provides less statistical certainty than other methods like simple random sampling." }, { "code": null, "e": 6997, "s": 6510, "text": "Data sampling is an effective technique to use when working with a large data set. By leveraging data sampling techniques, we can sample a smaller, easier manage subset of the larger set to perform our analysis and modeling whilst ensuring we still draw valid conclusions from this subset. In this article, we covered the 2 main ways to perform data sampling, why it may be better to start with probability sampling techniques, and implemented 4 probability sample techniques in python." }, { "code": null, "e": 7020, "s": 6997, "text": "Thank you for reading!" } ]
PyQtGraph – Double Click Event for Bar Graph - GeeksforGeeks
30 Nov, 2021 In this article we will see how we can create a double click event with the bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart. Double click event is the vent which get triggered when double mouse click is occurred on the bar graph.We can create a plot window and bar graph with the help of commands given below # creating a pyqtgraph plot window window = pg.plot() # creating a bar graph of green color bargraph = pg.BarGraphItem(x=x, height=y1, width=0.6, brush='g') In order to do this we have modify the bar graph class, below is the class which can be used # Bar Graph class class BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # increase the scale of the graph # x-axis by 2 and y-axis by 2 self.scale(2, 2) # print the message print("Mouse Double Click Event") Below is the implementation Python3 # importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # increase the scale of the graph # x-axis by 2 and y-axis by 2 self.scale(2, 2) # print the message print("Mouse Double Click Event") class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a plot window plot = pg.plot() # create list for y-axis y1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axis x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6 # with bar colors = green bargraph = BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # bargraph.viewRangeChanged.connect(lambda: print("sss")) # add item to plot window # adding bargraph item to the plot window plot.addItem(bargraph) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # plot window goes on right side, spanning 3 rows layout.addWidget(plot, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Mouse Double Click Event Mouse Double Click Event Mouse Double Click Event anikakapoor Python-gui Python-PyQt Python-PyQtGraph Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26323, "s": 26295, "text": "\n30 Nov, 2021" }, { "code": null, "e": 27275, "s": 26323, "text": "In this article we will see how we can create a double click event with the bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart. Double click event is the vent which get triggered when double mouse click is occurred on the bar graph.We can create a plot window and bar graph with the help of commands given below " }, { "code": null, "e": 27433, "s": 27275, "text": "# creating a pyqtgraph plot window\nwindow = pg.plot()\n\n# creating a bar graph of green color\nbargraph = pg.BarGraphItem(x=x, height=y1, width=0.6, brush='g')" }, { "code": null, "e": 27527, "s": 27433, "text": "In order to do this we have modify the bar graph class, below is the class which can be used " }, { "code": null, "e": 28021, "s": 27527, "text": "# Bar Graph class\nclass BarGraphItem(pg.BarGraphItem):\n \n # constructor which inherit original \n # BarGraphItem\n def __init__(self, *args, **kwargs):\n pg.BarGraphItem.__init__(self, *args, **kwargs)\n\n # creating a mouse double click event\n def mouseDoubleClickEvent(self, e):\n \n # increase the scale of the graph\n # x-axis by 2 and y-axis by 2\n self.scale(2, 2)\n \n # print the message\n print(\"Mouse Double Click Event\")" }, { "code": null, "e": 28050, "s": 28021, "text": "Below is the implementation " }, { "code": null, "e": 28058, "s": 28050, "text": "Python3" }, { "code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * # Bar Graph classclass BarGraphItem(pg.BarGraphItem): # constructor which inherit original # BarGraphItem def __init__(self, *args, **kwargs): pg.BarGraphItem.__init__(self, *args, **kwargs) # creating a mouse double click event def mouseDoubleClickEvent(self, e): # increase the scale of the graph # x-axis by 2 and y-axis by 2 self.scale(2, 2) # print the message print(\"Mouse Double Click Event\") class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a plot window plot = pg.plot() # create list for y-axis y1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axis x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6 # with bar colors = green bargraph = BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # bargraph.viewRangeChanged.connect(lambda: print(\"sss\")) # add item to plot window # adding bargraph item to the plot window plot.addItem(bargraph) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # plot window goes on right side, spanning 3 rows layout.addWidget(plot, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 30266, "s": 28058, "text": null }, { "code": null, "e": 30276, "s": 30266, "text": "Output : " }, { "code": null, "e": 30351, "s": 30276, "text": "Mouse Double Click Event\nMouse Double Click Event\nMouse Double Click Event" }, { "code": null, "e": 30363, "s": 30351, "text": "anikakapoor" }, { "code": null, "e": 30374, "s": 30363, "text": "Python-gui" }, { "code": null, "e": 30386, "s": 30374, "text": "Python-PyQt" }, { "code": null, "e": 30403, "s": 30386, "text": "Python-PyQtGraph" }, { "code": null, "e": 30410, "s": 30403, "text": "Python" }, { "code": null, "e": 30508, "s": 30410, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30526, "s": 30508, "text": "Python Dictionary" }, { "code": null, "e": 30561, "s": 30526, "text": "Read a file line by line in Python" }, { "code": null, "e": 30593, "s": 30561, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30615, "s": 30593, "text": "Enumerate() in Python" }, { "code": null, "e": 30657, "s": 30615, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30687, "s": 30657, "text": "Iterate over a list in Python" }, { "code": null, "e": 30713, "s": 30687, "text": "Python String | replace()" }, { "code": null, "e": 30757, "s": 30713, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30786, "s": 30757, "text": "*args and **kwargs in Python" } ]
Encode Number in C++
Suppose we have a non-negative integer n, and we have to find the encoded form of it. The encoding strategy will be as follows − So if the number is 23, then result will be 1000, if the number is 54, then it will be 10111 To solve this, we will follow these steps − Create one method called bin, this will take n and k, this method will act like below res := empty string while n > 0res := res + the digit of n mod 2n := n /2 res := res + the digit of n mod 2 n := n /2 reverse the number res while x > length of resres := prepend 0 with res res := prepend 0 with res return res The actual method will be as follows − if n = 0, then return empty string, if n is 1, return “0”, or when n is 2, then return “1” x := log n base 2 if 2 ^ (x + 1) – 1 = n, thenans := empty stringincrease x by 1while x is not 0, then ans := append 0 with ans, and increase x by 1return ans ans := empty string increase x by 1 while x is not 0, then ans := append 0 with ans, and increase x by 1 return ans return bin(n – 2^x + 1, x) Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: string bin(int n, int x){ string result = ""; while(n>0){ result += (n%2) + '0'; n/=2; } reverse(result.begin(), result.end()); while(x>result.size())result = '0' + result; return result; } string encode(int n) { if(n == 0)return ""; if(n == 1)return "0"; if(n==2) return "1"; int x = log2(n); if(((1<<(x+1)) - 1) == n){ string ans = ""; x++; while(x--)ans+="0"; return ans; } return bin(n - (1<<x) + 1, x); } }; main(){ Solution ob; cout << (ob.encode(23)) << endl; cout << (ob.encode(56)) << endl; } 23 54 1000 11001
[ { "code": null, "e": 1191, "s": 1062, "text": "Suppose we have a non-negative integer n, and we have to find the encoded form of it. The encoding strategy will be as follows −" }, { "code": null, "e": 1284, "s": 1191, "text": "So if the number is 23, then result will be 1000, if the number is 54, then it will be 10111" }, { "code": null, "e": 1328, "s": 1284, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1414, "s": 1328, "text": "Create one method called bin, this will take n and k, this method will act like below" }, { "code": null, "e": 1434, "s": 1414, "text": "res := empty string" }, { "code": null, "e": 1488, "s": 1434, "text": "while n > 0res := res + the digit of n mod 2n := n /2" }, { "code": null, "e": 1522, "s": 1488, "text": "res := res + the digit of n mod 2" }, { "code": null, "e": 1532, "s": 1522, "text": "n := n /2" }, { "code": null, "e": 1555, "s": 1532, "text": "reverse the number res" }, { "code": null, "e": 1604, "s": 1555, "text": "while x > length of resres := prepend 0 with res" }, { "code": null, "e": 1630, "s": 1604, "text": "res := prepend 0 with res" }, { "code": null, "e": 1641, "s": 1630, "text": "return res" }, { "code": null, "e": 1680, "s": 1641, "text": "The actual method will be as follows −" }, { "code": null, "e": 1771, "s": 1680, "text": "if n = 0, then return empty string, if n is 1, return “0”, or when n is 2, then return “1”" }, { "code": null, "e": 1789, "s": 1771, "text": "x := log n base 2" }, { "code": null, "e": 1930, "s": 1789, "text": "if 2 ^ (x + 1) – 1 = n, thenans := empty stringincrease x by 1while x is not 0, then ans := append 0 with ans, and increase x by 1return ans" }, { "code": null, "e": 1950, "s": 1930, "text": "ans := empty string" }, { "code": null, "e": 1966, "s": 1950, "text": "increase x by 1" }, { "code": null, "e": 2035, "s": 1966, "text": "while x is not 0, then ans := append 0 with ans, and increase x by 1" }, { "code": null, "e": 2046, "s": 2035, "text": "return ans" }, { "code": null, "e": 2073, "s": 2046, "text": "return bin(n – 2^x + 1, x)" }, { "code": null, "e": 2143, "s": 2073, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2154, "s": 2143, "text": " Live Demo" }, { "code": null, "e": 2883, "s": 2154, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n string bin(int n, int x){\n string result = \"\";\n while(n>0){\n result += (n%2) + '0';\n n/=2;\n }\n reverse(result.begin(), result.end());\n while(x>result.size())result = '0' + result;\n return result;\n }\n string encode(int n) {\n if(n == 0)return \"\";\n if(n == 1)return \"0\";\n if(n==2) return \"1\";\n int x = log2(n);\n if(((1<<(x+1)) - 1) == n){\n string ans = \"\";\n x++;\n while(x--)ans+=\"0\";\n return ans;\n }\n return bin(n - (1<<x) + 1, x);\n }\n};\nmain(){\n Solution ob;\n cout << (ob.encode(23)) << endl;\n cout << (ob.encode(56)) << endl;\n}" }, { "code": null, "e": 2889, "s": 2883, "text": "23\n54" }, { "code": null, "e": 2900, "s": 2889, "text": "1000\n11001" } ]
Predict the Column | Practice | GeeksforGeeks
Given a matrix(2D array) M of size N*N consisting of 0s and 1s only. The task is to find the column with maximum number of 0s. Example: Input:N = 3M[][] = {{1, 1, 0}, {1, 1, 0}, {1, 1, 0}}Output:2Explanation:2nd column (0-based indexing) is having 3 zeros which is maximum among all columns. Your Task:Your task is to complete the function columnWithMaxZero() which should return the column number with maximum number of zeros. If more than one column exists, print the one which comes first. Constraints:1 <= N <= 1020 <= A[i][j] <= 1 0 mannukhurana103976 days ago Java int columnWithMaxZeros(int arr[][], int N) { // time: O(n*n) // space: O(1) int max=0; int index=-1; for(int i=0; i<N; i++){ int temp=0; for(int j=0; j<N; j++){ temp += arr[j][i]==0?1:0; } if(max<temp) {max = temp; index=i;} } return index; } +1 kartikeyashokgautam4 weeks ago Easy to understand JAVA Solution :- int columnWithMaxZeros(int arr[][], int N) { // 3M[][] = {{1, 1, 0}, {1, 1, 0}, {1, 1, 0}} HashMap<Integer,Integer> hm = new HashMap<>(); for(int i=0;i<N;i++) // 0-0 , 1-0 , 2-0 initializing each column as containing 0 zeroes { hm.put(i,0); } // if any column contains zero then increase its value by one // in this way we will stores no. of zeroes with corresponding columns for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { if(arr[i][j]==0) { hm.put(j,hm.get(j)+1); } } } // here we will check which column contains max zeroes int max=0; int columnWithMaxZero = 0; for(int i=0;i<N;i++) { if(hm.get(i)>max) { max=hm.get(i); columnWithMaxZero=i; } } return columnWithMaxZero; } 0 hgaur7011 month ago TIME COMPLEXITY : O(N*N), TIME TAKEN : 0.1 int columnWithMaxZeros(vector<vector<int>>arr,int N){ int highNum = 0; int column = 0; for (int i = 0; i < N; i++) { int temp = 0; for (int j = 0; j < N; j++) { if (arr[j][i] == 0) { temp++; } } if (temp > highNum) { highNum = temp; column = i; } } return column; } 0 yakash2220002 months ago class Solution{ int columnWithMaxZeros(int arr[][], int N) { int m=0,c=0,res=0,j; for (int i=0;i<N;i++){ for (j=0;j<N;j++){ if(arr[j][i]==0){ c++; } } if(m<c){ res=i; } m=Math.max(c,m); c=0; } return res; }} 0 dangrio2 months ago int columnWithMaxZeros(vector<vector<int>>arr,int N){ // Your code here int max=INT_MIN, count=0, col; for(int i=0;i<N;i++){ count=0; for(int j=0;j<N;j++){ if(arr[j][i]==0) count++; } if(max<count){ col = i; max = count; } } return col; } 0 mulangacanon This comment was deleted. 0 harshitshivam001 This comment was deleted. 0 bhagyeshreddy29113 months ago int columnWithMaxZeros(vector<vector<int>>arr,int N){ int maxi = 0; // intialising maximum count int ans = 0; // intialising column index for(int col = 0; col < N; col++) { // traverse through the column and row int temp = 0; for(int row = 0; row < N; row++) { if(arr[row][col] == 0) { temp++; } if(temp > maxi) { maxi = temp; ans = col; } } } return ans; }}; 0 hitentandon3 months ago Python: mcc,mc = 0,0; for i in range(N): cc=0; for j in range(N): if arr[j][i]==0: cc+=1; if cc > mc: mcc,mc = i,cc; return mcc; C++: int mcc=0, mc=0; for(int i = 0; i < N; i++) { int cc=0; for(int j = 0; j < N; j++) if(!arr[j][i]) cc++; if(cc>mc) { mc = cc; mcc = i; } } return mcc; JS: columnWithMaxZeros(M,N){ let mcc=0, mc=0; for(let i = 0; i < N; i++) { let cc=0; for(let j = 0; j < N; j++) if(M[j][i]===0) cc++; if(cc>mc) { mc = cc; mcc = i; } } return mcc; } Java: int mcc=0, mc=0; for(int i = 0; i < N; i++) { int cc=0; for(int j = 0; j < N; j++) if(arr[j][i]==0) cc++; if(cc>mc) { mc = cc; mcc = i; } } return mcc; 0 sudhirswain1203 months ago class Solution: def columnWithMaxZeros(self,arr,N): # code here max_count,ans=0,0 for i in range(N): temp=0 for j in range(N): if (arr[j][i]==0): temp+=1 if temp > max_count: max_count=temp ans=i return ans We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 353, "s": 226, "text": "Given a matrix(2D array) M of size N*N consisting of 0s and 1s only. The task is to find the column with maximum number of 0s." }, { "code": null, "e": 362, "s": 353, "text": "Example:" }, { "code": null, "e": 532, "s": 362, "text": "Input:N = 3M[][] = {{1, 1, 0}, {1, 1, 0}, {1, 1, 0}}Output:2Explanation:2nd column (0-based indexing) is having 3 zeros which is maximum among all columns." }, { "code": null, "e": 733, "s": 532, "text": "Your Task:Your task is to complete the function columnWithMaxZero() which should return the column number with maximum number of zeros. If more than one column exists, print the one which comes first." }, { "code": null, "e": 776, "s": 733, "text": "Constraints:1 <= N <= 1020 <= A[i][j] <= 1" }, { "code": null, "e": 778, "s": 776, "text": "0" }, { "code": null, "e": 806, "s": 778, "text": "mannukhurana103976 days ago" }, { "code": null, "e": 811, "s": 806, "text": "Java" }, { "code": null, "e": 1174, "s": 813, "text": " int columnWithMaxZeros(int arr[][], int N)\n {\n // time: O(n*n)\n // space: O(1)\n int max=0;\n int index=-1;\n \n for(int i=0; i<N; i++){\n int temp=0;\n for(int j=0; j<N; j++){\n temp += arr[j][i]==0?1:0;\n }\n if(max<temp) {max = temp; index=i;}\n }\n return index;\n }" }, { "code": null, "e": 1177, "s": 1174, "text": "+1" }, { "code": null, "e": 1208, "s": 1177, "text": "kartikeyashokgautam4 weeks ago" }, { "code": null, "e": 1245, "s": 1208, "text": "Easy to understand JAVA Solution :- " }, { "code": null, "e": 1361, "s": 1247, "text": " int columnWithMaxZeros(int arr[][], int N) { // 3M[][] = {{1, 1, 0}, {1, 1, 0}, {1, 1, 0}}" }, { "code": null, "e": 1563, "s": 1361, "text": " HashMap<Integer,Integer> hm = new HashMap<>(); for(int i=0;i<N;i++) // 0-0 , 1-0 , 2-0 initializing each column as containing 0 zeroes { hm.put(i,0); } " }, { "code": null, "e": 2238, "s": 1563, "text": " // if any column contains zero then increase its value by one // in this way we will stores no. of zeroes with corresponding columns for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { if(arr[i][j]==0) { hm.put(j,hm.get(j)+1); } } } // here we will check which column contains max zeroes int max=0; int columnWithMaxZero = 0; for(int i=0;i<N;i++) { if(hm.get(i)>max) { max=hm.get(i); columnWithMaxZero=i; } } return columnWithMaxZero; }" }, { "code": null, "e": 2240, "s": 2238, "text": "0" }, { "code": null, "e": 2260, "s": 2240, "text": "hgaur7011 month ago" }, { "code": null, "e": 2305, "s": 2260, "text": "TIME COMPLEXITY : O(N*N), TIME TAKEN : 0.1" }, { "code": null, "e": 2761, "s": 2305, "text": "int columnWithMaxZeros(vector<vector<int>>arr,int N){\n \n int highNum = 0;\n int column = 0;\n\n for (int i = 0; i < N; i++)\n {\n int temp = 0;\n for (int j = 0; j < N; j++)\n {\n if (arr[j][i] == 0)\n {\n temp++;\n }\n }\n if (temp > highNum)\n {\n highNum = temp;\n column = i;\n }\n }\n\n return column;\n \n \n }" }, { "code": null, "e": 2763, "s": 2761, "text": "0" }, { "code": null, "e": 2788, "s": 2763, "text": "yakash2220002 months ago" }, { "code": null, "e": 3166, "s": 2788, "text": "class Solution{ int columnWithMaxZeros(int arr[][], int N) { int m=0,c=0,res=0,j; for (int i=0;i<N;i++){ for (j=0;j<N;j++){ if(arr[j][i]==0){ c++; } } if(m<c){ res=i; } m=Math.max(c,m); c=0; } return res; }}" }, { "code": null, "e": 3168, "s": 3166, "text": "0" }, { "code": null, "e": 3188, "s": 3168, "text": "dangrio2 months ago" }, { "code": null, "e": 3558, "s": 3188, "text": "int columnWithMaxZeros(vector<vector<int>>arr,int N){ // Your code here int max=INT_MIN, count=0, col; for(int i=0;i<N;i++){ count=0; for(int j=0;j<N;j++){ if(arr[j][i]==0) count++; } if(max<count){ col = i; max = count; } } return col; }" }, { "code": null, "e": 3560, "s": 3558, "text": "0" }, { "code": null, "e": 3573, "s": 3560, "text": "mulangacanon" }, { "code": null, "e": 3599, "s": 3573, "text": "This comment was deleted." }, { "code": null, "e": 3601, "s": 3599, "text": "0" }, { "code": null, "e": 3618, "s": 3601, "text": "harshitshivam001" }, { "code": null, "e": 3644, "s": 3618, "text": "This comment was deleted." }, { "code": null, "e": 3646, "s": 3644, "text": "0" }, { "code": null, "e": 3676, "s": 3646, "text": "bhagyeshreddy29113 months ago" }, { "code": null, "e": 4214, "s": 3676, "text": " int columnWithMaxZeros(vector<vector<int>>arr,int N){ int maxi = 0; // intialising maximum count int ans = 0; // intialising column index for(int col = 0; col < N; col++) { // traverse through the column and row int temp = 0; for(int row = 0; row < N; row++) { if(arr[row][col] == 0) { temp++; } if(temp > maxi) { maxi = temp; ans = col; } } } return ans; }};" }, { "code": null, "e": 4216, "s": 4214, "text": "0" }, { "code": null, "e": 4240, "s": 4216, "text": "hitentandon3 months ago" }, { "code": null, "e": 4248, "s": 4240, "text": "Python:" }, { "code": null, "e": 4474, "s": 4248, "text": " mcc,mc = 0,0;\n for i in range(N):\n cc=0;\n for j in range(N):\n if arr[j][i]==0:\n cc+=1;\n if cc > mc:\n mcc,mc = i,cc;\n return mcc; " }, { "code": null, "e": 4479, "s": 4474, "text": "C++:" }, { "code": null, "e": 4785, "s": 4479, "text": " int mcc=0, mc=0;\n for(int i = 0; i < N; i++)\n {\n int cc=0;\n for(int j = 0; j < N; j++)\n if(!arr[j][i])\n cc++;\n if(cc>mc)\n {\n mc = cc;\n mcc = i;\n }\n }\n return mcc; " }, { "code": null, "e": 4789, "s": 4785, "text": "JS:" }, { "code": null, "e": 5127, "s": 4789, "text": " columnWithMaxZeros(M,N){\n let mcc=0, mc=0;\n for(let i = 0; i < N; i++)\n {\n let cc=0;\n for(let j = 0; j < N; j++)\n if(M[j][i]===0)\n cc++;\n if(cc>mc)\n {\n mc = cc;\n mcc = i;\n }\n }\n return mcc;\n }" }, { "code": null, "e": 5133, "s": 5127, "text": "Java:" }, { "code": null, "e": 5440, "s": 5133, "text": " int mcc=0, mc=0;\n for(int i = 0; i < N; i++)\n {\n int cc=0;\n for(int j = 0; j < N; j++)\n if(arr[j][i]==0)\n cc++;\n if(cc>mc)\n {\n mc = cc;\n mcc = i;\n }\n }\n return mcc;" }, { "code": null, "e": 5442, "s": 5440, "text": "0" }, { "code": null, "e": 5469, "s": 5442, "text": "sudhirswain1203 months ago" }, { "code": null, "e": 5814, "s": 5469, "text": "class Solution: def columnWithMaxZeros(self,arr,N): # code here max_count,ans=0,0 for i in range(N): temp=0 for j in range(N): if (arr[j][i]==0): temp+=1 if temp > max_count: max_count=temp ans=i return ans " }, { "code": null, "e": 5960, "s": 5814, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5996, "s": 5960, "text": " Login to access your submissions. " }, { "code": null, "e": 6006, "s": 5996, "text": "\nProblem\n" }, { "code": null, "e": 6016, "s": 6006, "text": "\nContest\n" }, { "code": null, "e": 6079, "s": 6016, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6227, "s": 6079, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6435, "s": 6227, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6541, "s": 6435, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Histogram for discrete values with Matplotlib
To plot a histogram for discrete values with matplotlib, we can use hist() method. Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Make a list of discrete values. Make a list of discrete values. Use hist() method to plot data with bins=length of data and edgecolor=black. Use hist() method to plot data with bins=length of data and edgecolor=black. To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True data = [1, 4, 2, 3, 5, 9, 6, 7] plt.hist(data, bins=len(data), edgecolor='black') plt.show()
[ { "code": null, "e": 1145, "s": 1062, "text": "To plot a histogram for discrete values with matplotlib, we can use hist() method." }, { "code": null, "e": 1221, "s": 1145, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1297, "s": 1221, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1329, "s": 1297, "text": "Make a list of discrete values." }, { "code": null, "e": 1361, "s": 1329, "text": "Make a list of discrete values." }, { "code": null, "e": 1438, "s": 1361, "text": "Use hist() method to plot data with bins=length of data and edgecolor=black." }, { "code": null, "e": 1515, "s": 1438, "text": "Use hist() method to plot data with bins=length of data and edgecolor=black." }, { "code": null, "e": 1557, "s": 1515, "text": "To display the figure, use show() method." }, { "code": null, "e": 1599, "s": 1557, "text": "To display the figure, use show() method." }, { "code": null, "e": 1818, "s": 1599, "text": "from matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = [1, 4, 2, 3, 5, 9, 6, 7]\nplt.hist(data, bins=len(data), edgecolor='black')\nplt.show()" } ]
Program to find area of a circle - GeeksforGeeks
06 Nov, 2021 The area of a circle can simply be evaluated using the following formula. Area = pi * r2 where r is radius of circle and it maybe in float because value of pie is 3.14 C++ C Java Python3 C# PHP Javascript // C++ program to find area// of circle#include <iostream>const double pi = 3.14159265358979323846;using namespace std; // function to calculate the area of circlefloat findArea(float r){ return (pi * r * r);}// driver codeint main(){ float r, Area; r = 5; // function calling Area = findArea(r); // displaying the area cout << "Area of Circle is :" << Area; return 0;} // C program to find area// of circle#include <stdio.h>#include <math.h>#define PI 3.142 double findArea(int r){ return PI * pow(r, 2);} int main(){ printf("Area is %f", findArea(5)); return 0;} // Java program to find area// of circle class Test{ static final double PI = Math.PI; static double findArea(int r) { return PI * Math.pow(r, 2); } // Driver method public static void main(String[] args) { System.out.println("Area is " + findArea(5)); }} # Python3 program to find Area of a circle def findArea(r): PI = 3.142 return PI * (r*r); # Driver methodprint("Area is %.6f" % findArea(5)); # This code is contributed by Chinmoy Lenka // C# program to find area of circleusing System; class GFG{ static double PI = Math.PI; static double findArea(int r) { return PI * Math.Pow(r, 2); } // Driver method static void Main() { Console.Write("Area is " + findArea(5)); }} // This code is contributed by Sam007. <?php// PHP program to find area// of circle function findArea( $r){ $PI =3.142; return $PI * pow($r, 2);} // Driver Codeecho("Area is ");echo(findArea(5));return 0; // This code is contributed by vt_m.?> <script> // Javascript program to find area// of circle let pi = 3.14159265358979323846; // function to calculate the area of circlefunction findArea(r){ return (pi * r * r);} // Driver code let r, Area; r = 5; // function calling Area = findArea(r); // displaying the area document.write("Area of Circle is :" + Area); // This code is contributed by Mayank Tyagi </script> Output: Area is 78.550000 Time Complexity: O(1) Auxiliary Space: O(1) vt_m RamAryan mayanktyagi1709 harisuman7082 subhammahato348 area-volume-programs Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Circle and Lattice Points Queries on count of points lie inside a circle Given n line segments, find if any two segments intersect Check if a point lies inside a rectangle | Set-2 Window to Viewport Transformation in Computer Graphics with Implementation Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24493, "s": 24465, "text": "\n06 Nov, 2021" }, { "code": null, "e": 24568, "s": 24493, "text": "The area of a circle can simply be evaluated using the following formula. " }, { "code": null, "e": 24665, "s": 24570, "text": "Area = pi * r2\nwhere r is radius of circle and it maybe in float because value of pie is 3.14 " }, { "code": null, "e": 24673, "s": 24669, "text": "C++" }, { "code": null, "e": 24675, "s": 24673, "text": "C" }, { "code": null, "e": 24680, "s": 24675, "text": "Java" }, { "code": null, "e": 24688, "s": 24680, "text": "Python3" }, { "code": null, "e": 24691, "s": 24688, "text": "C#" }, { "code": null, "e": 24695, "s": 24691, "text": "PHP" }, { "code": null, "e": 24706, "s": 24695, "text": "Javascript" }, { "code": "// C++ program to find area// of circle#include <iostream>const double pi = 3.14159265358979323846;using namespace std; // function to calculate the area of circlefloat findArea(float r){ return (pi * r * r);}// driver codeint main(){ float r, Area; r = 5; // function calling Area = findArea(r); // displaying the area cout << \"Area of Circle is :\" << Area; return 0;}", "e": 25101, "s": 24706, "text": null }, { "code": "// C program to find area// of circle#include <stdio.h>#include <math.h>#define PI 3.142 double findArea(int r){ return PI * pow(r, 2);} int main(){ printf(\"Area is %f\", findArea(5)); return 0;}", "e": 25304, "s": 25101, "text": null }, { "code": "// Java program to find area// of circle class Test{ static final double PI = Math.PI; static double findArea(int r) { return PI * Math.pow(r, 2); } // Driver method public static void main(String[] args) { System.out.println(\"Area is \" + findArea(5)); }}", "e": 25622, "s": 25304, "text": null }, { "code": "# Python3 program to find Area of a circle def findArea(r): PI = 3.142 return PI * (r*r); # Driver methodprint(\"Area is %.6f\" % findArea(5)); # This code is contributed by Chinmoy Lenka", "e": 25814, "s": 25622, "text": null }, { "code": "// C# program to find area of circleusing System; class GFG{ static double PI = Math.PI; static double findArea(int r) { return PI * Math.Pow(r, 2); } // Driver method static void Main() { Console.Write(\"Area is \" + findArea(5)); }} // This code is contributed by Sam007.", "e": 26138, "s": 25814, "text": null }, { "code": "<?php// PHP program to find area// of circle function findArea( $r){ $PI =3.142; return $PI * pow($r, 2);} // Driver Codeecho(\"Area is \");echo(findArea(5));return 0; // This code is contributed by vt_m.?>", "e": 26355, "s": 26138, "text": null }, { "code": "<script> // Javascript program to find area// of circle let pi = 3.14159265358979323846; // function to calculate the area of circlefunction findArea(r){ return (pi * r * r);} // Driver code let r, Area; r = 5; // function calling Area = findArea(r); // displaying the area document.write(\"Area of Circle is :\" + Area); // This code is contributed by Mayank Tyagi </script>", "e": 26761, "s": 26355, "text": null }, { "code": null, "e": 26770, "s": 26761, "text": "Output: " }, { "code": null, "e": 26788, "s": 26770, "text": "Area is 78.550000" }, { "code": null, "e": 26810, "s": 26788, "text": "Time Complexity: O(1)" }, { "code": null, "e": 26833, "s": 26810, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 26838, "s": 26833, "text": "vt_m" }, { "code": null, "e": 26847, "s": 26838, "text": "RamAryan" }, { "code": null, "e": 26863, "s": 26847, "text": "mayanktyagi1709" }, { "code": null, "e": 26877, "s": 26863, "text": "harisuman7082" }, { "code": null, "e": 26893, "s": 26877, "text": "subhammahato348" }, { "code": null, "e": 26914, "s": 26893, "text": "area-volume-programs" }, { "code": null, "e": 26924, "s": 26914, "text": "Geometric" }, { "code": null, "e": 26937, "s": 26924, "text": "Mathematical" }, { "code": null, "e": 26956, "s": 26937, "text": "School Programming" }, { "code": null, "e": 26969, "s": 26956, "text": "Mathematical" }, { "code": null, "e": 26979, "s": 26969, "text": "Geometric" }, { "code": null, "e": 27077, "s": 26979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27086, "s": 27077, "text": "Comments" }, { "code": null, "e": 27099, "s": 27086, "text": "Old Comments" }, { "code": null, "e": 27125, "s": 27099, "text": "Circle and Lattice Points" }, { "code": null, "e": 27172, "s": 27125, "text": "Queries on count of points lie inside a circle" }, { "code": null, "e": 27230, "s": 27172, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 27279, "s": 27230, "text": "Check if a point lies inside a rectangle | Set-2" }, { "code": null, "e": 27354, "s": 27279, "text": "Window to Viewport Transformation in Computer Graphics with Implementation" }, { "code": null, "e": 27384, "s": 27354, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 27444, "s": 27384, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 27459, "s": 27444, "text": "C++ Data Types" }, { "code": null, "e": 27502, "s": 27459, "text": "Set in C++ Standard Template Library (STL)" } ]
C++ Program to Implement The Edmonds-Karp Algorithm
This is a C++ Program to Implement the Edmonds-Karp algorithm to calculate maximum flow between source and sink vertex. Begin function edmondsKarp() : initiate flow as 0. If there is an augmenting path from source to sink, add the path to flow. Return flow. End #include<cstdio> #include<queue> #include<cstring> #include<vector> #include<iostream> using namespace std; int c[10][10]; int flowPassed[10][10]; vector<int> g[10]; int parList[10]; int currentPathC[10]; int bfs(int sNode, int eNode)//breadth first search { memset(parList, -1, sizeof(parList)); memset(currentPathC, 0, sizeof(currentPathC)); queue<int> q;//declare queue vector q.push(sNode); parList[sNode] = -1;//initialize parlist’s source node currentPathC[sNode] = 999;//initialize currentpath’s source node while(!q.empty())// if q is not empty { int currNode = q.front(); q.pop(); for(int i=0; i<g[currNode].size(); i++) { int to = g[currNode][i]; if(parList[to] == -1) { if(c[currNode][to] - flowPassed[currNode][to] > 0) { parList[to] = currNode; currentPathC[to] = min(currentPathC[currNode], c[currNode][to] - flowPassed[currNode][to]); if(to == eNode) { return currentPathC[eNode]; } q.push(to); } } } } return 0; } int edmondsKarp(int sNode, int eNode) { int maxFlow = 0; while(true) { int flow = bfs(sNode, eNode); if (flow == 0) { break; } maxFlow += flow; int currNode = eNode; while(currNode != sNode) { int prevNode = parList[currNode]; flowPassed[prevNode][currNode] += flow; flowPassed[currNode][prevNode] -= flow; currNode = prevNode; } } return maxFlow; } int main() { int nodCount, edCount; cout<<"enter the number of nodes and edges\n"; cin>>nodCount>>edCount; int source, sink; cout<<"enter the source and sink\n"; cin>>source>>sink; for(int ed = 0; ed < edCount; ed++) { cout<<"enter the start and end vertex along with capacity\n"; int from, to, cap; cin>>from>>to>>cap; c[from][to] = cap; g[from].push_back(to); g[to].push_back(from); } int maxFlow = edmondsKarp(source, sink); cout<<endl<<endl<<"Max Flow is:"<<maxFlow<<endl; } enter the number of nodes and edges 6 7 enter the source and sink 0 4 enter the start and end vertex along with capacity 0 1 14 enter the start and end vertex along with capacity 2 4 10 enter the start and end vertex along with capacity 6 7 9 enter the start and end vertex along with capacity 5 2 10 enter the start and end vertex along with capacity 1 4 12 enter the start and end vertex along with capacity 2 0 15 enter the start and end vertex along with capacity 5 3 15 Max Flow is:12
[ { "code": null, "e": 1182, "s": 1062, "text": "This is a C++ Program to Implement the Edmonds-Karp algorithm to calculate maximum flow between source and sink vertex." }, { "code": null, "e": 1345, "s": 1182, "text": "Begin\n function edmondsKarp() :\n initiate flow as 0.\n If there is an augmenting path from source to sink, add the path to flow.\n Return flow.\nEnd" }, { "code": null, "e": 3539, "s": 1345, "text": "#include<cstdio>\n#include<queue>\n#include<cstring>\n#include<vector>\n#include<iostream>\nusing namespace std;\nint c[10][10];\nint flowPassed[10][10];\nvector<int> g[10];\nint parList[10];\nint currentPathC[10];\nint bfs(int sNode, int eNode)//breadth first search\n{\n memset(parList, -1, sizeof(parList));\n memset(currentPathC, 0, sizeof(currentPathC));\n queue<int> q;//declare queue vector\n q.push(sNode);\n parList[sNode] = -1;//initialize parlist’s source node\n currentPathC[sNode] = 999;//initialize currentpath’s source node\n while(!q.empty())// if q is not empty\n {\n int currNode = q.front();\n q.pop();\n for(int i=0; i<g[currNode].size(); i++)\n {\n int to = g[currNode][i];\n if(parList[to] == -1)\n {\n if(c[currNode][to] - flowPassed[currNode][to] > 0)\n {\n parList[to] = currNode;\n currentPathC[to] = min(currentPathC[currNode],\n c[currNode][to] - flowPassed[currNode][to]);\n if(to == eNode)\n {\n return currentPathC[eNode];\n }\n q.push(to);\n }\n }\n }\n }\n return 0;\n}\nint edmondsKarp(int sNode, int eNode)\n{\n int maxFlow = 0;\n while(true)\n {\n int flow = bfs(sNode, eNode);\n if (flow == 0)\n {\n break;\n }\n maxFlow += flow;\n int currNode = eNode;\n while(currNode != sNode)\n {\n int prevNode = parList[currNode];\n flowPassed[prevNode][currNode] += flow;\n flowPassed[currNode][prevNode] -= flow;\n currNode = prevNode;\n }\n }\nreturn maxFlow;\n}\nint main()\n{\n int nodCount, edCount;\n cout<<\"enter the number of nodes and edges\\n\";\n cin>>nodCount>>edCount;\n int source, sink;\n cout<<\"enter the source and sink\\n\";\n cin>>source>>sink;\n for(int ed = 0; ed < edCount; ed++)\n {\n cout<<\"enter the start and end vertex along with capacity\\n\";\n int from, to, cap;\n cin>>from>>to>>cap;\n c[from][to] = cap;\n g[from].push_back(to);\n g[to].push_back(from);\n }\n int maxFlow = edmondsKarp(source, sink);\n cout<<endl<<endl<<\"Max Flow is:\"<<maxFlow<<endl;\n}" }, { "code": null, "e": 4029, "s": 3539, "text": "enter the number of nodes and edges\n6\n7\nenter the source and sink\n0\n4\nenter the start and end vertex along with capacity\n0\n1\n14\nenter the start and end vertex along with capacity\n2\n4\n10\nenter the start and end vertex along with capacity\n6\n7\n9\nenter the start and end vertex along with capacity\n5\n2\n10\nenter the start and end vertex along with capacity\n1\n4\n12\nenter the start and end vertex along with capacity\n2\n0\n15\nenter the start and end vertex along with capacity\n5\n3\n15\nMax Flow is:12" } ]
PyQt5 - How to get visible column in the model of combo box - GeeksforGeeks
22 Apr, 2020 In this article we will see how we can get the visible column of combo box. Column model is used to set the column which will be visible to the user, model column property holds the column in the model that is visible. In order to set this we use setModelColumn method. In order to get the model column we use modelColumn method. Syntax : combo_box.modelColumn() Argument : It takes no argument Return : It returns integer Below is the implementation – # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 150, 30) # setting visible model column self.combo_box.setModelColumn(0) # geek list geek_list = ["Sayian", "Super Saiyan", "Super Sayian 2", "Super Sayian B"] # making it editable self.combo_box.setEditable(True) # adding list of items to combo box self.combo_box.addItems(geek_list) # getting model column model_column = self.combo_box.modelColumn() # creating label to show model label = QLabel("Model Column = " + str(model_column), self) # setting geometry to the label label.setGeometry(200, 100, 300, 30) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-ComboBox Python-gui Python-PyQt 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": "\n22 Apr, 2020" }, { "code": null, "e": 24231, "s": 23901, "text": "In this article we will see how we can get the visible column of combo box. Column model is used to set the column which will be visible to the user, model column property holds the column in the model that is visible. In order to set this we use setModelColumn method. In order to get the model column we use modelColumn method." }, { "code": null, "e": 24264, "s": 24231, "text": "Syntax : combo_box.modelColumn()" }, { "code": null, "e": 24296, "s": 24264, "text": "Argument : It takes no argument" }, { "code": null, "e": 24324, "s": 24296, "text": "Return : It returns integer" }, { "code": null, "e": 24354, "s": 24324, "text": "Below is the implementation –" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 150, 30) # setting visible model column self.combo_box.setModelColumn(0) # geek list geek_list = [\"Sayian\", \"Super Saiyan\", \"Super Sayian 2\", \"Super Sayian B\"] # making it editable self.combo_box.setEditable(True) # adding list of items to combo box self.combo_box.addItems(geek_list) # getting model column model_column = self.combo_box.modelColumn() # creating label to show model label = QLabel(\"Model Column = \" + str(model_column), self) # setting geometry to the label label.setGeometry(200, 100, 300, 30) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 25805, "s": 24354, "text": null }, { "code": null, "e": 25814, "s": 25805, "text": "Output :" }, { "code": null, "e": 25836, "s": 25814, "text": "Python PyQt5-ComboBox" }, { "code": null, "e": 25847, "s": 25836, "text": "Python-gui" }, { "code": null, "e": 25859, "s": 25847, "text": "Python-PyQt" }, { "code": null, "e": 25866, "s": 25859, "text": "Python" }, { "code": null, "e": 25964, "s": 25866, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25973, "s": 25964, "text": "Comments" }, { "code": null, "e": 25986, "s": 25973, "text": "Old Comments" }, { "code": null, "e": 26022, "s": 25986, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26045, "s": 26022, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26084, "s": 26045, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26117, "s": 26084, "text": "Python | Convert set into a list" }, { "code": null, "e": 26166, "s": 26117, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26207, "s": 26166, "text": "Python - Call function from another file" }, { "code": null, "e": 26223, "s": 26207, "text": "loops in python" }, { "code": null, "e": 26274, "s": 26223, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26306, "s": 26274, "text": "Python Dictionary keys() method" } ]
Power Function in C/C++
Power function is used to calculate the power of the given number. The pow function find the value of a raised to the power b i.e. ab. double pow(double a , double b) It accepts a double integers as input and output a double integer as output. It pow() function is defined in math.h package. If you pass an integer to the power function, the function converts it into double data type. But there's an issue with this, sometimes this conversion might store this as a lower double. For example, if we pass 3 and is converted as 2.99 then the square is 8.99940001 which converts into 8. But this is an error although it comes rarely but to remove this error 0.25 is added to it. #include <stdio.h> #include <math.h> int main() { double x = 6.1, y = 2; double result = pow(x, y); printf("%f raised to the power of %f is %f \n" ,x,y, result ); // Taking integers int a = 5 , b = 2; int square = pow(a,b); printf("%d raised to the power of %d is %d \n", a,b, square ); return 0; } 6.100000 raised to the power of 2.000000 is 37.210000 5 raised to the power of 2 is 25
[ { "code": null, "e": 1129, "s": 1062, "text": "Power function is used to calculate the power of the given number." }, { "code": null, "e": 1197, "s": 1129, "text": "The pow function find the value of a raised to the power b i.e. ab." }, { "code": null, "e": 1229, "s": 1197, "text": "double pow(double a , double b)" }, { "code": null, "e": 1354, "s": 1229, "text": "It accepts a double integers as input and output a double integer as output. It pow() function is defined in math.h package." }, { "code": null, "e": 1738, "s": 1354, "text": "If you pass an integer to the power function, the function converts it into double data type. But there's an issue with this, sometimes this conversion might store this as a lower double. For example, if we pass 3 and is converted as 2.99 then the square is 8.99940001 which converts into 8. But this is an error although it comes rarely but to remove this error 0.25 is added to it." }, { "code": null, "e": 2061, "s": 1738, "text": "#include <stdio.h>\n#include <math.h>\nint main() {\n double x = 6.1, y = 2;\n double result = pow(x, y);\n printf(\"%f raised to the power of %f is %f \\n\" ,x,y, result );\n // Taking integers\n int a = 5 , b = 2;\n int square = pow(a,b);\n printf(\"%d raised to the power of %d is %d \\n\", a,b, square );\n return 0;\n}" }, { "code": null, "e": 2148, "s": 2061, "text": "6.100000 raised to the power of 2.000000 is 37.210000\n5 raised to the power of 2 is 25" } ]
C# Program for Largest Sum Contiguous Subarray - GeeksforGeeks
29 Nov, 2021 Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum. Kadane’s Algorithm: Initialize: max_so_far = INT_MIN max_ending_here = 0 Loop for each element of the array (a) max_ending_here = max_ending_here + a[i] (b) if(max_so_far < max_ending_here) max_so_far = max_ending_here (c) if(max_ending_here < 0) max_ending_here = 0 return max_so_far Explanation: The simple idea of Kadane's algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far Lets take the example: {-2, -3, 4, -1, -2, 1, 5, -3} max_so_far = max_ending_here = 0 for i=0, a[0] = -2 max_ending_here = max_ending_here + (-2) Set max_ending_here = 0 because max_ending_here < 0 for i=1, a[1] = -3 max_ending_here = max_ending_here + (-3) Set max_ending_here = 0 because max_ending_here < 0 for i=2, a[2] = 4 max_ending_here = max_ending_here + (4) max_ending_here = 4 max_so_far is updated to 4 because max_ending_here greater than max_so_far which was 0 till now for i=3, a[3] = -1 max_ending_here = max_ending_here + (-1) max_ending_here = 3 for i=4, a[4] = -2 max_ending_here = max_ending_here + (-2) max_ending_here = 1 for i=5, a[5] = 1 max_ending_here = max_ending_here + (1) max_ending_here = 2 for i=6, a[6] = 5 max_ending_here = max_ending_here + (5) max_ending_here = 7 max_so_far is updated to 7 because max_ending_here is greater than max_so_far for i=7, a[7] = -3 max_ending_here = max_ending_here + (-3) max_ending_here = 4 Program: C# // C# program to print largest // contiguous array sumusing System; class GFG{ static int maxSubArraySum(int []a) { int size = a.Length; int max_so_far = int.MinValue, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } // Driver code public static void Main () { int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; Console.Write("Maximum contiguous sum is " + maxSubArraySum(a)); } } // This code is contributed by Sam007_ Output: Maximum contiguous sum is 7 Another approach: C# static int maxSubArraySum(int[] a, int size){ int max_so_far = a[0], max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; /* Do not compare for all elements. Compare only when max_ending_here > 0 */ else if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} // This code is contributed// by ChitraNayal Time Complexity: O(n) Algorithmic Paradigm: Dynamic ProgrammingFollowing is another simple implementation suggested by Mohit Kumar. The implementation handles the case when all numbers in the array are negative. C# // C# program to print largest // contiguous array sumusing System; class GFG{ static int maxSubArraySum(int []a, int size) { int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = Math.Max(a[i], curr_max+a[i]); max_so_far = Math.Max(max_so_far, curr_max); } return max_so_far; } // Driver code public static void Main () { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; Console.Write("Maximum contiguous sum is " + maxSubArraySum(a, n)); } } // This code is contributed by Sam007_ Output: Maximum contiguous sum is 7 To print the subarray with the maximum sum, we maintain indices whenever we get the maximum sum. C# // C# program to print largest // contiguous array sumusing System; class GFG { static void maxSubArraySum(int []a, int size) { int max_so_far = int.MinValue, max_ending_here = 0, start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } Console.WriteLine("Maximum contiguous " + "sum is " + max_so_far); Console.WriteLine("Starting index " + start); Console.WriteLine("Ending index " + end); } // Driver code public static void Main() { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; maxSubArraySum(a, n); }} // This code is contributed// by anuj_67. Output: Maximum contiguous sum is 7 Starting index 2 Ending index 6 Kadane's Algorithm can be viewed both as a greedy and DP. As we can see that we are keeping a running sum of integers and when it becomes less than 0, we reset it to 0 (Greedy Part). This is because continuing with a negative sum is way more worse than restarting with a new range. Now it can also be viewed as a DP, at each stage we have 2 choices: Either take the current element and continue with previous sum OR restart a new range. These both choices are being taken care of in the implementation. Time Complexity: O(n) Auxiliary Space: O(1) Now try the below question Given an array of integers (possibly some elements negative), write a C program to find out the *maximum product* possible by multiplying 'n' consecutive integers in the array where n ≤ ARRAY_SIZE. Also, print the starting point of the maximum product subarray. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to Print a New Line in C# How to Remove Duplicate Values From an Array in C#? C# Program to print all permutations of a given string C# Program to Convert a Binary String to an Integer How to Convert ASCII Char to Byte in C#? Different Ways to Take Input and Print a Float Value in C# C# Program to Demonstrate the IList Interface Hash Function for String data in C# C# Program to Check a Specified Type is an Enum or Not C# Program to Read and Write a Byte Array to File using FileStream Class
[ { "code": null, "e": 25230, "s": 25202, "text": "\n29 Nov, 2021" }, { "code": null, "e": 25365, "s": 25230, "text": "Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum. " }, { "code": null, "e": 25387, "s": 25367, "text": "Kadane’s Algorithm:" }, { "code": null, "e": 25691, "s": 25387, "text": "Initialize:\n max_so_far = INT_MIN\n max_ending_here = 0\n\nLoop for each element of the array\n (a) max_ending_here = max_ending_here + a[i]\n (b) if(max_so_far < max_ending_here)\n max_so_far = max_ending_here\n (c) if(max_ending_here < 0)\n max_ending_here = 0\nreturn max_so_far" }, { "code": null, "e": 26062, "s": 25691, "text": "Explanation: The simple idea of Kadane's algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far " }, { "code": null, "e": 27171, "s": 26062, "text": " Lets take the example:\n {-2, -3, 4, -1, -2, 1, 5, -3}\n\n max_so_far = max_ending_here = 0\n\n for i=0, a[0] = -2\n max_ending_here = max_ending_here + (-2)\n Set max_ending_here = 0 because max_ending_here < 0\n\n for i=1, a[1] = -3\n max_ending_here = max_ending_here + (-3)\n Set max_ending_here = 0 because max_ending_here < 0\n\n for i=2, a[2] = 4\n max_ending_here = max_ending_here + (4)\n max_ending_here = 4\n max_so_far is updated to 4 because max_ending_here greater \n than max_so_far which was 0 till now\n\n for i=3, a[3] = -1\n max_ending_here = max_ending_here + (-1)\n max_ending_here = 3\n\n for i=4, a[4] = -2\n max_ending_here = max_ending_here + (-2)\n max_ending_here = 1\n\n for i=5, a[5] = 1\n max_ending_here = max_ending_here + (1)\n max_ending_here = 2\n\n for i=6, a[6] = 5\n max_ending_here = max_ending_here + (5)\n max_ending_here = 7\n max_so_far is updated to 7 because max_ending_here is \n greater than max_so_far\n\n for i=7, a[7] = -3\n max_ending_here = max_ending_here + (-3)\n max_ending_here = 4" }, { "code": null, "e": 27181, "s": 27171, "text": "Program: " }, { "code": null, "e": 27184, "s": 27181, "text": "C#" }, { "code": "// C# program to print largest // contiguous array sumusing System; class GFG{ static int maxSubArraySum(int []a) { int size = a.Length; int max_so_far = int.MinValue, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } // Driver code public static void Main () { int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; Console.Write(\"Maximum contiguous sum is \" + maxSubArraySum(a)); } } // This code is contributed by Sam007_", "e": 28008, "s": 27184, "text": null }, { "code": null, "e": 28016, "s": 28008, "text": "Output:" }, { "code": null, "e": 28044, "s": 28016, "text": "Maximum contiguous sum is 7" }, { "code": null, "e": 28062, "s": 28044, "text": "Another approach:" }, { "code": null, "e": 28065, "s": 28062, "text": "C#" }, { "code": "static int maxSubArraySum(int[] a, int size){ int max_so_far = a[0], max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; /* Do not compare for all elements. Compare only when max_ending_here > 0 */ else if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} // This code is contributed// by ChitraNayal", "e": 28570, "s": 28065, "text": null }, { "code": null, "e": 28593, "s": 28570, "text": "Time Complexity: O(n) " }, { "code": null, "e": 28784, "s": 28593, "text": "Algorithmic Paradigm: Dynamic ProgrammingFollowing is another simple implementation suggested by Mohit Kumar. The implementation handles the case when all numbers in the array are negative. " }, { "code": null, "e": 28787, "s": 28784, "text": "C#" }, { "code": "// C# program to print largest // contiguous array sumusing System; class GFG{ static int maxSubArraySum(int []a, int size) { int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = Math.Max(a[i], curr_max+a[i]); max_so_far = Math.Max(max_so_far, curr_max); } return max_so_far; } // Driver code public static void Main () { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; Console.Write(\"Maximum contiguous sum is \" + maxSubArraySum(a, n)); } } // This code is contributed by Sam007_", "e": 29425, "s": 28787, "text": null }, { "code": null, "e": 29434, "s": 29425, "text": "Output: " }, { "code": null, "e": 29462, "s": 29434, "text": "Maximum contiguous sum is 7" }, { "code": null, "e": 29561, "s": 29462, "text": "To print the subarray with the maximum sum, we maintain indices whenever we get the maximum sum. " }, { "code": null, "e": 29564, "s": 29561, "text": "C#" }, { "code": "// C# program to print largest // contiguous array sumusing System; class GFG { static void maxSubArraySum(int []a, int size) { int max_so_far = int.MinValue, max_ending_here = 0, start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } Console.WriteLine(\"Maximum contiguous \" + \"sum is \" + max_so_far); Console.WriteLine(\"Starting index \" + start); Console.WriteLine(\"Ending index \" + end); } // Driver code public static void Main() { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; maxSubArraySum(a, n); }} // This code is contributed// by anuj_67.", "e": 30727, "s": 29564, "text": null }, { "code": null, "e": 30736, "s": 30727, "text": "Output: " }, { "code": null, "e": 30796, "s": 30736, "text": "Maximum contiguous sum is 7\nStarting index 2\nEnding index 6" }, { "code": null, "e": 31300, "s": 30796, "text": "Kadane's Algorithm can be viewed both as a greedy and DP. As we can see that we are keeping a running sum of integers and when it becomes less than 0, we reset it to 0 (Greedy Part). This is because continuing with a negative sum is way more worse than restarting with a new range. Now it can also be viewed as a DP, at each stage we have 2 choices: Either take the current element and continue with previous sum OR restart a new range. These both choices are being taken care of in the implementation. " }, { "code": null, "e": 31322, "s": 31300, "text": "Time Complexity: O(n)" }, { "code": null, "e": 31344, "s": 31322, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 31633, "s": 31344, "text": "Now try the below question Given an array of integers (possibly some elements negative), write a C program to find out the *maximum product* possible by multiplying 'n' consecutive integers in the array where n ≤ ARRAY_SIZE. Also, print the starting point of the maximum product subarray." }, { "code": null, "e": 31758, "s": 31633, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31769, "s": 31758, "text": "nidhi_biet" }, { "code": null, "e": 31781, "s": 31769, "text": "C# Programs" }, { "code": null, "e": 31879, "s": 31781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31913, "s": 31879, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 31965, "s": 31913, "text": "How to Remove Duplicate Values From an Array in C#?" }, { "code": null, "e": 32020, "s": 31965, "text": "C# Program to print all permutations of a given string" }, { "code": null, "e": 32072, "s": 32020, "text": "C# Program to Convert a Binary String to an Integer" }, { "code": null, "e": 32113, "s": 32072, "text": "How to Convert ASCII Char to Byte in C#?" }, { "code": null, "e": 32172, "s": 32113, "text": "Different Ways to Take Input and Print a Float Value in C#" }, { "code": null, "e": 32218, "s": 32172, "text": "C# Program to Demonstrate the IList Interface" }, { "code": null, "e": 32254, "s": 32218, "text": "Hash Function for String data in C#" }, { "code": null, "e": 32309, "s": 32254, "text": "C# Program to Check a Specified Type is an Enum or Not" } ]
3 Top Python Packages to Learn Statistic for Data Scientist | by Cornellius Yudha Wijaya | Towards Data Science
If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here. Data Scientists are known for having better programming skills than a statistician and better statistic knowledge than a programmer. While learning programming skill is not an easy feat, sometimes new data people forget about the statistic skill. I know statistic is hard to learn, especially for people who are not formally educated in the statistic. However, it is possible to learn statistics from scratch — with the help of modern technology. Learning statistics becomes easier than before with all these developed statistic packages in the programming language. I know that many would argue if you want to learn statistics. You should use the R language instead of Python; but, I want to offer an alternative by using the Python package because many people start their Data Science journey by learning the Python language. In this article, I want to show you the 3 top Python Packages to learn Statistic and the example of how to use the package — remember, for learning. Let’s get into it! SciPy (pronounced “Sigh Pie”) is an open-source package computing tool for performing a scientific method in the Python environment. The Scipy itself is also a collection of numerical algorithms and domain-specific toolboxes used in many mathematical, engineering, and data research. One of the APIs available within Scipy is the statistical API called Stats. According to the Scipy homepage, Scipy.Stats is a module that contains a large number of probability distributions and a growing library of statistical functions, especially for probability function study. On the Scipy.Stats module, there are many statistical function API you could refer to for further learning. They are: Continuous distributions Multivariate distributions Discrete distributions Summary statistics Frequency statistics Correlation functions Statistical tests Transformations Statistical distances Random variate generation Circular statistical functions Contingency table functions Plot-tests Masked statistics functions Univariate and multivariate kernel density estimation To get a better understanding of the statistical working function, Scipy.Stats also provide a tutorial you could try. The tutorial is comprehensive that many newbies could follow; you have a little understanding of statistical terms with a note. Let’s try to learn some statistics with Scipy.Stats. If you are using Python from Anaconda distribution, the Scipy package is already inbuilt within the environment. If you choose to install the Scipy independently, you need to install the dependence package. You could do that via pip by executing this line below. python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose Let’s try to learn the simplest concept on Probability Distribution, and that is Normal distribution. First, we import the necessary package to the environment. #Import statistical package from Scipyfrom scipy import stats#Import the normal distribution classfrom scipy.stats import norm The norm class we import would become a probability function to produce a random variable that follows a normal distribution. To get more info regarding the class, we could try to print the documentation. print(stats.norm.__doc__) The documentation would provide you with all the basic information necessary to understand the object, the methods available, and the example of the class application. Norm class is used to produce a random variable that follows a normal distribution. The package has given you all the explanations to learn about it, and you only need to execute few lines to produce the concept example. Let’s use the example to produce a normal distribution plot. import matplotlib.pyplot as plt#Produce 1000 Random Variable following normal distributionr = norm.rvs(size=1000)#Plotting the distributionfig, ax = plt.subplots(1, 1)ax.hist(r, density=True, histtype='stepfilled', alpha=0.2)ax.legend(loc='best', frameon=False)plt.show() There is so much more you can explore with this package. I recommend you take your time exploring the statistical tutorial to understand the package and understand the theorem as well. Pingouin is an open-source statistical package that is mainly used for statistical. This package gives you many classes and functions to learn basic statistics and hypothesis testing. According to the developer, Pingouin is designed for users who want simple yet exhaustive stats functions. Pingouin is simple but exhaustive because the package gives you more explanation regarding the data. On Scipy.Stats, they return only the T-value and the p-value when sometimes we want more explanation regarding the data. In the Pingouin package, the calculation is taken a few steps above. For example, instead of returning only the T-value and p-value, the t-test from Pingouin also return the degrees of freedom, the effect size (Cohen’s d), the 95% confidence intervals of the difference in means, the statistical power, and the Bayes Factor (BF10) of the test. Currently, the Pingouin package provides an APIs function you could use for statistical testing. They are: ANOVA and T-test Bayesian Circular Contingency Correlation and regression Distribution Effect sizes Multiple comparisons and post-hoc tests Multivariate tests Non-parametric Others Plotting Power analysis Reliability and consistency Pingouin APIs documentation itself is wealthy for learning purposes. I have explored the file and find it really insightful. For example, let’s explore the ANOVA function. First, you need to install the Pingouin package. pip install pingouin The installation should only take you a second. After that, we would use an mpg dataset example to do an ANOVA statistical hypothesis testing with Pingouin. #Import necessary packageimport seaborn as snsimport pingouin as pgmpg = sns.load_dataset('mpg')pg.anova(data = mpg, dv = 'mpg', between = 'origin') The example statistical testing provides you with all the necessary scores you expect from the test. For further interpretation of the result, you should consult the API documentation here. Pingouin guideline also provides you a learning guideline for using some of the testing package functions. One of them is for One-way ANOVA testing. I have written a deeper explanation of the Pingouin package if you want to know more about the package. towardsdatascience.com Statsmodels is a statistical model python package that provides many classes and functions to create a statistical estimation. Statsmodel package use to be a part of the Scipy module, but currently, the statsmodel package is developed separately. What is different between Scipy.Stats and statsmodel? The Scipy.Stats module focuses on the statistical theorem such as probabilistic function and distribution, while the statsmodel package focuses on the statistical estimation based on the data. Statsmodel provides API that is frequently used in Statistical modeling. Statsmodel package split the APIs into 3 main models: statsmodels.api which provide many Cross-sectional models and methods, including Regression and GLM. statsmodels.tsa.api Which provide Time-series models and methods. statsmodels.formula.api Which provide an interface for specifying models using formula strings and DataFrames — in simpler term, you could create your own model. Statsmodel is a great starter package for anybody who wants to understand statistical modeling in greater depth. The user guide gives you an in-depth explanation of the concept you need for understanding statistical estimation. For example, endogenous and exogenous terms taken from the Statsmodel user guide is explained in the below passage: Some informal definitions of the terms are endogenous: caused by factors within the system exogenous: caused by factors outside the system Endogenous variables designates variables in an economic/econometric model that are explained, or predicted, by that model. http://stats.oecd.org/glossary/detail.asp?ID=794 Exogenous variables designates variables that appear in an economic/econometric model, but are not explained by that model (i.e. they are taken as given by the model). http://stats.oecd.org/glossary/detail.asp?ID=890 Let’s try to learn OLS (Ordinary Least Square) modeling using the Statsmodel package. If you did not use the Python from the Anaconda distribution or haven’t installed the Statsmodel package, you could use the following line to do it. pip install statsmodels Continuing the steps, let’s develop the model by importing the package and the dataset. #Importing the necessary packagefrom sklearn.datasets import load_bostonimport statsmodels.api as smfrom statsmodels.api import OLS#import the databoston = load_boston()data = pd.DataFrame(data = boston['data'], columns = boston['feature_names'])target = pd.Series(boston['target'])#Develop the modelsm_lm = OLS(target, sm.add_constant(data))result = sm_lm.fit()result.summary() The OLS model you develop with the Statsmodel package would have all the necessary results you expect from model estimation. For further interpretation of the result, you could visit the OLS example on the homepage. As a Data Scientist, you are expected to have adequate knowledge of statistics. The problem is, many data enthusiasts only focus on learning the programming language, especially Python. To help the statistic study, I want to introduce my top 3 Python Packages to learning statistics. They are: Scipy.StatsPingouinStatsmodels Scipy.Stats Pingouin Statsmodels Visit me on my LinkedIn or Twitter If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 342, "s": 172, "text": "If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here." }, { "code": null, "e": 589, "s": 342, "text": "Data Scientists are known for having better programming skills than a statistician and better statistic knowledge than a programmer. While learning programming skill is not an easy feat, sometimes new data people forget about the statistic skill." }, { "code": null, "e": 909, "s": 589, "text": "I know statistic is hard to learn, especially for people who are not formally educated in the statistic. However, it is possible to learn statistics from scratch — with the help of modern technology. Learning statistics becomes easier than before with all these developed statistic packages in the programming language." }, { "code": null, "e": 1170, "s": 909, "text": "I know that many would argue if you want to learn statistics. You should use the R language instead of Python; but, I want to offer an alternative by using the Python package because many people start their Data Science journey by learning the Python language." }, { "code": null, "e": 1338, "s": 1170, "text": "In this article, I want to show you the 3 top Python Packages to learn Statistic and the example of how to use the package — remember, for learning. Let’s get into it!" }, { "code": null, "e": 1622, "s": 1338, "text": "SciPy (pronounced “Sigh Pie”) is an open-source package computing tool for performing a scientific method in the Python environment. The Scipy itself is also a collection of numerical algorithms and domain-specific toolboxes used in many mathematical, engineering, and data research." }, { "code": null, "e": 1904, "s": 1622, "text": "One of the APIs available within Scipy is the statistical API called Stats. According to the Scipy homepage, Scipy.Stats is a module that contains a large number of probability distributions and a growing library of statistical functions, especially for probability function study." }, { "code": null, "e": 2022, "s": 1904, "text": "On the Scipy.Stats module, there are many statistical function API you could refer to for further learning. They are:" }, { "code": null, "e": 2047, "s": 2022, "text": "Continuous distributions" }, { "code": null, "e": 2074, "s": 2047, "text": "Multivariate distributions" }, { "code": null, "e": 2097, "s": 2074, "text": "Discrete distributions" }, { "code": null, "e": 2116, "s": 2097, "text": "Summary statistics" }, { "code": null, "e": 2137, "s": 2116, "text": "Frequency statistics" }, { "code": null, "e": 2159, "s": 2137, "text": "Correlation functions" }, { "code": null, "e": 2177, "s": 2159, "text": "Statistical tests" }, { "code": null, "e": 2193, "s": 2177, "text": "Transformations" }, { "code": null, "e": 2215, "s": 2193, "text": "Statistical distances" }, { "code": null, "e": 2241, "s": 2215, "text": "Random variate generation" }, { "code": null, "e": 2272, "s": 2241, "text": "Circular statistical functions" }, { "code": null, "e": 2300, "s": 2272, "text": "Contingency table functions" }, { "code": null, "e": 2311, "s": 2300, "text": "Plot-tests" }, { "code": null, "e": 2339, "s": 2311, "text": "Masked statistics functions" }, { "code": null, "e": 2393, "s": 2339, "text": "Univariate and multivariate kernel density estimation" }, { "code": null, "e": 2692, "s": 2393, "text": "To get a better understanding of the statistical working function, Scipy.Stats also provide a tutorial you could try. The tutorial is comprehensive that many newbies could follow; you have a little understanding of statistical terms with a note. Let’s try to learn some statistics with Scipy.Stats." }, { "code": null, "e": 2955, "s": 2692, "text": "If you are using Python from Anaconda distribution, the Scipy package is already inbuilt within the environment. If you choose to install the Scipy independently, you need to install the dependence package. You could do that via pip by executing this line below." }, { "code": null, "e": 3041, "s": 2955, "text": "python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose" }, { "code": null, "e": 3202, "s": 3041, "text": "Let’s try to learn the simplest concept on Probability Distribution, and that is Normal distribution. First, we import the necessary package to the environment." }, { "code": null, "e": 3329, "s": 3202, "text": "#Import statistical package from Scipyfrom scipy import stats#Import the normal distribution classfrom scipy.stats import norm" }, { "code": null, "e": 3534, "s": 3329, "text": "The norm class we import would become a probability function to produce a random variable that follows a normal distribution. To get more info regarding the class, we could try to print the documentation." }, { "code": null, "e": 3560, "s": 3534, "text": "print(stats.norm.__doc__)" }, { "code": null, "e": 3728, "s": 3560, "text": "The documentation would provide you with all the basic information necessary to understand the object, the methods available, and the example of the class application." }, { "code": null, "e": 4010, "s": 3728, "text": "Norm class is used to produce a random variable that follows a normal distribution. The package has given you all the explanations to learn about it, and you only need to execute few lines to produce the concept example. Let’s use the example to produce a normal distribution plot." }, { "code": null, "e": 4282, "s": 4010, "text": "import matplotlib.pyplot as plt#Produce 1000 Random Variable following normal distributionr = norm.rvs(size=1000)#Plotting the distributionfig, ax = plt.subplots(1, 1)ax.hist(r, density=True, histtype='stepfilled', alpha=0.2)ax.legend(loc='best', frameon=False)plt.show()" }, { "code": null, "e": 4467, "s": 4282, "text": "There is so much more you can explore with this package. I recommend you take your time exploring the statistical tutorial to understand the package and understand the theorem as well." }, { "code": null, "e": 4758, "s": 4467, "text": "Pingouin is an open-source statistical package that is mainly used for statistical. This package gives you many classes and functions to learn basic statistics and hypothesis testing. According to the developer, Pingouin is designed for users who want simple yet exhaustive stats functions." }, { "code": null, "e": 4980, "s": 4758, "text": "Pingouin is simple but exhaustive because the package gives you more explanation regarding the data. On Scipy.Stats, they return only the T-value and the p-value when sometimes we want more explanation regarding the data." }, { "code": null, "e": 5324, "s": 4980, "text": "In the Pingouin package, the calculation is taken a few steps above. For example, instead of returning only the T-value and p-value, the t-test from Pingouin also return the degrees of freedom, the effect size (Cohen’s d), the 95% confidence intervals of the difference in means, the statistical power, and the Bayes Factor (BF10) of the test." }, { "code": null, "e": 5431, "s": 5324, "text": "Currently, the Pingouin package provides an APIs function you could use for statistical testing. They are:" }, { "code": null, "e": 5448, "s": 5431, "text": "ANOVA and T-test" }, { "code": null, "e": 5457, "s": 5448, "text": "Bayesian" }, { "code": null, "e": 5466, "s": 5457, "text": "Circular" }, { "code": null, "e": 5478, "s": 5466, "text": "Contingency" }, { "code": null, "e": 5505, "s": 5478, "text": "Correlation and regression" }, { "code": null, "e": 5518, "s": 5505, "text": "Distribution" }, { "code": null, "e": 5531, "s": 5518, "text": "Effect sizes" }, { "code": null, "e": 5571, "s": 5531, "text": "Multiple comparisons and post-hoc tests" }, { "code": null, "e": 5590, "s": 5571, "text": "Multivariate tests" }, { "code": null, "e": 5605, "s": 5590, "text": "Non-parametric" }, { "code": null, "e": 5612, "s": 5605, "text": "Others" }, { "code": null, "e": 5621, "s": 5612, "text": "Plotting" }, { "code": null, "e": 5636, "s": 5621, "text": "Power analysis" }, { "code": null, "e": 5664, "s": 5636, "text": "Reliability and consistency" }, { "code": null, "e": 5885, "s": 5664, "text": "Pingouin APIs documentation itself is wealthy for learning purposes. I have explored the file and find it really insightful. For example, let’s explore the ANOVA function. First, you need to install the Pingouin package." }, { "code": null, "e": 5906, "s": 5885, "text": "pip install pingouin" }, { "code": null, "e": 6063, "s": 5906, "text": "The installation should only take you a second. After that, we would use an mpg dataset example to do an ANOVA statistical hypothesis testing with Pingouin." }, { "code": null, "e": 6212, "s": 6063, "text": "#Import necessary packageimport seaborn as snsimport pingouin as pgmpg = sns.load_dataset('mpg')pg.anova(data = mpg, dv = 'mpg', between = 'origin')" }, { "code": null, "e": 6402, "s": 6212, "text": "The example statistical testing provides you with all the necessary scores you expect from the test. For further interpretation of the result, you should consult the API documentation here." }, { "code": null, "e": 6551, "s": 6402, "text": "Pingouin guideline also provides you a learning guideline for using some of the testing package functions. One of them is for One-way ANOVA testing." }, { "code": null, "e": 6655, "s": 6551, "text": "I have written a deeper explanation of the Pingouin package if you want to know more about the package." }, { "code": null, "e": 6678, "s": 6655, "text": "towardsdatascience.com" }, { "code": null, "e": 6925, "s": 6678, "text": "Statsmodels is a statistical model python package that provides many classes and functions to create a statistical estimation. Statsmodel package use to be a part of the Scipy module, but currently, the statsmodel package is developed separately." }, { "code": null, "e": 7172, "s": 6925, "text": "What is different between Scipy.Stats and statsmodel? The Scipy.Stats module focuses on the statistical theorem such as probabilistic function and distribution, while the statsmodel package focuses on the statistical estimation based on the data." }, { "code": null, "e": 7299, "s": 7172, "text": "Statsmodel provides API that is frequently used in Statistical modeling. Statsmodel package split the APIs into 3 main models:" }, { "code": null, "e": 7400, "s": 7299, "text": "statsmodels.api which provide many Cross-sectional models and methods, including Regression and GLM." }, { "code": null, "e": 7466, "s": 7400, "text": "statsmodels.tsa.api Which provide Time-series models and methods." }, { "code": null, "e": 7628, "s": 7466, "text": "statsmodels.formula.api Which provide an interface for specifying models using formula strings and DataFrames — in simpler term, you could create your own model." }, { "code": null, "e": 7972, "s": 7628, "text": "Statsmodel is a great starter package for anybody who wants to understand statistical modeling in greater depth. The user guide gives you an in-depth explanation of the concept you need for understanding statistical estimation. For example, endogenous and exogenous terms taken from the Statsmodel user guide is explained in the below passage:" }, { "code": null, "e": 8015, "s": 7972, "text": "Some informal definitions of the terms are" }, { "code": null, "e": 8063, "s": 8015, "text": "endogenous: caused by factors within the system" }, { "code": null, "e": 8111, "s": 8063, "text": "exogenous: caused by factors outside the system" }, { "code": null, "e": 8284, "s": 8111, "text": "Endogenous variables designates variables in an economic/econometric model that are explained, or predicted, by that model. http://stats.oecd.org/glossary/detail.asp?ID=794" }, { "code": null, "e": 8501, "s": 8284, "text": "Exogenous variables designates variables that appear in an economic/econometric model, but are not explained by that model (i.e. they are taken as given by the model). http://stats.oecd.org/glossary/detail.asp?ID=890" }, { "code": null, "e": 8736, "s": 8501, "text": "Let’s try to learn OLS (Ordinary Least Square) modeling using the Statsmodel package. If you did not use the Python from the Anaconda distribution or haven’t installed the Statsmodel package, you could use the following line to do it." }, { "code": null, "e": 8760, "s": 8736, "text": "pip install statsmodels" }, { "code": null, "e": 8848, "s": 8760, "text": "Continuing the steps, let’s develop the model by importing the package and the dataset." }, { "code": null, "e": 9227, "s": 8848, "text": "#Importing the necessary packagefrom sklearn.datasets import load_bostonimport statsmodels.api as smfrom statsmodels.api import OLS#import the databoston = load_boston()data = pd.DataFrame(data = boston['data'], columns = boston['feature_names'])target = pd.Series(boston['target'])#Develop the modelsm_lm = OLS(target, sm.add_constant(data))result = sm_lm.fit()result.summary()" }, { "code": null, "e": 9443, "s": 9227, "text": "The OLS model you develop with the Statsmodel package would have all the necessary results you expect from model estimation. For further interpretation of the result, you could visit the OLS example on the homepage." }, { "code": null, "e": 9737, "s": 9443, "text": "As a Data Scientist, you are expected to have adequate knowledge of statistics. The problem is, many data enthusiasts only focus on learning the programming language, especially Python. To help the statistic study, I want to introduce my top 3 Python Packages to learning statistics. They are:" }, { "code": null, "e": 9768, "s": 9737, "text": "Scipy.StatsPingouinStatsmodels" }, { "code": null, "e": 9780, "s": 9768, "text": "Scipy.Stats" }, { "code": null, "e": 9789, "s": 9780, "text": "Pingouin" }, { "code": null, "e": 9801, "s": 9789, "text": "Statsmodels" }, { "code": null, "e": 9836, "s": 9801, "text": "Visit me on my LinkedIn or Twitter" } ]
Beginner’s Guide to Sentiment Analysis for Simplified Chinese using SnowNLP | by Ng Wai Foong | Towards Data Science
By reading this article, you will be exposed to a technique for analyzing the sentiments of any text in Simplified Chinese. This tutorial will be based on Simplified Chinese but it can be used on Traditional Chinese as well due to the fact that SnowNLP is capable of converting Traditional Chinese to Simplified Chinese. There will be 4 sections in this tutorial: Setup and installationUsage and API callTraining modelConclusion Setup and installation Usage and API call Training model Conclusion In this tutorial, I will be installing the modules required via pip on Windows operating system. Let’s start by getting the files from an open-source modules called SnowNLP which is a Simplified Chinese Text Processing module. Although this module has not been updated for quite some time, the results is good enough for most use cases. Go to the following link and download the required files. Once it is completed, extract the zipped files to a directory of your preference. You should have a snownlp-master folder which contains all the necessary files. SnowNLP supports Python 3 as stated in the official Github Link. In this tutorial, I will be using Python 3.7.1 in a virtual environment. You can easily install this module via the following command: pip install snownlp Once it is completed, you will be able to the the output that indicates the version number. In case you have missed it, feel free to check it via the following command: pip list I am using version 0.12.3 for this tutorial. Once you have finished, proceed to the next section. Let’s explore a little more on the basic API calls that can be used to pre-process the input text. You have to import it and do the initialization via the SnowNLP class as follow: You initialize it with your input text as parameter. It is recommended to prefix with a u to indicate that this is an Unicode string. This syntax has been in used since Python 2.0 but was later removed in version 3.0 to 3.2. From 3.3 onward, the u prefix is a valid syntax for Unicode string. Chinese is a unique language in a sense that there is no spacing between words unlike majority of the languages in the world. This makes it difficult to determine the number of words in a sentences as a word can be a combination of 1 or more Chinese characters. Hence, when performing any natural language processing, you need to split the whole chunk of text into words, a process known as Tokenization. You can easily use the following command to do the tokenization: You should get the following results as output: ['我', '喜欢', '看', '电影', '。'] Most of the time, we will be more interested in the part-of-speech tags which refer to the relationship with adjacent and related words in a sentence. If you have difficulty understand this, think of it as putting a tag to identify a word is a noun, adverb, verb, adjective or etc. Use the following code to get the tags of each word: The function tags returns a zip object which can be unzipped using the list function. You should get the following result: [('我', 'r'), ('喜欢', 'v'), ('看', 'v'), ('电影', 'n'), ('。', 'w')] Each of the words will be paired with the respective tags. Kindly refer the list below to know more about the meaning of certain tags (this is not a complete list as I could not find any documentation on it in the official site): r: refers to pronoun, word that replaces a noun in a sentence. v: refers to verb, a word used to describe an action, state, or occurrence. n: refers to noun, a word used to identify any of a class of people, places, or things. w: refers to punctuation, a symbol used in writing to separate sentences and their elements and to clarify meaning There is also a function to get the pinyin of each character. However, tones are not included in the pinyin. Example of getting the pinyin is as follow: You should get the following output: ['wo', 'xi', 'huan', 'kan', 'dian', 'ying', '。'] As I have mentioned earlier, this module are meant for Simplified Chinese. If you would like to process Traditional Chinese, kindly use the following code to convert the text to Simplified Chinese: You should get the following output” '这家伙是坏人。' Up until now, the input text consists of just one sentence. If you are using a paragraph as input, you should split it into chunk of sentences before running any API call. To do that, type the following command: Check if you get the following output: ['在茂密的大森林里', '一只饥饿的老虎逮住了一只狐狸', '老虎张开大嘴就要把狐狸吃掉', '“慢着”', '狐狸虽然很害怕但还是装出一副很神气的样子说', '“你知道我是谁吗', '我可是玉皇大帝派来管理百兽的兽王', '你要是吃了我', '玉皇大帝是决不会放过你的”'] There is also an option to identify keywords from the sentences. You can pass an integer parameter indicating the number of keywords to get from the input. I personally tested it to extract 5 keywords and it works great for news article and short stories. Type the following command: The extracted keywords are as follow: ['狐狸', '大', '老虎', '大帝', '皇'] If keywords aren’t what you are looking for, you can try to use the summary to extract synopsis(important sentences) from it. The module will split the text into sentences and extract what it feels are the most important sentences. Similar to keywords, it accepts an integer as parameter that determine the number of summary. If the sentences in your text is less than the input, it will output the whole text as summary. Use the following command: You should get the following output: ['老虎张开大嘴就要把狐狸吃掉', '我可是玉皇大帝派来管理百兽的兽王', '玉皇大帝是决不会放过你的”', '一只饥饿的老虎逮住了一只狐狸', '你要是吃了我'] The focus of this tutorial is on sentiment analysis. However, most of the time, you need to do text pre-processing in order to reduce the input text for better accuracy. Hence, you can use the other API calls mentioned above. Let’s test it with some sample text: Check if you get the following results (the comments are not part of the output, they are added for easier viewing): 0.7853504415636449 #这个产品很好用0.5098208142944668 #这个产品不好用0.13082804652201174 #这个产品是垃圾0.5 #这个也太贵了吧0.0954842128485538 #超级垃圾0.04125325276132508 #是个垃圾中的垃圾 The value output range from 0 to 1 with 0 represent negative sentiment while 1 represent positive sentiment. As you can see, the results are not that bad consider the fact that most of the results are on point except for the 0.5 value which should be a negative sentiment. Please be noted that the sentiment is trained on comments made when purchasing a product. If you are testing it on other domain, the results will be really bad. You can check the following files to find out more on the training data used: snownlp-master/snownlp/sentiment/neg.txtsnownlp-master/snownlp/sentiment/pos.txt snownlp-master/snownlp/sentiment/neg.txt snownlp-master/snownlp/sentiment/pos.txt You will notice that the word 贵 appeared about 600+ times in both neg.txt and pos.txt. This is the reason why the module output a neutral 0.5 value for the sentiment. In contrast, the word 垃圾 appeared 200+ times in neg.txt and only 35 times in pos.txt. To solve this issue, we can train our own model using custom text dataset. It will be explained in the next section. Prepare your own dataset by collecting the positive and negative sample sentences in two text folders. I created them in the snownlp-master folder and named them as custom_pos.txt and custom_neg.txt. Each example sentences is separated in a newline as follows: 今天明明是周六,我就不想工作,你看他,好意思吗?一直在偷懒... Once you have your dataset ready, let run the following code (change the name accordingly): You should get an output file called custom_sentiment.marshal.3 in the snownlp-master folder. Do not be surprise by the .3 extension at the end of the file. To use the output model, you can do one of the following: Modify the code in snownlp-master/snownlp/sentiment/__init__.py. Change the data path to the directory of the newly output marshal.3 file.Go to snownlp-master/snownlp/sentiment folder. Create a new folder called backup and place both sentiment.marshal and sentiment.marshal.3 to the backup folder. Copy custom_sentiment.marshal.3 from snownlp-master folder and place it into snownlp-master/snownlp/sentiment folder. Rename it to sentiment.marshal.3. Modify the code in snownlp-master/snownlp/sentiment/__init__.py. Change the data path to the directory of the newly output marshal.3 file. Go to snownlp-master/snownlp/sentiment folder. Create a new folder called backup and place both sentiment.marshal and sentiment.marshal.3 to the backup folder. Copy custom_sentiment.marshal.3 from snownlp-master folder and place it into snownlp-master/snownlp/sentiment folder. Rename it to sentiment.marshal.3. Personally, I prefer the second method as modifying code can be risky at times. Kindly note that you only need the .3 file. You can test the result by re-initialize the SnowNLP module and run the following code (replace the text with something that similar to your training data): There will be some differences in the output results based of your training data. Apart from sentiment, you can train segmentation and tags as well. Refer to the following code to do the training for segmentation: We will be using the following code for tags: This article demonstrated a simple and effective way to use a Python module called SnowNLP for sentiment analysis for Simplified Chinese. At the time of this writing, the official documentation still lacks in quality in explaining certain functionality. Feel free to read the code and explore it to get a better understanding on the techniques used by the developer. There are a lot other modules available for natural language processing and each one of them have their own advantages and disadvantages. Kindly evaluate them according to your use cases and make use of it in your projects. Thanks and have a good day ahead!
[ { "code": null, "e": 493, "s": 172, "text": "By reading this article, you will be exposed to a technique for analyzing the sentiments of any text in Simplified Chinese. This tutorial will be based on Simplified Chinese but it can be used on Traditional Chinese as well due to the fact that SnowNLP is capable of converting Traditional Chinese to Simplified Chinese." }, { "code": null, "e": 536, "s": 493, "text": "There will be 4 sections in this tutorial:" }, { "code": null, "e": 601, "s": 536, "text": "Setup and installationUsage and API callTraining modelConclusion" }, { "code": null, "e": 624, "s": 601, "text": "Setup and installation" }, { "code": null, "e": 643, "s": 624, "text": "Usage and API call" }, { "code": null, "e": 658, "s": 643, "text": "Training model" }, { "code": null, "e": 669, "s": 658, "text": "Conclusion" }, { "code": null, "e": 1006, "s": 669, "text": "In this tutorial, I will be installing the modules required via pip on Windows operating system. Let’s start by getting the files from an open-source modules called SnowNLP which is a Simplified Chinese Text Processing module. Although this module has not been updated for quite some time, the results is good enough for most use cases." }, { "code": null, "e": 1226, "s": 1006, "text": "Go to the following link and download the required files. Once it is completed, extract the zipped files to a directory of your preference. You should have a snownlp-master folder which contains all the necessary files." }, { "code": null, "e": 1364, "s": 1226, "text": "SnowNLP supports Python 3 as stated in the official Github Link. In this tutorial, I will be using Python 3.7.1 in a virtual environment." }, { "code": null, "e": 1426, "s": 1364, "text": "You can easily install this module via the following command:" }, { "code": null, "e": 1446, "s": 1426, "text": "pip install snownlp" }, { "code": null, "e": 1615, "s": 1446, "text": "Once it is completed, you will be able to the the output that indicates the version number. In case you have missed it, feel free to check it via the following command:" }, { "code": null, "e": 1624, "s": 1615, "text": "pip list" }, { "code": null, "e": 1722, "s": 1624, "text": "I am using version 0.12.3 for this tutorial. Once you have finished, proceed to the next section." }, { "code": null, "e": 1821, "s": 1722, "text": "Let’s explore a little more on the basic API calls that can be used to pre-process the input text." }, { "code": null, "e": 1902, "s": 1821, "text": "You have to import it and do the initialization via the SnowNLP class as follow:" }, { "code": null, "e": 2195, "s": 1902, "text": "You initialize it with your input text as parameter. It is recommended to prefix with a u to indicate that this is an Unicode string. This syntax has been in used since Python 2.0 but was later removed in version 3.0 to 3.2. From 3.3 onward, the u prefix is a valid syntax for Unicode string." }, { "code": null, "e": 2665, "s": 2195, "text": "Chinese is a unique language in a sense that there is no spacing between words unlike majority of the languages in the world. This makes it difficult to determine the number of words in a sentences as a word can be a combination of 1 or more Chinese characters. Hence, when performing any natural language processing, you need to split the whole chunk of text into words, a process known as Tokenization. You can easily use the following command to do the tokenization:" }, { "code": null, "e": 2713, "s": 2665, "text": "You should get the following results as output:" }, { "code": null, "e": 2741, "s": 2713, "text": "['我', '喜欢', '看', '电影', '。']" }, { "code": null, "e": 3076, "s": 2741, "text": "Most of the time, we will be more interested in the part-of-speech tags which refer to the relationship with adjacent and related words in a sentence. If you have difficulty understand this, think of it as putting a tag to identify a word is a noun, adverb, verb, adjective or etc. Use the following code to get the tags of each word:" }, { "code": null, "e": 3199, "s": 3076, "text": "The function tags returns a zip object which can be unzipped using the list function. You should get the following result:" }, { "code": null, "e": 3262, "s": 3199, "text": "[('我', 'r'), ('喜欢', 'v'), ('看', 'v'), ('电影', 'n'), ('。', 'w')]" }, { "code": null, "e": 3492, "s": 3262, "text": "Each of the words will be paired with the respective tags. Kindly refer the list below to know more about the meaning of certain tags (this is not a complete list as I could not find any documentation on it in the official site):" }, { "code": null, "e": 3555, "s": 3492, "text": "r: refers to pronoun, word that replaces a noun in a sentence." }, { "code": null, "e": 3631, "s": 3555, "text": "v: refers to verb, a word used to describe an action, state, or occurrence." }, { "code": null, "e": 3719, "s": 3631, "text": "n: refers to noun, a word used to identify any of a class of people, places, or things." }, { "code": null, "e": 3834, "s": 3719, "text": "w: refers to punctuation, a symbol used in writing to separate sentences and their elements and to clarify meaning" }, { "code": null, "e": 3987, "s": 3834, "text": "There is also a function to get the pinyin of each character. However, tones are not included in the pinyin. Example of getting the pinyin is as follow:" }, { "code": null, "e": 4024, "s": 3987, "text": "You should get the following output:" }, { "code": null, "e": 4073, "s": 4024, "text": "['wo', 'xi', 'huan', 'kan', 'dian', 'ying', '。']" }, { "code": null, "e": 4271, "s": 4073, "text": "As I have mentioned earlier, this module are meant for Simplified Chinese. If you would like to process Traditional Chinese, kindly use the following code to convert the text to Simplified Chinese:" }, { "code": null, "e": 4308, "s": 4271, "text": "You should get the following output”" }, { "code": null, "e": 4318, "s": 4308, "text": "'这家伙是坏人。'" }, { "code": null, "e": 4530, "s": 4318, "text": "Up until now, the input text consists of just one sentence. If you are using a paragraph as input, you should split it into chunk of sentences before running any API call. To do that, type the following command:" }, { "code": null, "e": 4569, "s": 4530, "text": "Check if you get the following output:" }, { "code": null, "e": 4709, "s": 4569, "text": "['在茂密的大森林里', '一只饥饿的老虎逮住了一只狐狸', '老虎张开大嘴就要把狐狸吃掉', '“慢着”', '狐狸虽然很害怕但还是装出一副很神气的样子说', '“你知道我是谁吗', '我可是玉皇大帝派来管理百兽的兽王', '你要是吃了我', '玉皇大帝是决不会放过你的”']" }, { "code": null, "e": 4993, "s": 4709, "text": "There is also an option to identify keywords from the sentences. You can pass an integer parameter indicating the number of keywords to get from the input. I personally tested it to extract 5 keywords and it works great for news article and short stories. Type the following command:" }, { "code": null, "e": 5031, "s": 4993, "text": "The extracted keywords are as follow:" }, { "code": null, "e": 5060, "s": 5031, "text": "['狐狸', '大', '老虎', '大帝', '皇']" }, { "code": null, "e": 5509, "s": 5060, "text": "If keywords aren’t what you are looking for, you can try to use the summary to extract synopsis(important sentences) from it. The module will split the text into sentences and extract what it feels are the most important sentences. Similar to keywords, it accepts an integer as parameter that determine the number of summary. If the sentences in your text is less than the input, it will output the whole text as summary. Use the following command:" }, { "code": null, "e": 5546, "s": 5509, "text": "You should get the following output:" }, { "code": null, "e": 5629, "s": 5546, "text": "['老虎张开大嘴就要把狐狸吃掉', '我可是玉皇大帝派来管理百兽的兽王', '玉皇大帝是决不会放过你的”', '一只饥饿的老虎逮住了一只狐狸', '你要是吃了我']" }, { "code": null, "e": 5892, "s": 5629, "text": "The focus of this tutorial is on sentiment analysis. However, most of the time, you need to do text pre-processing in order to reduce the input text for better accuracy. Hence, you can use the other API calls mentioned above. Let’s test it with some sample text:" }, { "code": null, "e": 6009, "s": 5892, "text": "Check if you get the following results (the comments are not part of the output, they are added for easier viewing):" }, { "code": null, "e": 6157, "s": 6009, "text": "0.7853504415636449 #这个产品很好用0.5098208142944668 #这个产品不好用0.13082804652201174 #这个产品是垃圾0.5 #这个也太贵了吧0.0954842128485538 #超级垃圾0.04125325276132508 #是个垃圾中的垃圾" }, { "code": null, "e": 6669, "s": 6157, "text": "The value output range from 0 to 1 with 0 represent negative sentiment while 1 represent positive sentiment. As you can see, the results are not that bad consider the fact that most of the results are on point except for the 0.5 value which should be a negative sentiment. Please be noted that the sentiment is trained on comments made when purchasing a product. If you are testing it on other domain, the results will be really bad. You can check the following files to find out more on the training data used:" }, { "code": null, "e": 6750, "s": 6669, "text": "snownlp-master/snownlp/sentiment/neg.txtsnownlp-master/snownlp/sentiment/pos.txt" }, { "code": null, "e": 6791, "s": 6750, "text": "snownlp-master/snownlp/sentiment/neg.txt" }, { "code": null, "e": 6832, "s": 6791, "text": "snownlp-master/snownlp/sentiment/pos.txt" }, { "code": null, "e": 7202, "s": 6832, "text": "You will notice that the word 贵 appeared about 600+ times in both neg.txt and pos.txt. This is the reason why the module output a neutral 0.5 value for the sentiment. In contrast, the word 垃圾 appeared 200+ times in neg.txt and only 35 times in pos.txt. To solve this issue, we can train our own model using custom text dataset. It will be explained in the next section." }, { "code": null, "e": 7463, "s": 7202, "text": "Prepare your own dataset by collecting the positive and negative sample sentences in two text folders. I created them in the snownlp-master folder and named them as custom_pos.txt and custom_neg.txt. Each example sentences is separated in a newline as follows:" }, { "code": null, "e": 7496, "s": 7463, "text": "今天明明是周六,我就不想工作,你看他,好意思吗?一直在偷懒..." }, { "code": null, "e": 7588, "s": 7496, "text": "Once you have your dataset ready, let run the following code (change the name accordingly):" }, { "code": null, "e": 7803, "s": 7588, "text": "You should get an output file called custom_sentiment.marshal.3 in the snownlp-master folder. Do not be surprise by the .3 extension at the end of the file. To use the output model, you can do one of the following:" }, { "code": null, "e": 8253, "s": 7803, "text": "Modify the code in snownlp-master/snownlp/sentiment/__init__.py. Change the data path to the directory of the newly output marshal.3 file.Go to snownlp-master/snownlp/sentiment folder. Create a new folder called backup and place both sentiment.marshal and sentiment.marshal.3 to the backup folder. Copy custom_sentiment.marshal.3 from snownlp-master folder and place it into snownlp-master/snownlp/sentiment folder. Rename it to sentiment.marshal.3." }, { "code": null, "e": 8392, "s": 8253, "text": "Modify the code in snownlp-master/snownlp/sentiment/__init__.py. Change the data path to the directory of the newly output marshal.3 file." }, { "code": null, "e": 8704, "s": 8392, "text": "Go to snownlp-master/snownlp/sentiment folder. Create a new folder called backup and place both sentiment.marshal and sentiment.marshal.3 to the backup folder. Copy custom_sentiment.marshal.3 from snownlp-master folder and place it into snownlp-master/snownlp/sentiment folder. Rename it to sentiment.marshal.3." }, { "code": null, "e": 8985, "s": 8704, "text": "Personally, I prefer the second method as modifying code can be risky at times. Kindly note that you only need the .3 file. You can test the result by re-initialize the SnowNLP module and run the following code (replace the text with something that similar to your training data):" }, { "code": null, "e": 9067, "s": 8985, "text": "There will be some differences in the output results based of your training data." }, { "code": null, "e": 9199, "s": 9067, "text": "Apart from sentiment, you can train segmentation and tags as well. Refer to the following code to do the training for segmentation:" }, { "code": null, "e": 9245, "s": 9199, "text": "We will be using the following code for tags:" } ]
How to Find the List of Daemon Processes and Zombie Processes in Linux
This article will guide you to understand the Zombie process and Daemons, and also help us to find the process which is running in the background. When a process ends the execution, then it will have an exit status to report to its master process. Because of that little bit of information, the process will remain in the OS process table as a zombie process, which indicates that it is not to be scheduled for future, but this process cannot be completely removed or the process ID will not be used until the exit has been determined and no longer needed. When a child completes the process, the master process will receive a SIGCHLD signal to indicate that one of its child process has finished the executing; the parent process will typically call the wait() system status at this point. That status will provide the parent with the child’s process exit status, and will cause the child process to be reaped, or removed from the process table. Linux is a multi-tasking operating system. Each program running at any time is called a process. Every running command starts with at least one new process and there are many numbers of system processes that are running. Each process is identified by a number called Process ID (PID). Similar to files, each process has its owner and group, and the group and owner permissions are useful to identify which files and devices are related to those processes. Most processes also have their own parent process that started them. Example: The shell is a process, and any command executed in the shell is a process which belongs to the shell parent process. The exception is a special process called init(8) which is the first process to start at booting time and which has a PID(Process ID) of 1. Some programs are to be run with continuous user input and disconnected from the terminal. For example, a web server responds to web requests, instead of user input. Mail servers are another examples of this type application. These type of programs are also known as daemons. Every process has to start running in the foreground. It gets its input from the keyboard and sends its output to the screen after the process. You can see this happen with the ls command. If I want to list all the files in my current directory, I can use the following command – This will show all the files in the current directory. # ls lost+found user1 user2 The process runs in the foreground and will direct the output to my screen, and if a command wants any input it waits for input. While a program is running in foreground and taking so much time, we cannot run any other commands from the command prompt which can be available until the program finishes its processing. A background process runs without being the interaction of users. If the background process requires any input, it waits. The advantage of running a process in the background is that you can run other commands, and you are not supposed to wait until it completes to start another process. The simplest way to start the background process is to add an ampersand (&) at the end of the command we execute. # find . / > files The above will write the output to files file with all the files and directories which will take more time. So, for instance, ampersand (&) at the end of the line will run in the background as a process and the cursor will come to prompt waiting for another command. # find ./ > files & [1] 76742 # The first line contains information about the background process about how many background process are running and the job number or process ID. We need to know the PID to manipulate it between background and foreground. If you press the Enter now, we can see the following output [1]+ Done find . / > files The first line tells you that the find command background process finishes successfully and waits for the other command. This command will list the own processes by running, the ps (process status) command. # ps PID TTY TIME CMD 69301 pts/0 00:00:00 bash 78926 pts/0 00:00:00 ps The commonly used flags for ps is the -f, -f will display full information, which provides more information as shown below. # ps -f UID PID PPID C STIME TTY TIME CMD root 69301 69261 0 13:34 pts/0 00:00:00 -bash root 79099 69301 0 13:51 pts/0 00:00:00 ps -f # ps --help ********* simple selection ********* ********* selection by list ********* -A all processes -C by command name -N negate selection -G by real group ID (supports names) -a all w/ tty except session leaders -U by real user ID (supports names) -d all except session leaders -g by session OR by effective group name -e all processes -p by process ID -q by process ID (unsorted & quick) T all processes on this terminal -s processes in the sessions given a all w/ tty, including other users -t by tty g OBSOLETE -- DO NOT USE -u by effective user ID (supports names) r only running processes U processes for specified users x processes w/o controlling ttys t by tty *********** output format ********** *********** long options *********** -o,o user-defined -f full --Group --User --pid --cols --ppid -j,j job control s signal --group --user --sid --rows --info -O,O preloaded -o v virtual memory --cumulative --format --deselect -l,l long u user-oriented --sort --tty --forest --version -F extra full X registers --heading --no-heading --context --quick-pid ********* misc options ********* -V,V show version L list format codes f ASCII art forest -m,m,-L,-T,H threads S children in sum -y change -l format -M,Z security data c true command name -c scheduling class -w,w wide output n numeric WCHAN,UID -H process hierarchy A process can be stopped in several ways. Often, from a command line, by sending a CTRL + C keystroke – will exit the command. This works when the process is running in the foreground. If a process is running in background mode, then first you would need to get its Job ID using the ps command and after that you can use kill command to kill the process as follows – # ps -f UID PID PPID C STIME TTY TIME CMD root 69301 69261 0 13:34 pts/0 00:00:00 -bash root 82913 69301 0 13:58 pts/0 00:00:00 ssh [email protected] root 82952 69301 0 13:58 pts/0 00:00:00 ps -f # kill 82913 Terminated Here kill command would terminate ssh [email protected]. If a process ignores a regular kill, we can use kill -9 followed by the process ID as follows. # ps -f UID PID PPID C STIME TTY TIME CMD root 69301 69261 0 13:34 pts/0 00:00:00 -bash root 83964 69301 0 14:00 pts/0 00:00:00 ps -f [1]+ Killed ssh [email protected] How can we see if there are zombie processes running on a system. Run “ps aux” and look for a Z in the STAT column. # ps -aux Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 11647 0.0 0.1 549100 7348 ? S Mar18 0:13 /usr/libexec/clock-applet --oaf-activate-iid=OAFIID:GNOME_ClockApplet_Factory --oaf-ior-fd=28 root 11648 0.0 0.1 400744 5552 ? S Mar18 0:00 /usr/libexec/gdm-user-switch-applet --oaf-activate-iid=OAFIID:GNOME_FastUserSwitchApplet_Factry --oaf-ior-fd=34 root 11649 0.0 0.1 290996 4072 ? S Mar18 0:00 /usr/libexec/notification-area-applet --oaf-activate-iid=OAFIID:GNOME_NotificationAreaApplet_Factory --oaf-ior-fd=40 root 11681 0.0 0.0 137416 1524 ? S Mar18 0:00 /usr/libexec/gvfsd-burn --spawner :1.9 /org/gtk/gvfs/exec_spaw/ root 11696 0.0 0.0 135276 1320 ? S Mar18 0:00 /usr/libexec/gvfsd-metadata root 12196 0.0 0.0 0 0 ? Z Mar18 0:20 [yumBackend.py] <defunct root 13284 0.0 0.1 303428 6212 ? Sl Mar18 0:00 gnome-terminal root 13286 0.0 0.0 8228 620 ? S Mar18 0:00 gnome-pty-helpe root 13287 0.0 0.0 108340 1340 pts/0 Ss+ Mar18 0:00 bas root 14347 0.0 0.0 223336 3408 ? S 10:50 0:00 smbd -D root 14578 0.0 0.4 425524 18172 ? Ss Mar25 0:21 /usr/sbin/http apache 15091 0.0 1.5 414648 61904 ? S Apr05 0:44 php-fpm: pool ww postfix 18359 0.0 0.0 80948 3384 ? S 12:24 0:00 pickup -l -t fifo -u In the above example, the process with process ID 12196 is having status z, use the kill command to kill that process #kill -9 12196 After this article you are able to understand what is zombie process and daemons and how to find out it and how to stop it, also how to make a process in background.
[ { "code": null, "e": 1209, "s": 1062, "text": "This article will guide you to understand the Zombie process and Daemons, and also help us to find the process which is running in the background." }, { "code": null, "e": 1619, "s": 1209, "text": "When a process ends the execution, then it will have an exit status to report to its master process. Because of that little bit of information, the process will remain in the OS process table as a zombie process, which indicates that it is not to be scheduled for future, but this process cannot be completely removed or the process ID will not be used until the exit has been determined and no longer needed." }, { "code": null, "e": 2009, "s": 1619, "text": "When a child completes the process, the master process will receive a SIGCHLD signal to indicate that one of its child process has finished the executing; the parent process will typically call the wait() system status at this point. That status will provide the parent with the child’s process exit status, and will cause the child process to be reaped, or removed from the process table." }, { "code": null, "e": 2230, "s": 2009, "text": "Linux is a multi-tasking operating system. Each program running at any time is called a process. Every running command starts with at least one new process and there are many numbers of system processes that are running." }, { "code": null, "e": 2534, "s": 2230, "text": "Each process is identified by a number called Process ID (PID). Similar to files, each process has its owner and group, and the group and owner permissions are useful to identify which files and devices are related to those processes. Most processes also have their own parent process that started them." }, { "code": null, "e": 2801, "s": 2534, "text": "Example: The shell is a process, and any command executed in the shell is a process which belongs to the shell parent process. The exception is a special process called init(8) which is the first process to start at booting time and which has a PID(Process ID) of 1." }, { "code": null, "e": 3077, "s": 2801, "text": "Some programs are to be run with continuous user input and disconnected from the terminal. For example, a web server responds to web requests, instead of user input. Mail servers are another examples of this type application. These type of programs are also known as daemons." }, { "code": null, "e": 3221, "s": 3077, "text": "Every process has to start running in the foreground. It gets its input from the keyboard and sends its output to the screen after the process." }, { "code": null, "e": 3357, "s": 3221, "text": "You can see this happen with the ls command. If I want to list all the files in my current directory, I can use the following command –" }, { "code": null, "e": 3412, "s": 3357, "text": "This will show all the files in the current directory." }, { "code": null, "e": 3440, "s": 3412, "text": "# ls\nlost+found user1 user2" }, { "code": null, "e": 3569, "s": 3440, "text": "The process runs in the foreground and will direct the output to my screen, and if a command wants any input it waits for input." }, { "code": null, "e": 3758, "s": 3569, "text": "While a program is running in foreground and taking so much time, we cannot run any other commands from the command prompt which can be available until the program finishes its processing." }, { "code": null, "e": 3880, "s": 3758, "text": "A background process runs without being the interaction of users. If the background process requires any input, it waits." }, { "code": null, "e": 4047, "s": 3880, "text": "The advantage of running a process in the background is that you can run other commands, and you are not supposed to wait until it completes to start another process." }, { "code": null, "e": 4161, "s": 4047, "text": "The simplest way to start the background process is to add an ampersand (&) at the end of the command we execute." }, { "code": null, "e": 4180, "s": 4161, "text": "# find . / > files" }, { "code": null, "e": 4447, "s": 4180, "text": "The above will write the output to files file with all the files and directories which will take more time. So, for instance, ampersand (&) at the end of the line will run in the background as a process and the cursor will come to prompt waiting for another command." }, { "code": null, "e": 4479, "s": 4447, "text": "# find ./ > files &\n[1] 76742\n#" }, { "code": null, "e": 4700, "s": 4479, "text": "The first line contains information about the background process about how many background process are running and the job number or process ID. We need to know the PID to manipulate it between background and foreground." }, { "code": null, "e": 4760, "s": 4700, "text": "If you press the Enter now, we can see the following output" }, { "code": null, "e": 4787, "s": 4760, "text": "[1]+ Done find . / > files" }, { "code": null, "e": 4908, "s": 4787, "text": "The first line tells you that the find command background process finishes successfully and waits for the other command." }, { "code": null, "e": 4994, "s": 4908, "text": "This command will list the own processes by running, the ps (process status) command." }, { "code": null, "e": 5083, "s": 4994, "text": "# ps\nPID TTY TIME CMD\n69301 pts/0 00:00:00 bash\n78926 pts/0 00:00:00 ps" }, { "code": null, "e": 5207, "s": 5083, "text": "The commonly used flags for ps is the -f, -f will display full information, which provides more information as shown below." }, { "code": null, "e": 5383, "s": 5207, "text": "# ps -f\nUID PID PPID C STIME TTY TIME CMD\nroot 69301 69261 0 13:34 pts/0 00:00:00 -bash\nroot 79099 69301 0 13:51 pts/0 00:00:00 ps -f" }, { "code": null, "e": 7070, "s": 5383, "text": "# ps --help\n********* simple selection ********* ********* selection by list *********\n-A all processes -C by command name\n-N negate selection -G by real group ID (supports names)\n-a all w/ tty except session leaders -U by real user ID (supports names)\n-d all except session leaders -g by session OR by effective group name\n-e all processes -p by process ID\n -q by process ID (unsorted & quick)\nT all processes on this terminal -s processes in the sessions given\na all w/ tty, including other users -t by tty\ng OBSOLETE -- DO NOT USE -u by effective user ID (supports names)\nr only running processes U processes for specified users\nx processes w/o controlling ttys t by tty\n*********** output format ********** *********** long options ***********\n-o,o user-defined -f full --Group --User --pid --cols --ppid\n-j,j job control s signal --group --user --sid --rows --info\n-O,O preloaded -o v virtual memory --cumulative --format --deselect\n-l,l long u user-oriented --sort --tty --forest --version\n-F extra full X registers --heading --no-heading --context\n --quick-pid\n********* misc options *********\n-V,V show version L list format codes f ASCII art forest\n-m,m,-L,-T,H threads S children in sum -y change -l format\n-M,Z security data c true command name -c scheduling class\n-w,w wide output n numeric WCHAN,UID -H process hierarchy\n\n" }, { "code": null, "e": 7255, "s": 7070, "text": "A process can be stopped in several ways. Often, from a command line, by sending a CTRL + C keystroke – will exit the command. This works when the process is running in the foreground." }, { "code": null, "e": 7437, "s": 7255, "text": "If a process is running in background mode, then first you would need to get its Job ID using the ps command and after that you can use kill command to kill the process as follows –" }, { "code": null, "e": 7709, "s": 7437, "text": "# ps -f\nUID PID PPID C STIME TTY TIME CMD\nroot 69301 69261 0 13:34 pts/0 00:00:00 -bash\nroot 82913 69301 0 13:58 pts/0 00:00:00 ssh [email protected]\nroot 82952 69301 0 13:58 pts/0 00:00:00 ps -f\n\n# kill 82913\nTerminated" }, { "code": null, "e": 7861, "s": 7709, "text": "Here kill command would terminate ssh [email protected]. If a process ignores a regular kill, we can use kill -9 followed by the process ID as follows." }, { "code": null, "e": 8081, "s": 7861, "text": "# ps -f\nUID PID PPID C STIME TTY TIME CMD\nroot 69301 69261 0 13:34 pts/0 00:00:00 -bash\nroot 83964 69301 0 14:00 pts/0 00:00:00 ps -f\n[1]+ Killed ssh [email protected]" }, { "code": null, "e": 8147, "s": 8081, "text": "How can we see if there are zombie processes running on a system." }, { "code": null, "e": 8197, "s": 8147, "text": "Run “ps aux” and look for a Z in the STAT column." }, { "code": null, "e": 9510, "s": 8197, "text": "# ps -aux\nWarning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ\nUSER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND\nroot 11647 0.0 0.1 549100 7348 ? S Mar18 0:13 /usr/libexec/clock-applet --oaf-activate-iid=OAFIID:GNOME_ClockApplet_Factory --oaf-ior-fd=28\nroot 11648 0.0 0.1 400744 5552 ? S Mar18 0:00 /usr/libexec/gdm-user-switch-applet --oaf-activate-iid=OAFIID:GNOME_FastUserSwitchApplet_Factry --oaf-ior-fd=34\nroot 11649 0.0 0.1 290996 4072 ? S Mar18 0:00 /usr/libexec/notification-area-applet --oaf-activate-iid=OAFIID:GNOME_NotificationAreaApplet_Factory --oaf-ior-fd=40\nroot 11681 0.0 0.0 137416 1524 ? S Mar18 0:00 /usr/libexec/gvfsd-burn --spawner :1.9 /org/gtk/gvfs/exec_spaw/\nroot 11696 0.0 0.0 135276 1320 ? S Mar18 0:00 /usr/libexec/gvfsd-metadata\nroot 12196 0.0 0.0 0 0 ? Z Mar18 0:20 [yumBackend.py] <defunct\nroot 13284 0.0 0.1 303428 6212 ? Sl Mar18 0:00 gnome-terminal\nroot 13286 0.0 0.0 8228 620 ? S Mar18 0:00 gnome-pty-helpe\nroot 13287 0.0 0.0 108340 1340 pts/0 Ss+ Mar18 0:00 bas\nroot 14347 0.0 0.0 223336 3408 ? S 10:50 0:00 smbd -D\nroot 14578 0.0 0.4 425524 18172 ? Ss Mar25 0:21 /usr/sbin/http\napache 15091 0.0 1.5 414648 61904 ? S Apr05 0:44 php-fpm: pool ww\npostfix 18359 0.0 0.0 80948 3384 ? S 12:24 0:00 pickup -l -t fifo -u" }, { "code": null, "e": 9628, "s": 9510, "text": "In the above example, the process with process ID 12196 is having status z, use the kill command to kill that process" }, { "code": null, "e": 9643, "s": 9628, "text": "#kill -9 12196" }, { "code": null, "e": 9809, "s": 9643, "text": "After this article you are able to understand what is zombie process and daemons and how to find out it and how to stop it, also how to make a process in background." } ]
Gradle - Build a Groovy Project
This chapter explains how to compile and execute a Groovy project using build.gradle file. The Groovy plug-in for Gradle extends the Java plug-in and provides tasks for Groovy programs. You can use the following line for applying groovy plugin. apply plugin: 'groovy' Copy the following code into build.gradle file. The complete build script file is as follows − apply plugin: 'groovy' repositories { mavenCentral() } dependencies { compile 'org.codehaus.groovy:groovy-all:2.4.5' testCompile 'junit:junit:4.12' } You can use the following command to execute the build script − gradle build The Groovy plugin assumes a certain setup of your Groovy project. src/main/groovy contains the Groovy source code src/test/groovy contains the Groovy tests src/main/java contains the Java source code src/test/java contains the Java tests Check the respective directory where build.gradle file places for build folder. Print Add Notes Bookmark this page
[ { "code": null, "e": 1973, "s": 1882, "text": "This chapter explains how to compile and execute a Groovy project using build.gradle file." }, { "code": null, "e": 2127, "s": 1973, "text": "The Groovy plug-in for Gradle extends the Java plug-in and provides tasks for Groovy programs. You can use the following line for applying groovy plugin." }, { "code": null, "e": 2151, "s": 2127, "text": "apply plugin: 'groovy'\n" }, { "code": null, "e": 2246, "s": 2151, "text": "Copy the following code into build.gradle file. The complete build script file is as follows −" }, { "code": null, "e": 2407, "s": 2246, "text": "apply plugin: 'groovy'\n\nrepositories {\n mavenCentral()\n}\n\ndependencies {\n compile 'org.codehaus.groovy:groovy-all:2.4.5'\n testCompile 'junit:junit:4.12'\n}" }, { "code": null, "e": 2471, "s": 2407, "text": "You can use the following command to execute the build script −" }, { "code": null, "e": 2485, "s": 2471, "text": "gradle build\n" }, { "code": null, "e": 2551, "s": 2485, "text": "The Groovy plugin assumes a certain setup of your Groovy project." }, { "code": null, "e": 2599, "s": 2551, "text": "src/main/groovy contains the Groovy source code" }, { "code": null, "e": 2641, "s": 2599, "text": "src/test/groovy contains the Groovy tests" }, { "code": null, "e": 2685, "s": 2641, "text": "src/main/java contains the Java source code" }, { "code": null, "e": 2723, "s": 2685, "text": "src/test/java contains the Java tests" }, { "code": null, "e": 2803, "s": 2723, "text": "Check the respective directory where build.gradle file places for build folder." }, { "code": null, "e": 2810, "s": 2803, "text": " Print" }, { "code": null, "e": 2821, "s": 2810, "text": " Add Notes" } ]
Connecting Apache Hive To Microsoft Power BI | by Rahul Pathak | Towards Data Science
In this story of our blog post, we are mentioning the steps we took to perform the required connection. The Hive database was based on Cloudera & the Power BI Desktop was installed on Windows. The connection can also occur with other BI tools such as Tableau & etc. As Hive can be integrated with many BI tools but the process can be challenging. Let's look forward to taking the required steps for the connection. Initially, we need to download the ODBC drivers from the Cloudera community. There are two versions one is the 64 bit and the other is 32 bit version. It depends on the version of your PC/Laptop you are using. You may check the version of your PC by clicking the Windows button and the Pause/Break button. A Panel opens up showing the technical characteristics of your system. Then you may go ahead and install the Hive ODBC driver depending on your system. Also, the links for Power BI desktop download are given below! Power BI Desktop Download link HIVE ODBC DRIVER DOWNLOAD LINK Here, we started the Hive Thrift server by using the command hive --service hiveserver2 Type ifconfig to get the inet address that would be your host for your connection. ifconfig First Press Windows + R simultaneously and type in odbcad32. A window would show up. In the User DSN tab click on the Add button Click on Cloudera ODBC Driver for Apache Hive and click Finish A New Window would open up Type in your Desired Data Source Name (DSN). In this case its Hive_Connection.Description is optionalChoose Hive Server 2 as your Server TypeType in your Host Address which you obtained from the terminal in Cloudera using ifconfigPort is 10000The Database section is optionalChoose the mechanism as usernameThe username for this connection is ClouderaChoose SASL in Thrift TransportClick on TestCheck whether the test is successful. After successful completion click OK Type in your Desired Data Source Name (DSN). In this case its Hive_Connection. Description is optional Choose Hive Server 2 as your Server Type Type in your Host Address which you obtained from the terminal in Cloudera using ifconfig Port is 10000 The Database section is optional Choose the mechanism as username The username for this connection is Cloudera Choose SASL in Thrift Transport Click on Test Check whether the test is successful. After successful completion click OK Click on Get Data =>more In the search bar type ODBC and click connect Choose Cloudera Hive DSN and click OK The tables from your Hive Database will be visible in your Navigator column of Power BI Once connected we may visualize the data imported from the hive table to the Power BI. Thank you for reading this throughout. I hope we are able to help you connect these tools. Happy Learning 🤗.
[ { "code": null, "e": 587, "s": 172, "text": "In this story of our blog post, we are mentioning the steps we took to perform the required connection. The Hive database was based on Cloudera & the Power BI Desktop was installed on Windows. The connection can also occur with other BI tools such as Tableau & etc. As Hive can be integrated with many BI tools but the process can be challenging. Let's look forward to taking the required steps for the connection." }, { "code": null, "e": 1108, "s": 587, "text": "Initially, we need to download the ODBC drivers from the Cloudera community. There are two versions one is the 64 bit and the other is 32 bit version. It depends on the version of your PC/Laptop you are using. You may check the version of your PC by clicking the Windows button and the Pause/Break button. A Panel opens up showing the technical characteristics of your system. Then you may go ahead and install the Hive ODBC driver depending on your system. Also, the links for Power BI desktop download are given below!" }, { "code": null, "e": 1139, "s": 1108, "text": "Power BI Desktop Download link" }, { "code": null, "e": 1170, "s": 1139, "text": "HIVE ODBC DRIVER DOWNLOAD LINK" }, { "code": null, "e": 1231, "s": 1170, "text": "Here, we started the Hive Thrift server by using the command" }, { "code": null, "e": 1258, "s": 1231, "text": "hive --service hiveserver2" }, { "code": null, "e": 1341, "s": 1258, "text": "Type ifconfig to get the inet address that would be your host for your connection." }, { "code": null, "e": 1350, "s": 1341, "text": "ifconfig" }, { "code": null, "e": 1435, "s": 1350, "text": "First Press Windows + R simultaneously and type in odbcad32. A window would show up." }, { "code": null, "e": 1479, "s": 1435, "text": "In the User DSN tab click on the Add button" }, { "code": null, "e": 1542, "s": 1479, "text": "Click on Cloudera ODBC Driver for Apache Hive and click Finish" }, { "code": null, "e": 1569, "s": 1542, "text": "A New Window would open up" }, { "code": null, "e": 2039, "s": 1569, "text": "Type in your Desired Data Source Name (DSN). In this case its Hive_Connection.Description is optionalChoose Hive Server 2 as your Server TypeType in your Host Address which you obtained from the terminal in Cloudera using ifconfigPort is 10000The Database section is optionalChoose the mechanism as usernameThe username for this connection is ClouderaChoose SASL in Thrift TransportClick on TestCheck whether the test is successful. After successful completion click OK" }, { "code": null, "e": 2118, "s": 2039, "text": "Type in your Desired Data Source Name (DSN). In this case its Hive_Connection." }, { "code": null, "e": 2142, "s": 2118, "text": "Description is optional" }, { "code": null, "e": 2183, "s": 2142, "text": "Choose Hive Server 2 as your Server Type" }, { "code": null, "e": 2273, "s": 2183, "text": "Type in your Host Address which you obtained from the terminal in Cloudera using ifconfig" }, { "code": null, "e": 2287, "s": 2273, "text": "Port is 10000" }, { "code": null, "e": 2320, "s": 2287, "text": "The Database section is optional" }, { "code": null, "e": 2353, "s": 2320, "text": "Choose the mechanism as username" }, { "code": null, "e": 2398, "s": 2353, "text": "The username for this connection is Cloudera" }, { "code": null, "e": 2430, "s": 2398, "text": "Choose SASL in Thrift Transport" }, { "code": null, "e": 2444, "s": 2430, "text": "Click on Test" }, { "code": null, "e": 2519, "s": 2444, "text": "Check whether the test is successful. After successful completion click OK" }, { "code": null, "e": 2544, "s": 2519, "text": "Click on Get Data =>more" }, { "code": null, "e": 2590, "s": 2544, "text": "In the search bar type ODBC and click connect" }, { "code": null, "e": 2628, "s": 2590, "text": "Choose Cloudera Hive DSN and click OK" }, { "code": null, "e": 2716, "s": 2628, "text": "The tables from your Hive Database will be visible in your Navigator column of Power BI" }, { "code": null, "e": 2803, "s": 2716, "text": "Once connected we may visualize the data imported from the hive table to the Power BI." } ]
PostgreSQL - Transactions - GeeksforGeeks
01 Feb, 2021 The Transaction is not a new word we are hearing. We heard that word many times like “Cash Transaction”. Banks usually deal with cash i.e sending or receiving cash, hence we coin the term as a cash transaction. So simply transaction is a unit of work. In this article, we are going to learn about transactions in the PostgreSQL database language. Transactions are important in any database language, whenever we want to add, delete and update then transactions are used for keeping the integrity of data and several other reasons. Even without the transactions we can add, delete and update the database but there are so high chances to data gets corrected due to loss of data integrity. Now let’s see the ACID properties of a transaction: Atomicity – This property ensures that all the transactions are complete. It follows all or none property i.e the transaction should not be partially completed. Consistency – This property ensures that all the transactions are consistent i.e after committing the transaction those changes are properly updated in the database or not. Isolation – When two transactions are running then both the transactions will have their own privacy i.e one transaction won’t disturb another transaction. Durability – This property ensures that even at the time of system failures the committed data in database is secure i.e permanently. There are three main commands in a transaction block. They are: BEGINCOMMITROLLBACK BEGIN COMMIT ROLLBACK BEGIN; // set of statements [COMMIT | ROLLBACK]; Now we will understand the importance of each and every transaction control command, for that, we have to set up a table in the database first. CREATE TABLE BankStatements ( customer_id serial PRIMARY KEY, full_name VARCHAR NOT NULL, balance INT ); As the database schema is ready now we will insert some values in it. INSERT INTO BankStatements ( customer_id , full_name, balance ) VALUES (1, 'Sekhar rao', 1000), (2, 'Abishek Yadav', 500), (3, 'Srinivas Goud', 1000); BEGIN command is used to initiate a transaction. To start a transaction we should give BEGIN command at first if we don’t give it like that then the database cant able recognizes the transaction. Example 1 BEGIN; INSERT INTO BankStatements ( customer_id, full_name, balance ) VALUES( 4, 'Priya chetri', 500 ) ; COMMIT; Output COMMIT command is used to save changes and reflect them in the database whenever we display the required data. For suppose we updated data in the database but we didn’t give COMMIT then the changes are not reflected in the database. To save the changes done in a transaction, we should COMMIT that transaction for sure. Example 2 BEGIN; UPDATE BankStatements SET balance = balance - 500 WHERE customer_id = 1; SELECT customer_id, full_name, balance FROM BankStatements; UPDATE BankStatements SET balance = balance + 500 WHERE customer_id = 2; COMMIT; SELECT customer_id, full_name, balance FROM BankStatements; Output: ROLLBACK command is used to undo the changes done in transactions. As we know transactions in database languages are used for purpose of large computations, for example in banks. For suppose, the employee of the bank incremented the balance record of the wrong person mistakenly then he can simply rollback and can go to the previous state. Example 3 BEGIN; DELETE FROM BankStatements WHERE customer_id = 1; SELECT customer_id, full_name, balance FROM BankStatements; ROLLBACK; SELECT customer_id, full_name, balance FROM BankStatements; Output: Picked postgreSQL-managing-database Technical Scripter 2020 PostgreSQL Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments PostgreSQL - Change Column Type PostgreSQL - Psql commands PostgreSQL - For Loops PostgreSQL - Function Returning A Table PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - ARRAY_AGG() Function PostgreSQL - DROP INDEX PostgreSQL - ROW_NUMBER Function How to use PostgreSQL Database in Django? PostgreSQL - Copy Table
[ { "code": null, "e": 27633, "s": 27605, "text": "\n01 Feb, 2021" }, { "code": null, "e": 27981, "s": 27633, "text": "The Transaction is not a new word we are hearing. We heard that word many times like “Cash Transaction”. Banks usually deal with cash i.e sending or receiving cash, hence we coin the term as a cash transaction. So simply transaction is a unit of work. In this article, we are going to learn about transactions in the PostgreSQL database language. " }, { "code": null, "e": 28322, "s": 27981, "text": "Transactions are important in any database language, whenever we want to add, delete and update then transactions are used for keeping the integrity of data and several other reasons. Even without the transactions we can add, delete and update the database but there are so high chances to data gets corrected due to loss of data integrity." }, { "code": null, "e": 28374, "s": 28322, "text": "Now let’s see the ACID properties of a transaction:" }, { "code": null, "e": 28535, "s": 28374, "text": "Atomicity – This property ensures that all the transactions are complete. It follows all or none property i.e the transaction should not be partially completed." }, { "code": null, "e": 28708, "s": 28535, "text": "Consistency – This property ensures that all the transactions are consistent i.e after committing the transaction those changes are properly updated in the database or not." }, { "code": null, "e": 28864, "s": 28708, "text": "Isolation – When two transactions are running then both the transactions will have their own privacy i.e one transaction won’t disturb another transaction." }, { "code": null, "e": 28998, "s": 28864, "text": "Durability – This property ensures that even at the time of system failures the committed data in database is secure i.e permanently." }, { "code": null, "e": 29062, "s": 28998, "text": "There are three main commands in a transaction block. They are:" }, { "code": null, "e": 29082, "s": 29062, "text": "BEGINCOMMITROLLBACK" }, { "code": null, "e": 29088, "s": 29082, "text": "BEGIN" }, { "code": null, "e": 29095, "s": 29088, "text": "COMMIT" }, { "code": null, "e": 29104, "s": 29095, "text": "ROLLBACK" }, { "code": null, "e": 29155, "s": 29104, "text": "BEGIN;\n\n// set of statements\n\n[COMMIT | ROLLBACK];" }, { "code": null, "e": 29299, "s": 29155, "text": "Now we will understand the importance of each and every transaction control command, for that, we have to set up a table in the database first." }, { "code": null, "e": 29416, "s": 29299, "text": "CREATE TABLE BankStatements (\n customer_id serial PRIMARY KEY,\n full_name VARCHAR NOT NULL,\n balance INT\n);" }, { "code": null, "e": 29486, "s": 29416, "text": "As the database schema is ready now we will insert some values in it." }, { "code": null, "e": 29661, "s": 29486, "text": "INSERT INTO BankStatements (\n customer_id ,\n full_name,\n balance\n)\nVALUES\n (1, 'Sekhar rao', 1000),\n (2, 'Abishek Yadav', 500),\n (3, 'Srinivas Goud', 1000);" }, { "code": null, "e": 29857, "s": 29661, "text": "BEGIN command is used to initiate a transaction. To start a transaction we should give BEGIN command at first if we don’t give it like that then the database cant able recognizes the transaction." }, { "code": null, "e": 29867, "s": 29857, "text": "Example 1" }, { "code": null, "e": 30028, "s": 29867, "text": "BEGIN;\n\n INSERT INTO BankStatements (\n customer_id,\n full_name,\n balance\n\n)\n VALUES(\n 4, 'Priya chetri', 500\n )\n;\n \nCOMMIT;" }, { "code": null, "e": 30035, "s": 30028, "text": "Output" }, { "code": null, "e": 30355, "s": 30035, "text": "COMMIT command is used to save changes and reflect them in the database whenever we display the required data. For suppose we updated data in the database but we didn’t give COMMIT then the changes are not reflected in the database. To save the changes done in a transaction, we should COMMIT that transaction for sure." }, { "code": null, "e": 30365, "s": 30355, "text": "Example 2" }, { "code": null, "e": 30752, "s": 30365, "text": "BEGIN;\n\n UPDATE BankStatements\n SET balance = balance - 500\n WHERE \n customer_id = 1;\n \n\n SELECT customer_id, full_name, balance\n FROM BankStatements;\n \n UPDATE BankStatements\n SET balance = balance + 500\n WHERE \n customer_id = 2;\n \n \nCOMMIT;\n\n\nSELECT customer_id, full_name, balance\n FROM BankStatements;\n " }, { "code": null, "e": 30760, "s": 30752, "text": "Output:" }, { "code": null, "e": 31101, "s": 30760, "text": "ROLLBACK command is used to undo the changes done in transactions. As we know transactions in database languages are used for purpose of large computations, for example in banks. For suppose, the employee of the bank incremented the balance record of the wrong person mistakenly then he can simply rollback and can go to the previous state." }, { "code": null, "e": 31111, "s": 31101, "text": "Example 3" }, { "code": null, "e": 31354, "s": 31111, "text": "BEGIN;\n\n DELETE FROM BankStatements\n WHERE \n customer_id = 1;\n \n\n SELECT customer_id, full_name, balance\n FROM BankStatements;\n \n\nROLLBACK;\n\n\nSELECT customer_id, full_name, balance\n FROM BankStatements;" }, { "code": null, "e": 31362, "s": 31354, "text": "Output:" }, { "code": null, "e": 31369, "s": 31362, "text": "Picked" }, { "code": null, "e": 31398, "s": 31369, "text": "postgreSQL-managing-database" }, { "code": null, "e": 31422, "s": 31398, "text": "Technical Scripter 2020" }, { "code": null, "e": 31433, "s": 31422, "text": "PostgreSQL" }, { "code": null, "e": 31452, "s": 31433, "text": "Technical Scripter" }, { "code": null, "e": 31550, "s": 31452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31559, "s": 31550, "text": "Comments" }, { "code": null, "e": 31572, "s": 31559, "text": "Old Comments" }, { "code": null, "e": 31604, "s": 31572, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 31631, "s": 31604, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 31654, "s": 31631, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 31694, "s": 31654, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 31749, "s": 31694, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 31783, "s": 31749, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 31807, "s": 31783, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 31840, "s": 31807, "text": "PostgreSQL - ROW_NUMBER Function" }, { "code": null, "e": 31882, "s": 31840, "text": "How to use PostgreSQL Database in Django?" } ]
Operating Systems | Set 13 - GeeksforGeeks
27 Mar, 2017 Following questions have been asked in GATE CS 2007 exam. 1) A virtual memory system uses First In First Out (FIFO) page replacement policy and allocates a fixed number of frames to a process. Consider the following statements:P: Increasing the number of page frames allocated to a process sometimes increases the page fault rate.Q: Some programs do not exhibit locality of reference. Which one of the following is TRUE?(A) Both P and Q are true, and Q is the reason for P(B) Both P and Q are true, but Q is not the reason for P.(C) P is false, but Q is true(D) Both P and Q are false. Answer (B)P is true. Increasing the number of page frames allocated to process may increases the no. of page faults (See Belady’s Anomaly).Q is also true, but Q is not the reason for-P as Belady’s Anomaly occurs for some specific patterns of page references. 2) A single processor system has three resource types X, Y and Z, which are shared by three processes. There are 5 units of each resource type. Consider the following scenario, where the column alloc denotes the number of units of each resource type allocated to each process, and the column request denotes the number of units of each resource type requested by a process in order to complete execution. Which of these processes will finish LAST? alloc request X Y Z X Y Z P0 1 2 1 1 0 3 P1 2 0 1 0 1 2 P2 2 2 1 1 2 0 (A) P0(B) P1(C) P2(D) None of the above, since the system is in a deadlock Answer (C)Once all resources (5, 4 and 3 instances of X, Y and Z respectively) are allocated, 0, 1 and 2 instances of X, Y and Z are left. Only needs of P1 can be satisfied. So P1 can finish its execution first. Once P1 is done, it releases 2, 1 and 3 units of X, Y and Z respectively. Among P0 and P2, needs of P0 can only be satisfied. So P0 finishes its execution. Finally, P2 finishes its execution. 3) Two processes, P1 and P2, need to access a critical section of code. Consider the following synchronization construct used by the processes:Here, wants1 and wants2 are shared variables, which are initialized to false. Which one of the following statements is TRUE about the above construct? /* P1 */ while (true) { wants1 = true; while (wants2 == true); /* Critical Section */ wants1=false; } /* Remainder section */ /* P2 */ while (true) { wants2 = true; while (wants1==true); /* Critical Section */ wants2 = false; } /* Remainder section */ (A) It does not ensure mutual exclusion.(B) It does not ensure bounded waiting.(C) It requires that processes enter the critical section in strict alternation.(D) It does not prevent deadlocks, but ensures mutual exclusion. Answer (D) The above synchronization constructs don’t prevent deadlock. When both wants1 and wants2 become true, both P1 and P2 stuck forever in their while loops waiting for each other to finish. 4) Consider the following statements about user level threads and kernel level threads. Which one of the following statement is FALSE?(A) Context switch time is longer for kernel level threads than for user level threads.(B) User level threads do not need any hardware support.(C) Related kernel level threads can be scheduled on different processors in a multi-processor system.(D) Blocking one kernel level thread blocks all related threads. Answer (D)Since kernel level threads are managed by kernel, blocking one thread doesn’t cause all related threads to block. It’s a problem with user level threads. See this for more details. Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above GATE-CS-2007 GATE CS MCQ Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Page Replacement Algorithms in Operating Systems Semaphores in Process Synchronization Differences between TCP and UDP Data encryption standard (DES) | Set 1 Regular Expressions, Regular Grammar and Regular Languages Practice questions on Height balanced/AVL Tree Computer Networks | Set 1 Operating Systems | Set 1 Database Management Systems | Set 1 Computer Networks | Set 2
[ { "code": null, "e": 23938, "s": 23910, "text": "\n27 Mar, 2017" }, { "code": null, "e": 23996, "s": 23938, "text": "Following questions have been asked in GATE CS 2007 exam." }, { "code": null, "e": 24524, "s": 23996, "text": "1) A virtual memory system uses First In First Out (FIFO) page replacement policy and allocates a fixed number of frames to a process. Consider the following statements:P: Increasing the number of page frames allocated to a process sometimes increases the page fault rate.Q: Some programs do not exhibit locality of reference. Which one of the following is TRUE?(A) Both P and Q are true, and Q is the reason for P(B) Both P and Q are true, but Q is not the reason for P.(C) P is false, but Q is true(D) Both P and Q are false." }, { "code": null, "e": 24783, "s": 24524, "text": "Answer (B)P is true. Increasing the number of page frames allocated to process may increases the no. of page faults (See Belady’s Anomaly).Q is also true, but Q is not the reason for-P as Belady’s Anomaly occurs for some specific patterns of page references." }, { "code": null, "e": 25231, "s": 24783, "text": "2) A single processor system has three resource types X, Y and Z, which are shared by three processes. There are 5 units of each resource type. Consider the following scenario, where the column alloc denotes the number of units of each resource type allocated to each process, and the column request denotes the number of units of each resource type requested by a process in order to complete execution. Which of these processes will finish LAST?" }, { "code": null, "e": 25370, "s": 25231, "text": " \n alloc request\n X Y Z X Y Z\nP0 1 2 1 1 0 3\nP1 2 0 1 0 1 2\nP2 2 2 1 1 2 0\n" }, { "code": null, "e": 25445, "s": 25370, "text": "(A) P0(B) P1(C) P2(D) None of the above, since the system is in a deadlock" }, { "code": null, "e": 25849, "s": 25445, "text": "Answer (C)Once all resources (5, 4 and 3 instances of X, Y and Z respectively) are allocated, 0, 1 and 2 instances of X, Y and Z are left. Only needs of P1 can be satisfied. So P1 can finish its execution first. Once P1 is done, it releases 2, 1 and 3 units of X, Y and Z respectively. Among P0 and P2, needs of P0 can only be satisfied. So P0 finishes its execution. Finally, P2 finishes its execution." }, { "code": null, "e": 26143, "s": 25849, "text": "3) Two processes, P1 and P2, need to access a critical section of code. Consider the following synchronization construct used by the processes:Here, wants1 and wants2 are shared variables, which are initialized to false. Which one of the following statements is TRUE about the above construct?" }, { "code": null, "e": 26431, "s": 26143, "text": " /* P1 */\nwhile (true) {\n wants1 = true;\n while (wants2 == true);\n /* Critical\n Section */\n wants1=false;\n}\n/* Remainder section */ \n\n\n/* P2 */\nwhile (true) {\n wants2 = true;\n while (wants1==true);\n /* Critical\n Section */\n wants2 = false;\n}\n/* Remainder section */\n" }, { "code": null, "e": 26655, "s": 26431, "text": "(A) It does not ensure mutual exclusion.(B) It does not ensure bounded waiting.(C) It requires that processes enter the critical section in strict alternation.(D) It does not prevent deadlocks, but ensures mutual exclusion." }, { "code": null, "e": 26666, "s": 26655, "text": "Answer (D)" }, { "code": null, "e": 26852, "s": 26666, "text": "The above synchronization constructs don’t prevent deadlock. When both wants1 and wants2 become true, both P1 and P2 stuck forever in their while loops waiting for each other to finish." }, { "code": null, "e": 27296, "s": 26852, "text": "4) Consider the following statements about user level threads and kernel level threads. Which one of the following statement is FALSE?(A) Context switch time is longer for kernel level threads than for user level threads.(B) User level threads do not need any hardware support.(C) Related kernel level threads can be scheduled on different processors in a multi-processor system.(D) Blocking one kernel level thread blocks all related threads." }, { "code": null, "e": 27487, "s": 27296, "text": "Answer (D)Since kernel level threads are managed by kernel, blocking one thread doesn’t cause all related threads to block. It’s a problem with user level threads. See this for more details." }, { "code": null, "e": 27601, "s": 27487, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc." }, { "code": null, "e": 27749, "s": 27601, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above" }, { "code": null, "e": 27762, "s": 27749, "text": "GATE-CS-2007" }, { "code": null, "e": 27770, "s": 27762, "text": "GATE CS" }, { "code": null, "e": 27774, "s": 27770, "text": "MCQ" }, { "code": null, "e": 27792, "s": 27774, "text": "Operating Systems" }, { "code": null, "e": 27810, "s": 27792, "text": "Operating Systems" }, { "code": null, "e": 27908, "s": 27810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27917, "s": 27908, "text": "Comments" }, { "code": null, "e": 27930, "s": 27917, "text": "Old Comments" }, { "code": null, "e": 27979, "s": 27930, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 28017, "s": 27979, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 28049, "s": 28017, "text": "Differences between TCP and UDP" }, { "code": null, "e": 28088, "s": 28049, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 28147, "s": 28088, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 28194, "s": 28147, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 28220, "s": 28194, "text": "Computer Networks | Set 1" }, { "code": null, "e": 28246, "s": 28220, "text": "Operating Systems | Set 1" }, { "code": null, "e": 28282, "s": 28246, "text": "Database Management Systems | Set 1" } ]
React Memo
Using memo will cause React to skip rendering a component if its props have not changed. This can improve performance. This section uses React Hooks. See the React Hooks section for more information on Hooks. In this example, the Todos component re-renders even when the todos have not changed. index.js: import { useState } from "react"; import ReactDOM from "react-dom/client"; import Todos from "./Todos"; const App = () => { const [count, setCount] = useState(0); const [todos, setTodos] = useState(["todo 1", "todo 2"]); const increment = () => { setCount((c) => c + 1); }; return ( <> <Todos todos={todos} /> <hr /> <div> Count: {count} <button onClick={increment}>+</button> </div> </> ); }; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />); Todos.js: const Todos = ({ todos }) => { console.log("child render"); return ( <> <h2>My Todos</h2> {todos.map((todo, index) => { return <p key={index}>{todo}</p>; })} </> ); }; export default Todos; Run Example » When you click the increment button, the Todos component re-renders. If this component was complex, it could cause performance issues. To fix this, we can use memo. Use memoto keep the Todos component from needlessly re-rendering. Wrap the Todos component export in memo: index.js: import { useState } from "react"; import ReactDOM from "react-dom/client"; import Todos from "./Todos"; const App = () => { const [count, setCount] = useState(0); const [todos, setTodos] = useState(["todo 1", "todo 2"]); const increment = () => { setCount((c) => c + 1); }; return ( <> <Todos todos={todos} /> <hr /> <div> Count: {count} <button onClick={increment}>+</button> </div> </> ); }; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />); Todos.js: import { memo } from "react"; const Todos = ({ todos }) => { console.log("child render"); return ( <> <h2>My Todos</h2> {todos.map((todo, index) => { return <p key={index}>{todo}</p>; })} </> ); }; export default memo(Todos); Run Example » Now the Todos component only re-renders when the todos that are passed to it through props are updated. 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": 89, "s": 0, "text": "Using memo will cause React to skip rendering a component if its props have not changed." }, { "code": null, "e": 119, "s": 89, "text": "This can improve performance." }, { "code": null, "e": 209, "s": 119, "text": "This section uses React Hooks. See the React Hooks section for more information on Hooks." }, { "code": null, "e": 295, "s": 209, "text": "In this example, the Todos component re-renders even when the todos have not changed." }, { "code": null, "e": 305, "s": 295, "text": "index.js:" }, { "code": null, "e": 857, "s": 305, "text": "import { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport Todos from \"./Todos\";\n\nconst App = () => {\n const [count, setCount] = useState(0);\n const [todos, setTodos] = useState([\"todo 1\", \"todo 2\"]);\n\n const increment = () => {\n setCount((c) => c + 1);\n };\n\n return (\n <>\n <Todos todos={todos} />\n <hr />\n <div>\n Count: {count}\n <button onClick={increment}>+</button>\n </div>\n </>\n );\n};\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<App />);\n" }, { "code": null, "e": 867, "s": 857, "text": "Todos.js:" }, { "code": null, "e": 1099, "s": 867, "text": "const Todos = ({ todos }) => {\n console.log(\"child render\");\n return (\n <>\n <h2>My Todos</h2>\n {todos.map((todo, index) => {\n return <p key={index}>{todo}</p>;\n })}\n </>\n );\n};\n\nexport default Todos;\n" }, { "code": null, "e": 1116, "s": 1099, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1185, "s": 1116, "text": "When you click the increment button, the Todos component re-renders." }, { "code": null, "e": 1251, "s": 1185, "text": "If this component was complex, it could cause performance issues." }, { "code": null, "e": 1281, "s": 1251, "text": "To fix this, we can use memo." }, { "code": null, "e": 1347, "s": 1281, "text": "Use memoto keep the Todos component from needlessly re-rendering." }, { "code": null, "e": 1388, "s": 1347, "text": "Wrap the Todos component export in memo:" }, { "code": null, "e": 1398, "s": 1388, "text": "index.js:" }, { "code": null, "e": 1950, "s": 1398, "text": "import { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport Todos from \"./Todos\";\n\nconst App = () => {\n const [count, setCount] = useState(0);\n const [todos, setTodos] = useState([\"todo 1\", \"todo 2\"]);\n\n const increment = () => {\n setCount((c) => c + 1);\n };\n\n return (\n <>\n <Todos todos={todos} />\n <hr />\n <div>\n Count: {count}\n <button onClick={increment}>+</button>\n </div>\n </>\n );\n};\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<App />);\n" }, { "code": null, "e": 1960, "s": 1950, "text": "Todos.js:" }, { "code": null, "e": 2229, "s": 1960, "text": "import { memo } from \"react\";\n\nconst Todos = ({ todos }) => {\n console.log(\"child render\");\n return (\n <>\n <h2>My Todos</h2>\n {todos.map((todo, index) => {\n return <p key={index}>{todo}</p>;\n })}\n </>\n );\n};\n\nexport default memo(Todos);\n" }, { "code": null, "e": 2246, "s": 2229, "text": "\nRun \nExample »\n" }, { "code": null, "e": 2350, "s": 2246, "text": "Now the Todos component only re-renders when the todos that are passed to it through props are updated." }, { "code": null, "e": 2383, "s": 2350, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2425, "s": 2383, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2532, "s": 2425, "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": 2551, "s": 2532, "text": "[email protected]" } ]
Solidity - Pure Functions
Pure functions ensure that they not read or modify the state. A function can be declared as pure. The following statements if present in the function are considered reading the state and compiler will throw warning in such cases. Reading state variables. Reading state variables. Accessing address(this).balance or <address>.balance. Accessing address(this).balance or <address>.balance. Accessing any of the special variable of block, tx, msg (msg.sig and msg.data can be read). Accessing any of the special variable of block, tx, msg (msg.sig and msg.data can be read). Calling any function not marked pure. Calling any function not marked pure. Using inline assembly that contains certain opcodes. Using inline assembly that contains certain opcodes. Pure functions can use the revert() and require() functions to revert potential state changes if an error occurs. See the example below using a view function. pragma solidity ^0.5.0; contract Test { function getResult() public pure returns(uint product, uint sum){ uint a = 1; uint b = 2; product = a * b; sum = a + b; } } Run the above program using steps provided in Solidity First Application chapter. 0: uint256: product 2 1: uint256: sum 3 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2786, "s": 2555, "text": "Pure functions ensure that they not read or modify the state. A function can be declared as pure. The following statements if present in the function are considered reading the state and compiler will throw warning in such cases. " }, { "code": null, "e": 2811, "s": 2786, "text": "Reading state variables." }, { "code": null, "e": 2836, "s": 2811, "text": "Reading state variables." }, { "code": null, "e": 2890, "s": 2836, "text": "Accessing address(this).balance or <address>.balance." }, { "code": null, "e": 2944, "s": 2890, "text": "Accessing address(this).balance or <address>.balance." }, { "code": null, "e": 3036, "s": 2944, "text": "Accessing any of the special variable of block, tx, msg (msg.sig and msg.data can be read)." }, { "code": null, "e": 3128, "s": 3036, "text": "Accessing any of the special variable of block, tx, msg (msg.sig and msg.data can be read)." }, { "code": null, "e": 3166, "s": 3128, "text": "Calling any function not marked pure." }, { "code": null, "e": 3204, "s": 3166, "text": "Calling any function not marked pure." }, { "code": null, "e": 3257, "s": 3204, "text": "Using inline assembly that contains certain opcodes." }, { "code": null, "e": 3310, "s": 3257, "text": "Using inline assembly that contains certain opcodes." }, { "code": null, "e": 3424, "s": 3310, "text": "Pure functions can use the revert() and require() functions to revert potential state changes if an error occurs." }, { "code": null, "e": 3469, "s": 3424, "text": "See the example below using a view function." }, { "code": null, "e": 3666, "s": 3469, "text": "pragma solidity ^0.5.0;\n\ncontract Test {\n function getResult() public pure returns(uint product, uint sum){\n uint a = 1; \n uint b = 2;\n product = a * b;\n sum = a + b; \n }\n}" }, { "code": null, "e": 3748, "s": 3666, "text": "Run the above program using steps provided in Solidity First Application chapter." }, { "code": null, "e": 3789, "s": 3748, "text": "0: uint256: product 2\n1: uint256: sum 3\n" }, { "code": null, "e": 3824, "s": 3789, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3841, "s": 3824, "text": " Abhilash Nelson" }, { "code": null, "e": 3876, "s": 3841, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3893, "s": 3876, "text": " Frahaan Hussain" }, { "code": null, "e": 3928, "s": 3893, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3942, "s": 3928, "text": " Swapnil Kole" }, { "code": null, "e": 3949, "s": 3942, "text": " Print" }, { "code": null, "e": 3960, "s": 3949, "text": " Add Notes" } ]
Optimize Python Code in Jupyter Notebook | by Winson Waisakurnia | Towards Data Science
Want to make a slow Python code fast in Jupyter Notebook? By using sum aggregate as an example, we will measure the runtime with %%time and find the bottleneck using %lprun line profiler. Assume that Pandas doesn’t have group-by and aggregate functions and we need to implement it ourselves. We want to aggregate the table above by name and calculate the sum of value. Perhaps, in our first iteration, we come out with code like below. We aggregate the value with the help of a dictionary (name ⇨ value). By iterating each row, we update the value of the dictionary. At the end of the iteration, we convert the dictionary back into Pandas’ DataFrame. Before we optimize the code, we need to ask: “Do we really need to optimize the code? Why?” It is not worth it if we take more time to optimize compared to waiting a little bit longer for the job to finish, isn’t it? “Premature optimization is the root of all evil.” — Donal Knuth For now, let’s assume that the sum aggregate code is too slow and we need to optimize it. How can we do that? “If you can’t measure it, you can’t improve it.” — Peter Drucker We need the ability to measure code runtime to compare the before and after optimization. There is a chance that we make things worse especially if we use an external library like Numpy and Pandas. We don’t know how the library implemented. Code with %% prefix is IPython cell magic-function. We can measure the runtime of a cell by adding %%time to the cell. We don’t need to install any new library for that. We just need to import time which is part of the Python standard library. %%timesum_aggregate_1(df, 'name', 'value').sort_values('value', ascending=False).head() The measured runtime is about 38 s. Now, which part do we need to optimize? If I am the one who is taking a guess, I will choose to optimize the time.sleep() part. It seems obvious. Optimizing based on gut feeling could end up with no significant improvement and just wasting time. We need to find the bottleneck. “Any improvements made anywhere besides the bottleneck are an illusion.” — Gene Kim Optimizing part of the code that is not the bottleneck will not reduce the total runtime significantly. That’s why Gene Kim said that the improvement is just an illusion and useless. How can we find the bottleneck? We can use line-profiler library to get the execution time for each line. We need to install line-profiler. After that, we need to import the magic function with %load_ext. ! pip install line-profiler%load_ext line_profiler We need to provide function to profile and execution trigger arguments to the line profiler. In our case, the function we want to profile is sum_aggregate_1 and we trigger the execution with sum_aggregate_1(random_df, 'name', 'value). # %lprun -f [function to profile] [execution trigger]# [function to profile]: sum_aggregate_1# [execution trigger]: sum_aggregate_1(random_df, 'name', 'value')%lprun -f sum_aggregate_1 sum_aggregate_1(random_df, 'name', 'value') From the result, we can see that the main bottleneck of the function is at line #4. Now, we know that DataFrame.iterrows() is very slow for iteration. It took 66% of execution time. After we found out the bottleneck, we could proceed with optimizing the code. We could just simply find alternatives for DataFrame.iterrows() from a search engine. One of the alternatives is to get the key and value columns as Numpy arrays. After that, zip both Numpy arrays and iterate over it. We could observe that the bottleneck is now moving from the iteration part to time.sleep() part. The total runtime decreased from 38 s to 7 s. By repeatedly finding and optimizing the bottleneck, we do the most impactful optimization first. It is like using a “greedy algorithm” mindset to prioritize optimization. We can stop optimizing when the code runtime is fast enough, although it is tempting to do further optimization. Three things that are very important to remember when doing optimization: Do optimization when you really need itDon’t optimize the code if it doesn’t worth your time because instead of making it fast, there is a chance you will introduce new bugs.We can’t improve what we can’t measureFirst, we must choose which metric we want to optimize. After that, we need to find how to measure it. Currently, we tried to optimize runtime. We can also choose to optimize memory usage in other cases.Optimize the bottleneckOptimizing part of the code that is not the bottleneck is useless because it will not reduce the runtime significantly. We can use line-profiler library to find the bottleneck. Do optimization when you really need itDon’t optimize the code if it doesn’t worth your time because instead of making it fast, there is a chance you will introduce new bugs. We can’t improve what we can’t measureFirst, we must choose which metric we want to optimize. After that, we need to find how to measure it. Currently, we tried to optimize runtime. We can also choose to optimize memory usage in other cases. Optimize the bottleneckOptimizing part of the code that is not the bottleneck is useless because it will not reduce the runtime significantly. We can use line-profiler library to find the bottleneck. You can get and run all of the code above from my Google Colab notebook. From the notebook, you can see the examples of how we could profile a class method. There is an example of how you could profile another function called by the triggering function as well. Thanks for reading. Hopefully, this could help you optimizing your code when it is too slow. Please leave a comment or note if you have any suggestions or feedback.
[ { "code": null, "e": 360, "s": 172, "text": "Want to make a slow Python code fast in Jupyter Notebook? By using sum aggregate as an example, we will measure the runtime with %%time and find the bottleneck using %lprun line profiler." }, { "code": null, "e": 541, "s": 360, "text": "Assume that Pandas doesn’t have group-by and aggregate functions and we need to implement it ourselves. We want to aggregate the table above by name and calculate the sum of value." }, { "code": null, "e": 823, "s": 541, "text": "Perhaps, in our first iteration, we come out with code like below. We aggregate the value with the help of a dictionary (name ⇨ value). By iterating each row, we update the value of the dictionary. At the end of the iteration, we convert the dictionary back into Pandas’ DataFrame." }, { "code": null, "e": 1040, "s": 823, "text": "Before we optimize the code, we need to ask: “Do we really need to optimize the code? Why?” It is not worth it if we take more time to optimize compared to waiting a little bit longer for the job to finish, isn’t it?" }, { "code": null, "e": 1104, "s": 1040, "text": "“Premature optimization is the root of all evil.” — Donal Knuth" }, { "code": null, "e": 1214, "s": 1104, "text": "For now, let’s assume that the sum aggregate code is too slow and we need to optimize it. How can we do that?" }, { "code": null, "e": 1279, "s": 1214, "text": "“If you can’t measure it, you can’t improve it.” — Peter Drucker" }, { "code": null, "e": 1520, "s": 1279, "text": "We need the ability to measure code runtime to compare the before and after optimization. There is a chance that we make things worse especially if we use an external library like Numpy and Pandas. We don’t know how the library implemented." }, { "code": null, "e": 1764, "s": 1520, "text": "Code with %% prefix is IPython cell magic-function. We can measure the runtime of a cell by adding %%time to the cell. We don’t need to install any new library for that. We just need to import time which is part of the Python standard library." }, { "code": null, "e": 1852, "s": 1764, "text": "%%timesum_aggregate_1(df, 'name', 'value').sort_values('value', ascending=False).head()" }, { "code": null, "e": 2166, "s": 1852, "text": "The measured runtime is about 38 s. Now, which part do we need to optimize? If I am the one who is taking a guess, I will choose to optimize the time.sleep() part. It seems obvious. Optimizing based on gut feeling could end up with no significant improvement and just wasting time. We need to find the bottleneck." }, { "code": null, "e": 2250, "s": 2166, "text": "“Any improvements made anywhere besides the bottleneck are an illusion.” — Gene Kim" }, { "code": null, "e": 2465, "s": 2250, "text": "Optimizing part of the code that is not the bottleneck will not reduce the total runtime significantly. That’s why Gene Kim said that the improvement is just an illusion and useless. How can we find the bottleneck?" }, { "code": null, "e": 2638, "s": 2465, "text": "We can use line-profiler library to get the execution time for each line. We need to install line-profiler. After that, we need to import the magic function with %load_ext." }, { "code": null, "e": 2689, "s": 2638, "text": "! pip install line-profiler%load_ext line_profiler" }, { "code": null, "e": 2924, "s": 2689, "text": "We need to provide function to profile and execution trigger arguments to the line profiler. In our case, the function we want to profile is sum_aggregate_1 and we trigger the execution with sum_aggregate_1(random_df, 'name', 'value)." }, { "code": null, "e": 3153, "s": 2924, "text": "# %lprun -f [function to profile] [execution trigger]# [function to profile]: sum_aggregate_1# [execution trigger]: sum_aggregate_1(random_df, 'name', 'value')%lprun -f sum_aggregate_1 sum_aggregate_1(random_df, 'name', 'value')" }, { "code": null, "e": 3335, "s": 3153, "text": "From the result, we can see that the main bottleneck of the function is at line #4. Now, we know that DataFrame.iterrows() is very slow for iteration. It took 66% of execution time." }, { "code": null, "e": 3499, "s": 3335, "text": "After we found out the bottleneck, we could proceed with optimizing the code. We could just simply find alternatives for DataFrame.iterrows() from a search engine." }, { "code": null, "e": 3774, "s": 3499, "text": "One of the alternatives is to get the key and value columns as Numpy arrays. After that, zip both Numpy arrays and iterate over it. We could observe that the bottleneck is now moving from the iteration part to time.sleep() part. The total runtime decreased from 38 s to 7 s." }, { "code": null, "e": 4059, "s": 3774, "text": "By repeatedly finding and optimizing the bottleneck, we do the most impactful optimization first. It is like using a “greedy algorithm” mindset to prioritize optimization. We can stop optimizing when the code runtime is fast enough, although it is tempting to do further optimization." }, { "code": null, "e": 4133, "s": 4059, "text": "Three things that are very important to remember when doing optimization:" }, { "code": null, "e": 4748, "s": 4133, "text": "Do optimization when you really need itDon’t optimize the code if it doesn’t worth your time because instead of making it fast, there is a chance you will introduce new bugs.We can’t improve what we can’t measureFirst, we must choose which metric we want to optimize. After that, we need to find how to measure it. Currently, we tried to optimize runtime. We can also choose to optimize memory usage in other cases.Optimize the bottleneckOptimizing part of the code that is not the bottleneck is useless because it will not reduce the runtime significantly. We can use line-profiler library to find the bottleneck." }, { "code": null, "e": 4923, "s": 4748, "text": "Do optimization when you really need itDon’t optimize the code if it doesn’t worth your time because instead of making it fast, there is a chance you will introduce new bugs." }, { "code": null, "e": 5165, "s": 4923, "text": "We can’t improve what we can’t measureFirst, we must choose which metric we want to optimize. After that, we need to find how to measure it. Currently, we tried to optimize runtime. We can also choose to optimize memory usage in other cases." }, { "code": null, "e": 5365, "s": 5165, "text": "Optimize the bottleneckOptimizing part of the code that is not the bottleneck is useless because it will not reduce the runtime significantly. We can use line-profiler library to find the bottleneck." }, { "code": null, "e": 5627, "s": 5365, "text": "You can get and run all of the code above from my Google Colab notebook. From the notebook, you can see the examples of how we could profile a class method. There is an example of how you could profile another function called by the triggering function as well." } ]
AI for good: Banknotes detection for blind people | by Bruno Sánchez-A Nuño | Towards Data Science
This service recognizes what currency a banknote is (euro or usd dollar) and what denomination (5,10,20, ...). The social impact purpose is to help blind people, so I took care to make “real-life” training images holding the banknotes in my hand, sometimes folded, sometimes covering part of it. This post hopefully helps encourage others to learn Deep Learning. I’m using the amazing fast.ai online free course, which I very much recommend. As a testament to their pragmatic, top-down approach, this side-project is based on lesson 3. On their online forum you can find many more amazing applications by fellow students. My project is deployed on iris.brunosan.eu Here’s an example inference: Amazingly, the fast, fun and easier part is the deep learning part (congrats fastai!), and the production server took roughly 10x time (I also had to learn some details about docker and serverless applications). I found just a few efforts on identifying banknotes to help blind people. Some attempts use Computer Vision and “scale-invariant features” (with ~70% accuracy) and some use Machine Learning (with much higher accuracy). On the machine learning side, worth mentioning one by Microsoft research last year and one this year by a Nepali programmer, Kshitiz Rimal, with support from Intel: Microsoft announced their version at an AI summit last year, “has been downloaded more than 100,000 times and has helped users with over three million tasks.” Their code is available here (sans training data). Basically, they use Keras and transfer learning, as we do in our course, but they don’t unfreeze for fine-tuning, and they create a “background” negative class with non-relevant pictures (I find odd to create a negative class... how can you learn “absence features”). They used a mobile-friendly pre-trained net “MobileNet” to run the detection on-device, and 250 images per banknote (+ plus data augmentation). They get 85% accuracy. The nepali version from Kshitiz: 14,000 images in total (taken by him), and gets 93% accuracy. He started with VGG19 and Keras for the neural net, and “Reach Native” for the app (This is a framework that can create both an iOS and Android app with the same code), but then he switched to Tensorflow with MobileNetV2 and native apps on each platform. This was a 6 months effort. Kudos!! He has the code for the training, AND the code for the apps, AND the training data on github. My goal was to replicate a similar solution, but I will only make a functioning website, not the app, nor on-device detection (I’m leaving that for now). However, I am going to use a different architecture. Since I want to do several currencies at once, I wanted to try multi-class classification. All the solutions I’ve seen use single-class detection, e.g. “`1 usd`”, and I wanted to break it into two classes, “`1`” and “`usd`”. The reason being that I think there are features to learn across currencies (all USD look similar) and also across denominations (e.g. the 5usd and 5eur have the number 5 in common). The commonalities should help the net reinforce those features for each class (e.g. a big digit “5”). I basically followed the fast.ai course lesson on multi-classfor satellite detection, without really many modifications: It is surprisingly hard to get images on single banknotes in real-life situations. After finishing this project I found the academic paper with Jordan currency I mentioned above, and the Nepali project which both link to their dataset. I decided to lean on Google Image searches and images from the European Central Bank and the US Mint, which I knew was going to give me unrealistically good images of banknotes. I also took some pictures myself with money I had home, for the low denominations (sadly I don’t have 100$ or 500eur lying around at home). In total I had between 14 and 30 images per banknote denomination. Not much at all. My image dataset is here. Since I didn’t have many images, I used data augmentation with widened parameters. (I wrongly added flips, it’s probably not a good idea): tfms = get_transforms(do_flip=True,flip_vert=True, max_rotate=90, max_zoom=1.5, max_lighting=0.5, max_warp=0.5) In the end, the dataset it looked like this during training/validation: It’s amazing one can get such good results with that few images. I used 20% split for validation, and 256 pixel size for the images, and `resnet50` as the pre-trained model. With the resnet frozen, I did 15 epochs (2 minutes each) training the added top layers, and got an fbeta of `.087`, pretty good already. Then unfroze and did more training with sliced learning rates (bigger rates on the last layers) on 20 epochs, to get `fbeta=.098`. I was able to squeeze some more accuracy by freezing again the pre-trained model and doing some more epochs. The best was `fbeta=0.983`. No signs of over-fitting, and I used the default parameters of dropout. Exporting the model to PyTorch Torch script for deployment is just a few lines of code. I did spend some time testing the exported model, and looking at the outputs (both the raw activations and the softmax. I then realized that I could use it to infer confidence: positive raw activations (which always translate to high softmax) usually meant high confidence. negative raw activations but non-zero softmax probabilities happened when there was no clear identification, so I could use them as “tentative alternatives”. e.g. let’s see this problematic image of a folded 5usd covering most of the 5 {‘probabilities’: ‘classes’: [‘1’, ‘10’, ‘100’, ‘20’, ‘200’, ‘5’, ‘50’, ‘500’, ‘euro’, ‘usd’] ‘softmax’: [‘0.00’, ‘0.00’, ‘0.01’, ‘0.04’, ‘0.01’, ‘0.20’, ‘0.00’, ‘0.00’, ‘0.00’, ‘99.73’], ‘output’: [‘-544.18’, ‘-616.93’, ‘-347.05’, ‘-246.08’, ‘-430.36’, ‘-83.76’, ‘-550.20’, ‘-655.22’, ‘-535.67’, ‘537.59’], ‘summary’: [‘usd’], ‘others’: {‘5’: ‘0.20%’, ‘20’: ‘0.04%’, ‘100’: ‘0.01%’, ‘200’: ‘0.01%’}} Only the activations for class “`usd`” positive (last on the array), but the softmax also correctly brings the class “`5`” up, together with some doubt about the class `20`. This was the hard part. Basically you need 2 parts. The front-end and the back-end. The front-end is what people see, and what it does is give you a page to look at (I use Bootstrap for the UI), the code to select an image and finally displays the result. I added some code to the front-end to downsample the image on the client using Javascript. The reason being that camera pictures are quite heavy nowadays and all the inference process needs is a 256 pixel image. These are the 11 lines of code to downsample on the client. Since these are all static code, I used github pages on the same repository. To send the image to the server I pass them directly as DataURI instead of uploading them somewhere and then pulling it from there. The back-end is the one that receives the image, runs the inference code on our model, and returns the results. It’s the hard part of the hard part :), see below: I first used Google Cloud Engine (GCE), as instructed here . My deployment code is here, and it includes code to upload and save a copy of the user images with the inferred class, so I can check false classifications use them for further training. Quite neat. Overall it was very easy to deploy. It basically creates a docker that deploys whatever code you need, and spins instances as needed. My problem was that the server is always running, actually 2 instances at least. GCE is meant for very high scalability and response, which is great, but it also meant I was paying all the time, even if no one is using it. I think it would have been 5–10$/month. If possible I wanted to deploy something that can remain online for long without paying much. I decided to switch to AWS Lambda (course instructions here). The process looks more complicated, but it’s actually not that hard, and the huge benefit is that you only pay for use. Moreover, for the usage level, we will be well within the free tier (except the cost of keeping the model on S3, which is minimal). My code to deploy is here. Since you are deploying a Torchscript model, you just need PyTorch dependencies, and AWS has a nice docker file with all that you need. I had to add some python libraries for formatting the output and logging and they were all there. That means your actual python code is minimal and you don’t need to bring fastai (On the course thread another student shared her deployment tricks IF you need to also bring fastai to the deployment). Inference of the classification takes 0.2 seconds roughly, which is really fast, but the overall time for the user from selecting the image to getting the result can be up to 30s, or even fail. The extra time is partly uploading the image from the client to the server, and downscaling it before uploading if needed. In real-life tests, the response time was a median of 1s, which is acceptable... except for the first times, it sometimes took up to 30s to respond for the first time. I think this is called “cold start”, and corresponds to the time of AWS pulling the Lambda from storage. To minimize this impact I added some code that triggers a ping to the server as soon as you load the client page. That ping just returns “pong” so it doesn’t consume much billing time, but it makes the trick of triggering AWS to get the lambda function ready for the real inference call. This summer I have a small weekly section to talk about Impact Science on a spanish national radio, and I dedicated to talk in one episode about Artificial Intelligence and the impact on employment and Society. I presented this tool as an example. You can listen to it (in Spanish, timestamp 2h31m): Julia en la Onda, Onda Cero. I’d love to get your feedback and ideas. Or if you try to replicate it have problems, let me know. These are some points already on my mind for the next sprint: Re-train the model using a mobile-friendly like “MobileNetV2” Re-train the model using as many currencies (and coins) as possible. The benefits of multi-category classification to detect the denomination should become visible as you add more currencies. Add server code to upload a copy of the user images, as I did with the GCE deployment. Smartphone apps with on-device inference. Some rights reserved
[ { "code": null, "e": 468, "s": 172, "text": "This service recognizes what currency a banknote is (euro or usd dollar) and what denomination (5,10,20, ...). The social impact purpose is to help blind people, so I took care to make “real-life” training images holding the banknotes in my hand, sometimes folded, sometimes covering part of it." }, { "code": null, "e": 794, "s": 468, "text": "This post hopefully helps encourage others to learn Deep Learning. I’m using the amazing fast.ai online free course, which I very much recommend. As a testament to their pragmatic, top-down approach, this side-project is based on lesson 3. On their online forum you can find many more amazing applications by fellow students." }, { "code": null, "e": 837, "s": 794, "text": "My project is deployed on iris.brunosan.eu" }, { "code": null, "e": 866, "s": 837, "text": "Here’s an example inference:" }, { "code": null, "e": 1078, "s": 866, "text": "Amazingly, the fast, fun and easier part is the deep learning part (congrats fastai!), and the production server took roughly 10x time (I also had to learn some details about docker and serverless applications)." }, { "code": null, "e": 1462, "s": 1078, "text": "I found just a few efforts on identifying banknotes to help blind people. Some attempts use Computer Vision and “scale-invariant features” (with ~70% accuracy) and some use Machine Learning (with much higher accuracy). On the machine learning side, worth mentioning one by Microsoft research last year and one this year by a Nepali programmer, Kshitiz Rimal, with support from Intel:" }, { "code": null, "e": 2107, "s": 1462, "text": "Microsoft announced their version at an AI summit last year, “has been downloaded more than 100,000 times and has helped users with over three million tasks.” Their code is available here (sans training data). Basically, they use Keras and transfer learning, as we do in our course, but they don’t unfreeze for fine-tuning, and they create a “background” negative class with non-relevant pictures (I find odd to create a negative class... how can you learn “absence features”). They used a mobile-friendly pre-trained net “MobileNet” to run the detection on-device, and 250 images per banknote (+ plus data augmentation). They get 85% accuracy." }, { "code": null, "e": 2587, "s": 2107, "text": "The nepali version from Kshitiz: 14,000 images in total (taken by him), and gets 93% accuracy. He started with VGG19 and Keras for the neural net, and “Reach Native” for the app (This is a framework that can create both an iOS and Android app with the same code), but then he switched to Tensorflow with MobileNetV2 and native apps on each platform. This was a 6 months effort. Kudos!! He has the code for the training, AND the code for the apps, AND the training data on github." }, { "code": null, "e": 3304, "s": 2587, "text": "My goal was to replicate a similar solution, but I will only make a functioning website, not the app, nor on-device detection (I’m leaving that for now). However, I am going to use a different architecture. Since I want to do several currencies at once, I wanted to try multi-class classification. All the solutions I’ve seen use single-class detection, e.g. “`1 usd`”, and I wanted to break it into two classes, “`1`” and “`usd`”. The reason being that I think there are features to learn across currencies (all USD look similar) and also across denominations (e.g. the 5usd and 5eur have the number 5 in common). The commonalities should help the net reinforce those features for each class (e.g. a big digit “5”)." }, { "code": null, "e": 3425, "s": 3304, "text": "I basically followed the fast.ai course lesson on multi-classfor satellite detection, without really many modifications:" }, { "code": null, "e": 3661, "s": 3425, "text": "It is surprisingly hard to get images on single banknotes in real-life situations. After finishing this project I found the academic paper with Jordan currency I mentioned above, and the Nepali project which both link to their dataset." }, { "code": null, "e": 4089, "s": 3661, "text": "I decided to lean on Google Image searches and images from the European Central Bank and the US Mint, which I knew was going to give me unrealistically good images of banknotes. I also took some pictures myself with money I had home, for the low denominations (sadly I don’t have 100$ or 500eur lying around at home). In total I had between 14 and 30 images per banknote denomination. Not much at all. My image dataset is here." }, { "code": null, "e": 4228, "s": 4089, "text": "Since I didn’t have many images, I used data augmentation with widened parameters. (I wrongly added flips, it’s probably not a good idea):" }, { "code": null, "e": 4344, "s": 4228, "text": "tfms = get_transforms(do_flip=True,flip_vert=True, max_rotate=90, max_zoom=1.5, max_lighting=0.5, max_warp=0.5)" }, { "code": null, "e": 4416, "s": 4344, "text": "In the end, the dataset it looked like this during training/validation:" }, { "code": null, "e": 4481, "s": 4416, "text": "It’s amazing one can get such good results with that few images." }, { "code": null, "e": 5067, "s": 4481, "text": "I used 20% split for validation, and 256 pixel size for the images, and `resnet50` as the pre-trained model. With the resnet frozen, I did 15 epochs (2 minutes each) training the added top layers, and got an fbeta of `.087`, pretty good already. Then unfroze and did more training with sliced learning rates (bigger rates on the last layers) on 20 epochs, to get `fbeta=.098`. I was able to squeeze some more accuracy by freezing again the pre-trained model and doing some more epochs. The best was `fbeta=0.983`. No signs of over-fitting, and I used the default parameters of dropout." }, { "code": null, "e": 5155, "s": 5067, "text": "Exporting the model to PyTorch Torch script for deployment is just a few lines of code." }, { "code": null, "e": 5332, "s": 5155, "text": "I did spend some time testing the exported model, and looking at the outputs (both the raw activations and the softmax. I then realized that I could use it to infer confidence:" }, { "code": null, "e": 5429, "s": 5332, "text": "positive raw activations (which always translate to high softmax) usually meant high confidence." }, { "code": null, "e": 5587, "s": 5429, "text": "negative raw activations but non-zero softmax probabilities happened when there was no clear identification, so I could use them as “tentative alternatives”." }, { "code": null, "e": 5665, "s": 5587, "text": "e.g. let’s see this problematic image of a folded 5usd covering most of the 5" }, { "code": null, "e": 6070, "s": 5665, "text": "{‘probabilities’: ‘classes’: [‘1’, ‘10’, ‘100’, ‘20’, ‘200’, ‘5’, ‘50’, ‘500’, ‘euro’, ‘usd’] ‘softmax’: [‘0.00’, ‘0.00’, ‘0.01’, ‘0.04’, ‘0.01’, ‘0.20’, ‘0.00’, ‘0.00’, ‘0.00’, ‘99.73’], ‘output’: [‘-544.18’, ‘-616.93’, ‘-347.05’, ‘-246.08’, ‘-430.36’, ‘-83.76’, ‘-550.20’, ‘-655.22’, ‘-535.67’, ‘537.59’], ‘summary’: [‘usd’], ‘others’: {‘5’: ‘0.20%’, ‘20’: ‘0.04%’, ‘100’: ‘0.01%’, ‘200’: ‘0.01%’}}" }, { "code": null, "e": 6244, "s": 6070, "text": "Only the activations for class “`usd`” positive (last on the array), but the softmax also correctly brings the class “`5`” up, together with some doubt about the class `20`." }, { "code": null, "e": 6268, "s": 6244, "text": "This was the hard part." }, { "code": null, "e": 6328, "s": 6268, "text": "Basically you need 2 parts. The front-end and the back-end." }, { "code": null, "e": 6981, "s": 6328, "text": "The front-end is what people see, and what it does is give you a page to look at (I use Bootstrap for the UI), the code to select an image and finally displays the result. I added some code to the front-end to downsample the image on the client using Javascript. The reason being that camera pictures are quite heavy nowadays and all the inference process needs is a 256 pixel image. These are the 11 lines of code to downsample on the client. Since these are all static code, I used github pages on the same repository. To send the image to the server I pass them directly as DataURI instead of uploading them somewhere and then pulling it from there." }, { "code": null, "e": 7144, "s": 6981, "text": "The back-end is the one that receives the image, runs the inference code on our model, and returns the results. It’s the hard part of the hard part :), see below:" }, { "code": null, "e": 7404, "s": 7144, "text": "I first used Google Cloud Engine (GCE), as instructed here . My deployment code is here, and it includes code to upload and save a copy of the user images with the inferred class, so I can check false classifications use them for further training. Quite neat." }, { "code": null, "e": 7895, "s": 7404, "text": "Overall it was very easy to deploy. It basically creates a docker that deploys whatever code you need, and spins instances as needed. My problem was that the server is always running, actually 2 instances at least. GCE is meant for very high scalability and response, which is great, but it also meant I was paying all the time, even if no one is using it. I think it would have been 5–10$/month. If possible I wanted to deploy something that can remain online for long without paying much." }, { "code": null, "e": 8671, "s": 7895, "text": "I decided to switch to AWS Lambda (course instructions here). The process looks more complicated, but it’s actually not that hard, and the huge benefit is that you only pay for use. Moreover, for the usage level, we will be well within the free tier (except the cost of keeping the model on S3, which is minimal). My code to deploy is here. Since you are deploying a Torchscript model, you just need PyTorch dependencies, and AWS has a nice docker file with all that you need. I had to add some python libraries for formatting the output and logging and they were all there. That means your actual python code is minimal and you don’t need to bring fastai (On the course thread another student shared her deployment tricks IF you need to also bring fastai to the deployment)." }, { "code": null, "e": 8988, "s": 8671, "text": "Inference of the classification takes 0.2 seconds roughly, which is really fast, but the overall time for the user from selecting the image to getting the result can be up to 30s, or even fail. The extra time is partly uploading the image from the client to the server, and downscaling it before uploading if needed." }, { "code": null, "e": 9549, "s": 8988, "text": "In real-life tests, the response time was a median of 1s, which is acceptable... except for the first times, it sometimes took up to 30s to respond for the first time. I think this is called “cold start”, and corresponds to the time of AWS pulling the Lambda from storage. To minimize this impact I added some code that triggers a ping to the server as soon as you load the client page. That ping just returns “pong” so it doesn’t consume much billing time, but it makes the trick of triggering AWS to get the lambda function ready for the real inference call." }, { "code": null, "e": 9878, "s": 9549, "text": "This summer I have a small weekly section to talk about Impact Science on a spanish national radio, and I dedicated to talk in one episode about Artificial Intelligence and the impact on employment and Society. I presented this tool as an example. You can listen to it (in Spanish, timestamp 2h31m): Julia en la Onda, Onda Cero." }, { "code": null, "e": 9977, "s": 9878, "text": "I’d love to get your feedback and ideas. Or if you try to replicate it have problems, let me know." }, { "code": null, "e": 10039, "s": 9977, "text": "These are some points already on my mind for the next sprint:" }, { "code": null, "e": 10101, "s": 10039, "text": "Re-train the model using a mobile-friendly like “MobileNetV2”" }, { "code": null, "e": 10293, "s": 10101, "text": "Re-train the model using as many currencies (and coins) as possible. The benefits of multi-category classification to detect the denomination should become visible as you add more currencies." }, { "code": null, "e": 10380, "s": 10293, "text": "Add server code to upload a copy of the user images, as I did with the GCE deployment." }, { "code": null, "e": 10422, "s": 10380, "text": "Smartphone apps with on-device inference." } ]
C Standard Library - Quick Guide
The assert.h header file of the C Standard Library provides a macro called assert which can be used to verify assumptions made by the program and print a diagnostic message if this assumption is false. The defined macro assert refers to another macro NDEBUG which is not a part of <assert.h>. If NDEBUG is defined as a macro name in the source file, at the point where <assert.h> is included, the assert macro is defined as follows − #define assert(ignore) ((void)0) Following is the only function defined in the header assert.h − This is actually a macro and not a function, which can be used to add diagnostics in your C program. The ctype.h header file of the C Standard Library declares several functions that are useful for testing and mapping characters. All the functions accepts int as a parameter, whose value must be EOF or representable as an unsigned char. All the functions return non-zero (true) if the argument c satisfies the condition described, and zero(false) if not. Following are the functions defined in the header ctype.h − This function checks whether the passed character is alphanumeric. This function checks whether the passed character is alphabetic. This function checks whether the passed character is control character. This function checks whether the passed character is decimal digit. This function checks whether the passed character has graphical representation using locale. This function checks whether the passed character is lowercase letter. This function checks whether the passed character is printable. This function checks whether the passed character is a punctuation character. This function checks whether the passed character is white-space. This function checks whether the passed character is an uppercase letter. This function checks whether the passed character is a hexadecimal digit. The library also contains two conversion functions that accepts and returns an "int". This function converts uppercase letters to lowercase. This function converts lowercase letters to uppercase. Digits This is a set of whole numbers { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }. Hexadecimal digits This is the set of { 0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f }. Lowercase letters This is a set of lowercase letters { a b c d e f g h i j k l m n o p q r s t u v w x y z }. Uppercase letters This is a set of uppercase letters {A B C D E F G H I J K L M N O P Q R S T U V W X Y Z }. Letters This is a set of lowercase and uppercase letters. Alphanumeric characters This is a set of Digits, Lowercase letters and Uppercase letters. Punctuation characters This is a set of ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ Graphical characters This is a set of Alphanumeric characters and Punctuation characters. Space characters This is a set of tab, newline, vertical tab, form feed, carriage return, and space. Printable characters This is a set of Alphanumeric characters, Punctuation characters and Space characters. Control characters In ASCII, these characters have octal codes 000 through 037, and 177 (DEL). Blank characters These are spaces and tabs. Alphabetic characters This is a set of Lowercase letters and Uppercase letters. The errno.h header file of the C Standard Library defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong. This macro expands to a modifiable lvalue of type int, therefore it can be both read and modified by a program. The errno is set to zero at program startup. Certain functions of the standard C library modify its value to other than zero to signal some types of error. You can also modify its value or reset to zero at your convenience. The errno.h header file also defines a list of macros indicating different error codes, which will expand to integer constant expressions with type int. Following are the macros defined in the header errno.h − This is the macro set by system calls and some library functions in the event of an error to indicate what went wrong. This macro represents a domain error, which occurs if an input argument is outside the domain, over which the mathematical function is defined and errno is set to EDOM. This macro represents a range error, which occurs if an input argument is outside the range, over which the mathematical function is defined and errno is set to ERANGE. The float.h header file of the C Standard Library contains a set of various platform-dependent constants related to floating point values. These constants are proposed by ANSI C. They allow making more portable programs. Before checking all the constants, it is good to understand that floating-point number is composed of following four elements − S sign ( +/- ) b base or radix of the exponent representation, 2 for binary, 10 for decimal, 16 for hexadecimal, and so on... e exponent, an integer between a minimum emin and a maximum emax. p precision, the number of base-b digits in the significand. Based on the above 4 components, a floating point will have its value as follows − floating-point = ( S ) p x be or floating-point = (+/-) precision x baseexponent The following values are implementation-specific and defined with the #define directive, but these values may not be any lower than what is given here. Note that in all instances FLT refers to type float, DBL refers to double, and LDBL refers to long double. FLT_ROUNDS Defines the rounding mode for floating point addition and it can have any of the following values − -1 − indeterminable 0 − towards zero 1 − to nearest 2 − towards positive infinity 3 − towards negative infinity FLT_RADIX 2 This defines the base radix representation of the exponent. A base-2 is binary, base-10 is the normal decimal representation, base-16 is Hex. FLT_MANT_DIG DBL_MANT_DIG LDBL_MANT_DIG These macros define the number of digits in the number (in the FLT_RADIX base). FLT_DIG 6 DBL_DIG 10 LDBL_DIG 10 These macros define the maximum number decimal digits (base-10) that can be represented without change after rounding. FLT_MIN_EXP DBL_MIN_EXP LDBL_MIN_EXP These macros define the minimum negative integer value for an exponent in base FLT_RADIX. FLT_MIN_10_EXP -37 DBL_MIN_10_EXP -37 LDBL_MIN_10_EXP -37 These macros define the minimum negative integer value for an exponent in base 10. FLT_MAX_EXP DBL_MAX_EXP LDBL_MAX_EXP These macros define the maximum integer value for an exponent in base FLT_RADIX. FLT_MAX_10_EXP +37 DBL_MAX_10_EXP +37 LDBL_MAX_10_EXP +37 These macros define the maximum integer value for an exponent in base 10. FLT_MAX 1E+37 DBL_MAX 1E+37 LDBL_MAX 1E+37 These macros define the maximum finite floating-point value. FLT_EPSILON 1E-5 DBL_EPSILON 1E-9 LDBL_EPSILON 1E-9 These macros define the least significant digit representable. FLT_MIN 1E-37 DBL_MIN 1E-37 LDBL_MIN 1E-37 These macros define the minimum floating-point values. The following example shows the usage of few of the constants defined in float.h file. #include <stdio.h> #include <float.h> int main () { printf("The maximum value of float = %.10e\n", FLT_MAX); printf("The minimum value of float = %.10e\n", FLT_MIN); printf("The number of digits in the number = %.10e\n", FLT_MANT_DIG); } Let us compile and run the above program that will produce the following result − The maximum value of float = 3.4028234664e+38 The minimum value of float = 1.1754943508e-38 The number of digits in the number = 7.2996655210e-312 The limits.h header determines various properties of the various variable types. The macros defined in this header, limits the values of various variable types like char, int and long. These limits specify that a variable cannot store any value beyond these limits, for example an unsigned character can store up to a maximum value of 255. The following values are implementation-specific and defined with the #define directive, but these values may not be any lower than what is given here. The following example shows the usage of few of the constants defined in limits.h file. #include <stdio.h> #include <limits.h> int main() { printf("The number of bits in a byte %d\n", CHAR_BIT); printf("The minimum value of SIGNED CHAR = %d\n", SCHAR_MIN); printf("The maximum value of SIGNED CHAR = %d\n", SCHAR_MAX); printf("The maximum value of UNSIGNED CHAR = %d\n", UCHAR_MAX); printf("The minimum value of SHORT INT = %d\n", SHRT_MIN); printf("The maximum value of SHORT INT = %d\n", SHRT_MAX); printf("The minimum value of INT = %d\n", INT_MIN); printf("The maximum value of INT = %d\n", INT_MAX); printf("The minimum value of CHAR = %d\n", CHAR_MIN); printf("The maximum value of CHAR = %d\n", CHAR_MAX); printf("The minimum value of LONG = %ld\n", LONG_MIN); printf("The maximum value of LONG = %ld\n", LONG_MAX); return(0); } Let us compile and run the above program that will produce the following result − The maximum value of UNSIGNED CHAR = 255 The minimum value of SHORT INT = -32768 The maximum value of SHORT INT = 32767 The minimum value of INT = -2147483648 The maximum value of INT = 2147483647 The minimum value of CHAR = -128 The maximum value of CHAR = 127 The minimum value of LONG = -9223372036854775808 The maximum value of LONG = 9223372036854775807 The locale.h header defines the location specific settings, such as date formats and currency symbols. You will find several macros defined along with an important structure struct lconv and two important functions listed below. Following are the macros defined in the header and these macros will be used in two functions listed below − LC_ALL Sets everything. LC_COLLATE Affects strcoll and strxfrm functions. LC_CTYPE Affects all character functions. LC_MONETARY Affects the monetary information provided by localeconv function. LC_NUMERIC Affects decimal-point formatting and the information provided by localeconv function. LC_TIME Affects the strftime function. Following are the functions defined in the header locale.h − Sets or reads location dependent information. Sets or reads location dependent information. typedef struct { char *decimal_point; char *thousands_sep; char *grouping; char *int_curr_symbol; char *currency_symbol; char *mon_decimal_point; char *mon_thousands_sep; char *mon_grouping; char *positive_sign; char *negative_sign; char int_frac_digits; char frac_digits; char p_cs_precedes; char p_sep_by_space; char n_cs_precedes; char n_sep_by_space; char p_sign_posn; char n_sign_posn; } lconv Following is the description of each of the fields − decimal_point Decimal point character used for non-monetary values. thousands_sep Thousands place separator character used for non-monetary values. grouping A string that indicates the size of each group of digits in non-monetary quantities. Each character represents an integer value, which designates the number of digits in the current group. A value of 0 means that the previous value is to be used for the rest of the groups. int_curr_symbol It is a string of the international currency symbols used. The first three characters are those specified by ISO 4217:1987 and the fourth is the character, which separates the currency symbol from the monetary quantity. currency_symbol The local symbol used for currency. mon_decimal_point The decimal point character used for monetary values. mon_thousands_sep The thousands place grouping character used for monetary values. mon_grouping A string whose elements defines the size of the grouping of digits in monetary values. Each character represents an integer value which designates the number of digits in the current group. A value of 0 means that the previous value is to be used for the rest of the groups. positive_sign The character used for positive monetary values. negative_sign The character used for negative monetary values. int_frac_digits Number of digits to show after the decimal point in international monetary values. frac_digits Number of digits to show after the decimal point in monetary values. p_cs_precedes If equals to 1, then the currency_symbol appears before a positive monetary value. If equals to 0, then the currency_symbol appears after a positive monetary value. p_sep_by_space If equals to 1, then the currency_symbol is separated by a space from a positive monetary value. If equals to 0, then there is no space between the currency_symbol and a positive monetary value. n_cs_precedes If equals to 1, then the currency_symbol precedes a negative monetary value. If equals to 0, then the currency_symbol succeeds a negative monetary value. n_sep_by_space If equals to 1, then the currency_symbol is separated by a space from a negative monetary value. If equals to 0, then there is no space between the currency_symbol and a negative monetary value. p_sign_posn Represents the position of the positive_sign in a positive monetary value. n_sign_posn Represents the position of the negative_sign in a negative monetary value. The following values are used for p_sign_posn and n_sign_posn − The math.h header defines various mathematical functions and one macro. All the functions available in this library take double as an argument and return double as the result. There is only one macro defined in this library − HUGE_VAL This macro is used when the result of a function may not be representable as a floating point number. If magnitude of the correct result is too large to be represented, the function sets errno to ERANGE to indicate a range error, and returns a particular, very large value named by the macro HUGE_VAL or its negation (- HUGE_VAL). If the magnitude of the result is too small, a value of zero is returned instead. In this case, errno might or might not be set to ERANGE. Following are the functions defined in the header math.h − Returns the arc cosine of x in radians. Returns the arc sine of x in radians. Returns the arc tangent of x in radians. Returns the arc tangent in radians of y/x based on the signs of both values to determine the correct quadrant. Returns the cosine of a radian angle x. Returns the hyperbolic cosine of x. Returns the sine of a radian angle x. Returns the hyperbolic sine of x. Returns the hyperbolic tangent of x. Returns the value of e raised to the xth power. The returned value is the mantissa and the integer pointed to by exponent is the exponent. The resultant value is x = mantissa * 2 ^ exponent. Returns x multiplied by 2 raised to the power of exponent. Returns the natural logarithm (base-e logarithm) of x. Returns the common logarithm (base-10 logarithm) of x. The returned value is the fraction component (part after the decimal), and sets integer to the integer component. Returns x raised to the power of y. Returns the square root of x. Returns the smallest integer value greater than or equal to x. Returns the absolute value of x. Returns the largest integer value less than or equal to x. Returns the remainder of x divided by y. The setjmp.h header defines the macro setjmp(), one function longjmp(), and one variable type jmp_buf, for bypassing the normal function call and return discipline. Following is the variable type defined in the header setjmp.h − jmp_buf This is an array type used for holding information for macro setjmp() and function longjmp(). There is only one macro defined in this library − This macro saves the current environment into the variable environment for later use by the function longjmp(). If this macro returns directly from the macro invocation, it returns zero but if it returns from a longjmp() function call, then a non-zero value is returned. Following is the only one function defined in the header setjmp.h − This function restores the environment saved by the most recent call to setjmp() macro in the same invocation of the program with the corresponding jmp_buf argument. The signal.h header defines a variable type sig_atomic_t, two function calls, and several macros to handle different signals reported during a program's execution. Following is the variable type defined in the header signal.h − sig_atomic_t This is of int type and is used as a variable in a signal handler. This is an integral type of an object that can be accessed as an atomic entity, even in the presence of asynchronous signals. Following are the macros defined in the header signal.h and these macros will be used in two functions listed below. The SIG_ macros are used with the signal function to define signal functions. SIG_DFL Default signal handler. SIG_ERR Represents a signal error. SIG_IGN Signal ignore. The SIG macros are used to represent a signal number in the following conditions − SIGABRT Abnormal program termination. SIGFPE Floating-point error like division by zero. SIGILL Illegal operation. SIGINT Interrupt signal such as ctrl-C. SIGSEGV Invalid access to storage like segment violation. SIGTERM Termination request. Following are the functions defined in the header signal.h − This function sets a function to handle signal i.e. a signal handler. This function causes signal sig to be generated. The sig argument is compatible with the SIG macros. The stdarg.h header defines a variable type va_list and three macros which can be used to get the arguments in a function when the number of arguments are not known i.e. variable number of arguments. A function of variable arguments is defined with the ellipsis (,...) at the end of the parameter list. Following is the variable type defined in the header stdarg.h − va_list This is a type suitable for holding information needed by the three macros va_start(), va_arg() and va_end(). Following are the macros defined in the header stdarg.h − This macro initializes ap variable to be used with the va_arg and va_end macros. The last_arg is the last known fixed argument being passed to the function i.e. the argument before the ellipsis. This macro retrieves the next argument in the parameter list of the function with type type. This macro allows a function with variable arguments which used the va_start macro to return. If va_end is not called before returning from the function, the result is undefined. The stddef.h header defines various variable types and macros. Many of these definitions also appear in other headers. Following are the variable types defined in the header stddef.h − ptrdiff_t This is the signed integral type and is the result of subtracting two pointers. size_t This is the unsigned integral type and is the result of the sizeof keyword. wchar_t This is an integral type of the size of a wide character constant. Following are the macros defined in the header stddef.h − This macro is the value of a null pointer constant. This results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type. The stdio.h header defines three variable types, several macros, and various functions for performing input and output. Following are the variable types defined in the header stdio.h − size_t This is the unsigned integral type and is the result of the sizeof keyword. FILE This is an object type suitable for storing information for a file stream. fpos_t This is an object type suitable for storing any position in a file. Following are the macros defined in the header stdio.h − NULL This macro is the value of a null pointer constant. _IOFBF, _IOLBF and _IONBF These are the macros which expand to integral constant expressions with distinct values and suitable for the use as third argument to the setvbuf function. BUFSIZ This macro is an integer, which represents the size of the buffer used by the setbuf function. EOF This macro is a negative integer, which indicates that the end-of-file has been reached. FOPEN_MAX This macro is an integer, which represents the maximum number of files that the system can guarantee to be opened simultaneously. FILENAME_MAX This macro is an integer, which represents the longest length of a char array suitable for holding the longest possible filename. If the implementation imposes no limit, then this value should be the recommended maximum value. L_tmpnam This macro is an integer, which represents the longest length of a char array suitable for holding the longest possible temporary filename created by the tmpnam function. SEEK_CUR, SEEK_END, and SEEK_SET These macros are used in the fseek function to locate different positions in a file. TMP_MAX This macro is the maximum number of unique filenames that the function tmpnam can generate. stderr, stdin, and stdout These macros are pointers to FILE types which correspond to the standard error, standard input, and standard output streams. Following are the functions defined in the header stdio.h − Closes the stream. All buffers are flushed. Clears the end-of-file and error indicators for the given stream. Tests the end-of-file indicator for the given stream. Tests the error indicator for the given stream. Flushes the output buffer of a stream. Gets the current file position of the stream and writes it to pos. Opens the filename pointed to by filename using the given mode. Reads data from the given stream into the array pointed to by ptr. Associates a new filename with the given open stream and same time closing the old file in stream. Sets the file position of the stream to the given offset. The argument offset signifies the number of bytes to seek from the given whence position. Sets the file position of the given stream to the given position. The argument pos is a position given by the function fgetpos. Returns the current file position of the given stream. Writes data from the array pointed to by ptr to the given stream. Deletes the given filename so that it is no longer accessible. Causes the filename referred to, by old_filename to be changed to new_filename. Sets the file position to the beginning of the file of the given stream. Defines how a stream should be buffered. Another function to define how a stream should be buffered. Creates a temporary file in binary update mode (wb+). Generates and returns a valid temporary filename which does not exist. Sends formatted output to a stream. Sends formatted output to stdout. Sends formatted output to a string. Sends formatted output to a stream using an argument list. Sends formatted output to stdout using an argument list. Sends formatted output to a string using an argument list. Reads formatted input from a stream. Reads formatted input from stdin. Reads formatted input from a string. Gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. Reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first. Writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream. Writes a string to the specified stream up to but not including the null character. Gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. Gets a character (an unsigned char) from stdin. Reads a line from stdin and stores it into the string pointed to by, str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first. Writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream. Writes a character (an unsigned char) specified by the argument char to stdout. Writes a string to stdout up to but not including the null character. A newline character is appended to the output. Pushes the character char (an unsigned char) onto the specified stream so that the next character is read. Prints a descriptive error message to stderr. First the string str is printed followed by a colon and then a space. The stdlib.h header defines four variable types, several macros, and various functions for performing general functions. Following are the variable types defined in the header stdlib.h − size_t This is the unsigned integral type and is the result of the sizeof keyword. wchar_t This is an integer type of the size of a wide character constant. div_t This is the structure returned by the div function. ldiv_t This is the structure returned by the ldiv function. Following are the macros defined in the header stdlib.h − NULL This macro is the value of a null pointer constant. EXIT_FAILURE This is the value for the exit function to return in case of failure. EXIT_SUCCESS This is the value for the exit function to return in case of success. RAND_MAX This macro is the maximum value returned by the rand function. MB_CUR_MAX This macro is the maximum number of bytes in a multi-byte character set which cannot be larger than MB_LEN_MAX. Following are the functions defined in the header stlib.h − Converts the string pointed to, by the argument str to a floating-point number (type double). Converts the string pointed to, by the argument str to an integer (type int). Converts the string pointed to, by the argument str to a long integer (type long int). Converts the string pointed to, by the argument str to a floating-point number (type double). Converts the string pointed to, by the argument str to a long integer (type long int). Converts the string pointed to, by the argument str to an unsigned long integer (type unsigned long int). Allocates the requested memory and returns a pointer to it. Deallocates the memory previously allocated by a call to calloc, malloc, or realloc. Allocates the requested memory and returns a pointer to it. Attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc. Causes an abnormal program termination. Causes the specified function func to be called when the program terminates normally. Causes the program to terminate normally. Searches for the environment string pointed to by name and returns the associated value to the string. The command specified by string is passed to the host environment to be executed by the command processor. Performs a binary search. Sorts an array. Returns the absolute value of x. Divides numer (numerator) by denom (denominator). Returns the absolute value of x. Divides numer (numerator) by denom (denominator). Returns a pseudo-random number in the range of 0 to RAND_MAX. This function seeds the random number generator used by the function rand. Returns the length of a multibyte character pointed to by the argument str. Converts the string of multibyte characters pointed to by the argument str to the array pointed to by pwcs. Examines the multibyte character pointed to by the argument str. Converts the codes stored in the array pwcs to multibyte characters and stores them in the string str. Examines the code which corresponds to a multibyte character given by the argument wchar. The string.h header defines one variable type, one macro, and various functions for manipulating arrays of characters. Following is the variable type defined in the header string.h − size_t This is the unsigned integral type and is the result of the sizeof keyword. Following is the macro defined in the header string.h − NULL This macro is the value of a null pointer constant. Following are the functions defined in the header string.h − Searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to, by the argument str. Compares the first n bytes of str1 and str2. Copies n characters from src to dest. Another function to copy n characters from str2 to str1. Copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str. Appends the string pointed to, by src to the end of the string pointed to by dest. Appends the string pointed to, by src to the end of the string pointed to, by dest up to n characters long. Searches for the first occurrence of the character c (an unsigned char) in the string pointed to, by the argument str. Compares the string pointed to, by str1 to the string pointed to by str2. Compares at most the first n bytes of str1 and str2. Compares string str1 to str2. The result is dependent on the LC_COLLATE setting of the location. Copies the string pointed to, by src to dest. Copies up to n characters from the string pointed to, by src to dest. Calculates the length of the initial segment of str1 which consists entirely of characters not in str2. Searches an internal array for the error number errnum and returns a pointer to an error message string. Computes the length of the string str up to but not including the terminating null character. Finds the first character in the string str1 that matches any character specified in str2. Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str. Calculates the length of the initial segment of str1 which consists entirely of characters in str2. Finds the first occurrence of the entire string needle (not including the terminating null character) which appears in the string haystack. Breaks string str into a series of tokens separated by delim. Transforms the first n characters of the string src into current locale and places them in the string dest. The time.h header defines four variable types, two macro and various functions for manipulating date and time. Following are the variable types defined in the header time.h − size_t This is the unsigned integral type and is the result of the sizeof keyword. clock_t This is a type suitable for storing the processor time. time_t is This is a type suitable for storing the calendar time. struct tm This is a structure used to hold the time and date. The tm structure has the following definition − struct tm { int tm_sec; /* seconds, range 0 to 59 */ int tm_min; /* minutes, range 0 to 59 */ int tm_hour; /* hours, range 0 to 23 */ int tm_mday; /* day of the month, range 1 to 31 */ int tm_mon; /* month, range 0 to 11 */ int tm_year; /* The number of years since 1900 */ int tm_wday; /* day of the week, range 0 to 6 */ int tm_yday; /* day in the year, range 0 to 365 */ int tm_isdst; /* daylight saving time */ }; Following are the macros defined in the header time.h − NULL This macro is the value of a null pointer constant. CLOCKS_PER_SEC This macro represents the number of processor clocks per second. Following are the functions defined in the header time.h − Returns a pointer to a string which represents the day and time of the structure timeptr. Returns the processor clock time used since the beginning of an implementation defined era (normally the beginning of the program). Returns a string representing the localtime based on the argument timer. Returns the difference of seconds between time1 and time2 (time1-time2). The value of timer is broken up into the structure tm and expressed in Coordinated Universal Time (UTC) also known as Greenwich Mean Time (GMT). The value of timer is broken up into the structure tm and expressed in the local time zone. Converts the structure pointed to by timeptr into a time_t value according to the local time zone. Formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str. Calculates the current calender time and encodes it into time_t format. 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2209, "s": 2007, "text": "The assert.h header file of the C Standard Library provides a macro called assert which can be used to verify assumptions made by the program and print a diagnostic message if this assumption is false." }, { "code": null, "e": 2442, "s": 2209, "text": "The defined macro assert refers to another macro NDEBUG which is not a part of <assert.h>. If NDEBUG is defined as a macro name in the source file, at the point where <assert.h> is included, the assert macro is defined as follows −" }, { "code": null, "e": 2475, "s": 2442, "text": "#define assert(ignore) ((void)0)" }, { "code": null, "e": 2539, "s": 2475, "text": "Following is the only function defined in the header assert.h −" }, { "code": null, "e": 2640, "s": 2539, "text": "This is actually a macro and not a function, which can be used to add diagnostics in your C program." }, { "code": null, "e": 2769, "s": 2640, "text": "The ctype.h header file of the C Standard Library declares several functions that are useful for testing and mapping characters." }, { "code": null, "e": 2877, "s": 2769, "text": "All the functions accepts int as a parameter, whose value must be EOF or representable as an unsigned char." }, { "code": null, "e": 2995, "s": 2877, "text": "All the functions return non-zero (true) if the argument c satisfies the condition described, and zero(false) if not." }, { "code": null, "e": 3055, "s": 2995, "text": "Following are the functions defined in the header ctype.h −" }, { "code": null, "e": 3122, "s": 3055, "text": "This function checks whether the passed character is alphanumeric." }, { "code": null, "e": 3187, "s": 3122, "text": "This function checks whether the passed character is alphabetic." }, { "code": null, "e": 3259, "s": 3187, "text": "This function checks whether the passed character is control character." }, { "code": null, "e": 3328, "s": 3259, "text": "This function checks whether the passed character is decimal digit." }, { "code": null, "e": 3421, "s": 3328, "text": "This function checks whether the passed character has graphical representation using locale." }, { "code": null, "e": 3493, "s": 3421, "text": "This function checks whether the passed character is lowercase letter." }, { "code": null, "e": 3557, "s": 3493, "text": "This function checks whether the passed character is printable." }, { "code": null, "e": 3635, "s": 3557, "text": "This function checks whether the passed character is a punctuation character." }, { "code": null, "e": 3701, "s": 3635, "text": "This function checks whether the passed character is white-space." }, { "code": null, "e": 3775, "s": 3701, "text": "This function checks whether the passed character is an uppercase letter." }, { "code": null, "e": 3849, "s": 3775, "text": "This function checks whether the passed character is a hexadecimal digit." }, { "code": null, "e": 3935, "s": 3849, "text": "The library also contains two conversion functions that accepts and returns an \"int\"." }, { "code": null, "e": 3990, "s": 3935, "text": "This function converts uppercase letters to lowercase." }, { "code": null, "e": 4045, "s": 3990, "text": "This function converts lowercase letters to uppercase." }, { "code": null, "e": 4052, "s": 4045, "text": "Digits" }, { "code": null, "e": 4117, "s": 4052, "text": "This is a set of whole numbers { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }." }, { "code": null, "e": 4136, "s": 4117, "text": "Hexadecimal digits" }, { "code": null, "e": 4204, "s": 4136, "text": "This is the set of { 0 1 2 3 4 5 6 7 8 9 A B C D E F a b c d e f }." }, { "code": null, "e": 4222, "s": 4204, "text": "Lowercase letters" }, { "code": null, "e": 4314, "s": 4222, "text": "This is a set of lowercase letters { a b c d e f g h i j k l m n o p q r s t u v w x y z }." }, { "code": null, "e": 4332, "s": 4314, "text": "Uppercase letters" }, { "code": null, "e": 4423, "s": 4332, "text": "This is a set of uppercase letters {A B C D E F G H I J K L M N O P Q R S T U V W X Y Z }." }, { "code": null, "e": 4431, "s": 4423, "text": "Letters" }, { "code": null, "e": 4481, "s": 4431, "text": "This is a set of lowercase and uppercase letters." }, { "code": null, "e": 4505, "s": 4481, "text": "Alphanumeric characters" }, { "code": null, "e": 4571, "s": 4505, "text": "This is a set of Digits, Lowercase letters and Uppercase letters." }, { "code": null, "e": 4594, "s": 4571, "text": "Punctuation characters" }, { "code": null, "e": 4675, "s": 4594, "text": "This is a set of ! \" # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \\ ] ^ _ ` { | } ~" }, { "code": null, "e": 4696, "s": 4675, "text": "Graphical characters" }, { "code": null, "e": 4765, "s": 4696, "text": "This is a set of Alphanumeric characters and Punctuation characters." }, { "code": null, "e": 4782, "s": 4765, "text": "Space characters" }, { "code": null, "e": 4867, "s": 4782, "text": "This is a set of tab, newline, vertical tab, form feed, carriage return, and space." }, { "code": null, "e": 4888, "s": 4867, "text": "Printable characters" }, { "code": null, "e": 4975, "s": 4888, "text": "This is a set of Alphanumeric characters, Punctuation characters and Space characters." }, { "code": null, "e": 4994, "s": 4975, "text": "Control characters" }, { "code": null, "e": 5070, "s": 4994, "text": "In ASCII, these characters have octal codes 000 through 037, and 177 (DEL)." }, { "code": null, "e": 5087, "s": 5070, "text": "Blank characters" }, { "code": null, "e": 5114, "s": 5087, "text": "These are spaces and tabs." }, { "code": null, "e": 5136, "s": 5114, "text": "Alphabetic characters" }, { "code": null, "e": 5194, "s": 5136, "text": "This is a set of Lowercase letters and Uppercase letters." }, { "code": null, "e": 5502, "s": 5194, "text": "The errno.h header file of the C Standard Library defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong. This macro expands to a modifiable lvalue of type int, therefore it can be both read and modified by a program." }, { "code": null, "e": 5726, "s": 5502, "text": "The errno is set to zero at program startup. Certain functions of the standard C library modify its value to other than zero to signal some types of error. You can also modify its value or reset to zero at your convenience." }, { "code": null, "e": 5879, "s": 5726, "text": "The errno.h header file also defines a list of macros indicating different error codes, which will expand to integer constant expressions with type int." }, { "code": null, "e": 5936, "s": 5879, "text": "Following are the macros defined in the header errno.h −" }, { "code": null, "e": 6055, "s": 5936, "text": "This is the macro set by system calls and some library functions in the event of an error to indicate what went wrong." }, { "code": null, "e": 6224, "s": 6055, "text": "This macro represents a domain error, which occurs if an input argument is outside the domain, over which the mathematical function is defined and errno is set to EDOM." }, { "code": null, "e": 6393, "s": 6224, "text": "This macro represents a range error, which occurs if an input argument is outside the range, over which the mathematical function is defined and errno is set to ERANGE." }, { "code": null, "e": 6742, "s": 6393, "text": "The float.h header file of the C Standard Library contains a set of various platform-dependent constants related to floating point values. These constants are proposed by ANSI C. They allow making more portable programs. Before checking all the constants, it is good to understand that floating-point number is composed of following four elements −" }, { "code": null, "e": 6744, "s": 6742, "text": "S" }, { "code": null, "e": 6757, "s": 6744, "text": "sign ( +/- )" }, { "code": null, "e": 6759, "s": 6757, "text": "b" }, { "code": null, "e": 6868, "s": 6759, "text": "base or radix of the exponent representation, 2 for binary, 10 for decimal, 16 for hexadecimal, and so on..." }, { "code": null, "e": 6870, "s": 6868, "text": "e" }, { "code": null, "e": 6934, "s": 6870, "text": "exponent, an integer between a minimum emin and a maximum emax." }, { "code": null, "e": 6936, "s": 6934, "text": "p" }, { "code": null, "e": 6995, "s": 6936, "text": "precision, the number of base-b digits in the significand." }, { "code": null, "e": 7078, "s": 6995, "text": "Based on the above 4 components, a floating point will have its value as follows −" }, { "code": null, "e": 7162, "s": 7078, "text": "floating-point = ( S ) p x be\n\nor\n\nfloating-point = (+/-) precision x baseexponent\n" }, { "code": null, "e": 7421, "s": 7162, "text": "The following values are implementation-specific and defined with the #define directive, but these values may not be any lower than what is given here. Note that in all instances FLT refers to type float, DBL refers to double, and LDBL refers to long double." }, { "code": null, "e": 7432, "s": 7421, "text": "FLT_ROUNDS" }, { "code": null, "e": 7532, "s": 7432, "text": "Defines the rounding mode for floating point addition and it can have any of the following values −" }, { "code": null, "e": 7552, "s": 7532, "text": "-1 − indeterminable" }, { "code": null, "e": 7569, "s": 7552, "text": "0 − towards zero" }, { "code": null, "e": 7584, "s": 7569, "text": "1 − to nearest" }, { "code": null, "e": 7614, "s": 7584, "text": "2 − towards positive infinity" }, { "code": null, "e": 7644, "s": 7614, "text": "3 − towards negative infinity" }, { "code": null, "e": 7656, "s": 7644, "text": "FLT_RADIX 2" }, { "code": null, "e": 7798, "s": 7656, "text": "This defines the base radix representation of the exponent. A base-2 is binary, base-10 is the normal decimal representation, base-16 is Hex." }, { "code": null, "e": 7811, "s": 7798, "text": "FLT_MANT_DIG" }, { "code": null, "e": 7824, "s": 7811, "text": "DBL_MANT_DIG" }, { "code": null, "e": 7838, "s": 7824, "text": "LDBL_MANT_DIG" }, { "code": null, "e": 7918, "s": 7838, "text": "These macros define the number of digits in the number (in the FLT_RADIX base)." }, { "code": null, "e": 7928, "s": 7918, "text": "FLT_DIG 6" }, { "code": null, "e": 7939, "s": 7928, "text": "DBL_DIG 10" }, { "code": null, "e": 7951, "s": 7939, "text": "LDBL_DIG 10" }, { "code": null, "e": 8070, "s": 7951, "text": "These macros define the maximum number decimal digits (base-10) that can be represented without change after rounding." }, { "code": null, "e": 8082, "s": 8070, "text": "FLT_MIN_EXP" }, { "code": null, "e": 8094, "s": 8082, "text": "DBL_MIN_EXP" }, { "code": null, "e": 8107, "s": 8094, "text": "LDBL_MIN_EXP" }, { "code": null, "e": 8197, "s": 8107, "text": "These macros define the minimum negative integer value for an exponent in base FLT_RADIX." }, { "code": null, "e": 8216, "s": 8197, "text": "FLT_MIN_10_EXP -37" }, { "code": null, "e": 8235, "s": 8216, "text": "DBL_MIN_10_EXP -37" }, { "code": null, "e": 8255, "s": 8235, "text": "LDBL_MIN_10_EXP -37" }, { "code": null, "e": 8338, "s": 8255, "text": "These macros define the minimum negative integer value for an exponent in base 10." }, { "code": null, "e": 8350, "s": 8338, "text": "FLT_MAX_EXP" }, { "code": null, "e": 8362, "s": 8350, "text": "DBL_MAX_EXP" }, { "code": null, "e": 8375, "s": 8362, "text": "LDBL_MAX_EXP" }, { "code": null, "e": 8456, "s": 8375, "text": "These macros define the maximum integer value for an exponent in base FLT_RADIX." }, { "code": null, "e": 8475, "s": 8456, "text": "FLT_MAX_10_EXP +37" }, { "code": null, "e": 8494, "s": 8475, "text": "DBL_MAX_10_EXP +37" }, { "code": null, "e": 8514, "s": 8494, "text": "LDBL_MAX_10_EXP +37" }, { "code": null, "e": 8588, "s": 8514, "text": "These macros define the maximum integer value for an exponent in base 10." }, { "code": null, "e": 8602, "s": 8588, "text": "FLT_MAX 1E+37" }, { "code": null, "e": 8616, "s": 8602, "text": "DBL_MAX 1E+37" }, { "code": null, "e": 8631, "s": 8616, "text": "LDBL_MAX 1E+37" }, { "code": null, "e": 8692, "s": 8631, "text": "These macros define the maximum finite floating-point value." }, { "code": null, "e": 8709, "s": 8692, "text": "FLT_EPSILON 1E-5" }, { "code": null, "e": 8726, "s": 8709, "text": "DBL_EPSILON 1E-9" }, { "code": null, "e": 8744, "s": 8726, "text": "LDBL_EPSILON 1E-9" }, { "code": null, "e": 8807, "s": 8744, "text": "These macros define the least significant digit representable." }, { "code": null, "e": 8821, "s": 8807, "text": "FLT_MIN 1E-37" }, { "code": null, "e": 8835, "s": 8821, "text": "DBL_MIN 1E-37" }, { "code": null, "e": 8850, "s": 8835, "text": "LDBL_MIN 1E-37" }, { "code": null, "e": 8905, "s": 8850, "text": "These macros define the minimum floating-point values." }, { "code": null, "e": 8992, "s": 8905, "text": "The following example shows the usage of few of the constants defined in float.h file." }, { "code": null, "e": 9241, "s": 8992, "text": "#include <stdio.h>\n#include <float.h>\n\nint main () {\n printf(\"The maximum value of float = %.10e\\n\", FLT_MAX);\n printf(\"The minimum value of float = %.10e\\n\", FLT_MIN);\n\n printf(\"The number of digits in the number = %.10e\\n\", FLT_MANT_DIG);\n}" }, { "code": null, "e": 9323, "s": 9241, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 9471, "s": 9323, "text": "The maximum value of float = 3.4028234664e+38\nThe minimum value of float = 1.1754943508e-38\nThe number of digits in the number = 7.2996655210e-312\n" }, { "code": null, "e": 9656, "s": 9471, "text": "The limits.h header determines various properties of the various variable types. The macros defined in this header, limits the values of various variable types like char, int and long." }, { "code": null, "e": 9811, "s": 9656, "text": "These limits specify that a variable cannot store any value beyond these limits, for example an unsigned character can store up to a maximum value of 255." }, { "code": null, "e": 9963, "s": 9811, "text": "The following values are implementation-specific and defined with the #define directive, but these values may not be any lower than what is given here." }, { "code": null, "e": 10051, "s": 9963, "text": "The following example shows the usage of few of the constants defined in limits.h file." }, { "code": null, "e": 10849, "s": 10051, "text": "#include <stdio.h>\n#include <limits.h>\n\nint main() {\n\n printf(\"The number of bits in a byte %d\\n\", CHAR_BIT);\n\n printf(\"The minimum value of SIGNED CHAR = %d\\n\", SCHAR_MIN);\n printf(\"The maximum value of SIGNED CHAR = %d\\n\", SCHAR_MAX);\n printf(\"The maximum value of UNSIGNED CHAR = %d\\n\", UCHAR_MAX);\n\n printf(\"The minimum value of SHORT INT = %d\\n\", SHRT_MIN);\n printf(\"The maximum value of SHORT INT = %d\\n\", SHRT_MAX); \n\n printf(\"The minimum value of INT = %d\\n\", INT_MIN);\n printf(\"The maximum value of INT = %d\\n\", INT_MAX);\n\n printf(\"The minimum value of CHAR = %d\\n\", CHAR_MIN);\n printf(\"The maximum value of CHAR = %d\\n\", CHAR_MAX);\n\n printf(\"The minimum value of LONG = %ld\\n\", LONG_MIN);\n printf(\"The maximum value of LONG = %ld\\n\", LONG_MAX);\n \n return(0);\n}" }, { "code": null, "e": 10931, "s": 10849, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 11596, "s": 10931, "text": "The maximum value of UNSIGNED CHAR = 255 \nThe minimum value of SHORT INT = -32768 \nThe maximum value of SHORT INT = 32767 \nThe minimum value of INT = -2147483648 \nThe maximum value of INT = 2147483647 \nThe minimum value of CHAR = -128 \nThe maximum value of CHAR = 127 \nThe minimum value of LONG = -9223372036854775808 \nThe maximum value of LONG = 9223372036854775807\n" }, { "code": null, "e": 11825, "s": 11596, "text": "The locale.h header defines the location specific settings, such as date formats and currency symbols. You will find several macros defined along with an important structure struct lconv and two important functions listed below." }, { "code": null, "e": 11934, "s": 11825, "text": "Following are the macros defined in the header and these macros will be used in two functions listed below −" }, { "code": null, "e": 11941, "s": 11934, "text": "LC_ALL" }, { "code": null, "e": 11958, "s": 11941, "text": "Sets everything." }, { "code": null, "e": 11969, "s": 11958, "text": "LC_COLLATE" }, { "code": null, "e": 12008, "s": 11969, "text": "Affects strcoll and strxfrm functions." }, { "code": null, "e": 12017, "s": 12008, "text": "LC_CTYPE" }, { "code": null, "e": 12050, "s": 12017, "text": "Affects all character functions." }, { "code": null, "e": 12062, "s": 12050, "text": "LC_MONETARY" }, { "code": null, "e": 12128, "s": 12062, "text": "Affects the monetary information provided by localeconv function." }, { "code": null, "e": 12139, "s": 12128, "text": "LC_NUMERIC" }, { "code": null, "e": 12225, "s": 12139, "text": "Affects decimal-point formatting and the information provided by localeconv function." }, { "code": null, "e": 12233, "s": 12225, "text": "LC_TIME" }, { "code": null, "e": 12264, "s": 12233, "text": "Affects the strftime function." }, { "code": null, "e": 12325, "s": 12264, "text": "Following are the functions defined in the header locale.h −" }, { "code": null, "e": 12371, "s": 12325, "text": "Sets or reads location dependent information." }, { "code": null, "e": 12417, "s": 12371, "text": "Sets or reads location dependent information." }, { "code": null, "e": 12871, "s": 12417, "text": "typedef struct {\n char *decimal_point;\n char *thousands_sep;\n char *grouping;\t\n char *int_curr_symbol;\n char *currency_symbol;\n char *mon_decimal_point;\n char *mon_thousands_sep;\n char *mon_grouping;\n char *positive_sign;\n char *negative_sign;\n char int_frac_digits;\n char frac_digits;\n char p_cs_precedes;\n char p_sep_by_space;\n char n_cs_precedes;\n char n_sep_by_space;\n char p_sign_posn;\n char n_sign_posn;\n} lconv" }, { "code": null, "e": 12924, "s": 12871, "text": "Following is the description of each of the fields −" }, { "code": null, "e": 12938, "s": 12924, "text": "decimal_point" }, { "code": null, "e": 12992, "s": 12938, "text": "Decimal point character used for non-monetary values." }, { "code": null, "e": 13006, "s": 12992, "text": "thousands_sep" }, { "code": null, "e": 13072, "s": 13006, "text": "Thousands place separator character used for non-monetary values." }, { "code": null, "e": 13081, "s": 13072, "text": "grouping" }, { "code": null, "e": 13355, "s": 13081, "text": "A string that indicates the size of each group of digits in non-monetary quantities. Each character represents an integer value, which designates the number of digits in the current group. A value of 0 means that the previous value is to be used for the rest of the groups." }, { "code": null, "e": 13371, "s": 13355, "text": "int_curr_symbol" }, { "code": null, "e": 13591, "s": 13371, "text": "It is a string of the international currency symbols used. The first three characters are those specified by ISO 4217:1987 and the fourth is the character, which separates the currency symbol from the monetary quantity." }, { "code": null, "e": 13607, "s": 13591, "text": "currency_symbol" }, { "code": null, "e": 13643, "s": 13607, "text": "The local symbol used for currency." }, { "code": null, "e": 13661, "s": 13643, "text": "mon_decimal_point" }, { "code": null, "e": 13715, "s": 13661, "text": "The decimal point character used for monetary values." }, { "code": null, "e": 13733, "s": 13715, "text": "mon_thousands_sep" }, { "code": null, "e": 13798, "s": 13733, "text": "The thousands place grouping character used for monetary values." }, { "code": null, "e": 13811, "s": 13798, "text": "mon_grouping" }, { "code": null, "e": 14086, "s": 13811, "text": "A string whose elements defines the size of the grouping of digits in monetary values. Each character represents an integer value which designates the number of digits in the current group. A value of 0 means that the previous value is to be used for the rest of the groups." }, { "code": null, "e": 14100, "s": 14086, "text": "positive_sign" }, { "code": null, "e": 14149, "s": 14100, "text": "The character used for positive monetary values." }, { "code": null, "e": 14163, "s": 14149, "text": "negative_sign" }, { "code": null, "e": 14212, "s": 14163, "text": "The character used for negative monetary values." }, { "code": null, "e": 14228, "s": 14212, "text": "int_frac_digits" }, { "code": null, "e": 14311, "s": 14228, "text": "Number of digits to show after the decimal point in international monetary values." }, { "code": null, "e": 14323, "s": 14311, "text": "frac_digits" }, { "code": null, "e": 14392, "s": 14323, "text": "Number of digits to show after the decimal point in monetary values." }, { "code": null, "e": 14406, "s": 14392, "text": "p_cs_precedes" }, { "code": null, "e": 14571, "s": 14406, "text": "If equals to 1, then the currency_symbol appears before a positive monetary value. If equals to 0, then the currency_symbol appears after a positive monetary value." }, { "code": null, "e": 14586, "s": 14571, "text": "p_sep_by_space" }, { "code": null, "e": 14781, "s": 14586, "text": "If equals to 1, then the currency_symbol is separated by a space from a positive monetary value. If equals to 0, then there is no space between the currency_symbol and a positive monetary value." }, { "code": null, "e": 14795, "s": 14781, "text": "n_cs_precedes" }, { "code": null, "e": 14949, "s": 14795, "text": "If equals to 1, then the currency_symbol precedes a negative monetary value. If equals to 0, then the currency_symbol succeeds a negative monetary value." }, { "code": null, "e": 14964, "s": 14949, "text": "n_sep_by_space" }, { "code": null, "e": 15159, "s": 14964, "text": "If equals to 1, then the currency_symbol is separated by a space from a negative monetary value. If equals to 0, then there is no space between the currency_symbol and a negative monetary value." }, { "code": null, "e": 15171, "s": 15159, "text": "p_sign_posn" }, { "code": null, "e": 15246, "s": 15171, "text": "Represents the position of the positive_sign in a positive monetary value." }, { "code": null, "e": 15258, "s": 15246, "text": "n_sign_posn" }, { "code": null, "e": 15333, "s": 15258, "text": "Represents the position of the negative_sign in a negative monetary value." }, { "code": null, "e": 15397, "s": 15333, "text": "The following values are used for p_sign_posn and n_sign_posn −" }, { "code": null, "e": 15573, "s": 15397, "text": "The math.h header defines various mathematical functions and one macro. All the functions available in this library take double as an argument and return double as the result." }, { "code": null, "e": 15623, "s": 15573, "text": "There is only one macro defined in this library −" }, { "code": null, "e": 15632, "s": 15623, "text": "HUGE_VAL" }, { "code": null, "e": 15963, "s": 15632, "text": "This macro is used when the result of a function may not be representable as a floating point number. If magnitude of the correct result is too large to be represented, the function sets errno to ERANGE to indicate a range error, and returns a particular, very large value named by the macro HUGE_VAL or its negation (- HUGE_VAL)." }, { "code": null, "e": 16102, "s": 15963, "text": "If the magnitude of the result is too small, a value of zero is returned instead. In this case, errno might or might not be set to ERANGE." }, { "code": null, "e": 16161, "s": 16102, "text": "Following are the functions defined in the header math.h −" }, { "code": null, "e": 16201, "s": 16161, "text": "Returns the arc cosine of x in radians." }, { "code": null, "e": 16239, "s": 16201, "text": "Returns the arc sine of x in radians." }, { "code": null, "e": 16280, "s": 16239, "text": "Returns the arc tangent of x in radians." }, { "code": null, "e": 16391, "s": 16280, "text": "Returns the arc tangent in radians of y/x based on the signs of both values to determine the correct quadrant." }, { "code": null, "e": 16431, "s": 16391, "text": "Returns the cosine of a radian angle x." }, { "code": null, "e": 16467, "s": 16431, "text": "Returns the hyperbolic cosine of x." }, { "code": null, "e": 16505, "s": 16467, "text": "Returns the sine of a radian angle x." }, { "code": null, "e": 16539, "s": 16505, "text": "Returns the hyperbolic sine of x." }, { "code": null, "e": 16576, "s": 16539, "text": "Returns the hyperbolic tangent of x." }, { "code": null, "e": 16624, "s": 16576, "text": "Returns the value of e raised to the xth power." }, { "code": null, "e": 16767, "s": 16624, "text": "The returned value is the mantissa and the integer pointed to by exponent is the exponent. The resultant value is x = mantissa * 2 ^ exponent." }, { "code": null, "e": 16826, "s": 16767, "text": "Returns x multiplied by 2 raised to the power of exponent." }, { "code": null, "e": 16881, "s": 16826, "text": "Returns the natural logarithm (base-e logarithm) of x." }, { "code": null, "e": 16936, "s": 16881, "text": "Returns the common logarithm (base-10 logarithm) of x." }, { "code": null, "e": 17050, "s": 16936, "text": "The returned value is the fraction component (part after the decimal), and sets integer to the integer component." }, { "code": null, "e": 17086, "s": 17050, "text": "Returns x raised to the power of y." }, { "code": null, "e": 17116, "s": 17086, "text": "Returns the square root of x." }, { "code": null, "e": 17179, "s": 17116, "text": "Returns the smallest integer value greater than or equal to x." }, { "code": null, "e": 17212, "s": 17179, "text": "Returns the absolute value of x." }, { "code": null, "e": 17271, "s": 17212, "text": "Returns the largest integer value less than or equal to x." }, { "code": null, "e": 17312, "s": 17271, "text": "Returns the remainder of x divided by y." }, { "code": null, "e": 17477, "s": 17312, "text": "The setjmp.h header defines the macro setjmp(), one function longjmp(), and one variable type jmp_buf, for bypassing the normal function call and return discipline." }, { "code": null, "e": 17541, "s": 17477, "text": "Following is the variable type defined in the header setjmp.h −" }, { "code": null, "e": 17549, "s": 17541, "text": "jmp_buf" }, { "code": null, "e": 17643, "s": 17549, "text": "This is an array type used for holding information for macro setjmp() and function longjmp()." }, { "code": null, "e": 17693, "s": 17643, "text": "There is only one macro defined in this library −" }, { "code": null, "e": 17964, "s": 17693, "text": "This macro saves the current environment into the variable environment for later use by the function longjmp(). If this macro returns directly from the macro invocation, it returns zero but if it returns from a longjmp() function call, then a non-zero value is returned." }, { "code": null, "e": 18032, "s": 17964, "text": "Following is the only one function defined in the header setjmp.h −" }, { "code": null, "e": 18198, "s": 18032, "text": "This function restores the environment saved by the most recent call to setjmp() macro in the same invocation of the program with the corresponding jmp_buf argument." }, { "code": null, "e": 18362, "s": 18198, "text": "The signal.h header defines a variable type sig_atomic_t, two function calls, and several macros to handle different signals reported during a program's execution." }, { "code": null, "e": 18426, "s": 18362, "text": "Following is the variable type defined in the header signal.h −" }, { "code": null, "e": 18439, "s": 18426, "text": "sig_atomic_t" }, { "code": null, "e": 18632, "s": 18439, "text": "This is of int type and is used as a variable in a signal handler. This is an integral type of an object that can be accessed as an atomic entity, even in the presence of asynchronous signals." }, { "code": null, "e": 18827, "s": 18632, "text": "Following are the macros defined in the header signal.h and these macros will be used in two functions listed below. The SIG_ macros are used with the signal function to define signal functions." }, { "code": null, "e": 18835, "s": 18827, "text": "SIG_DFL" }, { "code": null, "e": 18859, "s": 18835, "text": "Default signal handler." }, { "code": null, "e": 18867, "s": 18859, "text": "SIG_ERR" }, { "code": null, "e": 18894, "s": 18867, "text": "Represents a signal error." }, { "code": null, "e": 18902, "s": 18894, "text": "SIG_IGN" }, { "code": null, "e": 18917, "s": 18902, "text": "Signal ignore." }, { "code": null, "e": 19000, "s": 18917, "text": "The SIG macros are used to represent a signal number in the following conditions −" }, { "code": null, "e": 19008, "s": 19000, "text": "SIGABRT" }, { "code": null, "e": 19038, "s": 19008, "text": "Abnormal program termination." }, { "code": null, "e": 19045, "s": 19038, "text": "SIGFPE" }, { "code": null, "e": 19089, "s": 19045, "text": "Floating-point error like division by zero." }, { "code": null, "e": 19096, "s": 19089, "text": "SIGILL" }, { "code": null, "e": 19115, "s": 19096, "text": "Illegal operation." }, { "code": null, "e": 19122, "s": 19115, "text": "SIGINT" }, { "code": null, "e": 19155, "s": 19122, "text": "Interrupt signal such as ctrl-C." }, { "code": null, "e": 19163, "s": 19155, "text": "SIGSEGV" }, { "code": null, "e": 19213, "s": 19163, "text": "Invalid access to storage like segment violation." }, { "code": null, "e": 19221, "s": 19213, "text": "SIGTERM" }, { "code": null, "e": 19242, "s": 19221, "text": "Termination request." }, { "code": null, "e": 19303, "s": 19242, "text": "Following are the functions defined in the header signal.h −" }, { "code": null, "e": 19373, "s": 19303, "text": "This function sets a function to handle signal i.e. a signal handler." }, { "code": null, "e": 19474, "s": 19373, "text": "This function causes signal sig to be generated. The sig argument is compatible with the SIG macros." }, { "code": null, "e": 19674, "s": 19474, "text": "The stdarg.h header defines a variable type va_list and three macros which can be used to get the arguments in a function when the number of arguments are not known i.e. variable number of arguments." }, { "code": null, "e": 19777, "s": 19674, "text": "A function of variable arguments is defined with the ellipsis (,...) at the end of the parameter list." }, { "code": null, "e": 19841, "s": 19777, "text": "Following is the variable type defined in the header stdarg.h −" }, { "code": null, "e": 19849, "s": 19841, "text": "va_list" }, { "code": null, "e": 19959, "s": 19849, "text": "This is a type suitable for holding information needed by the three macros va_start(), va_arg() and va_end()." }, { "code": null, "e": 20017, "s": 19959, "text": "Following are the macros defined in the header stdarg.h −" }, { "code": null, "e": 20212, "s": 20017, "text": "This macro initializes ap variable to be used with the va_arg and va_end macros. The last_arg is the last known fixed argument being passed to the function i.e. the argument before the ellipsis." }, { "code": null, "e": 20305, "s": 20212, "text": "This macro retrieves the next argument in the parameter list of the function with type type." }, { "code": null, "e": 20484, "s": 20305, "text": "This macro allows a function with variable arguments which used the va_start macro to return. If va_end is not called before returning from the function, the result is undefined." }, { "code": null, "e": 20603, "s": 20484, "text": "The stddef.h header defines various variable types and macros. Many of these definitions also appear in other headers." }, { "code": null, "e": 20669, "s": 20603, "text": "Following are the variable types defined in the header stddef.h −" }, { "code": null, "e": 20679, "s": 20669, "text": "ptrdiff_t" }, { "code": null, "e": 20759, "s": 20679, "text": "This is the signed integral type and is the result of subtracting two pointers." }, { "code": null, "e": 20766, "s": 20759, "text": "size_t" }, { "code": null, "e": 20842, "s": 20766, "text": "This is the unsigned integral type and is the result of the sizeof keyword." }, { "code": null, "e": 20850, "s": 20842, "text": "wchar_t" }, { "code": null, "e": 20917, "s": 20850, "text": "This is an integral type of the size of a wide character constant." }, { "code": null, "e": 20975, "s": 20917, "text": "Following are the macros defined in the header stddef.h −" }, { "code": null, "e": 21027, "s": 20975, "text": "This macro is the value of a null pointer constant." }, { "code": null, "e": 21255, "s": 21027, "text": "This results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type." }, { "code": null, "e": 21375, "s": 21255, "text": "The stdio.h header defines three variable types, several macros, and various functions for performing input and output." }, { "code": null, "e": 21440, "s": 21375, "text": "Following are the variable types defined in the header stdio.h −" }, { "code": null, "e": 21447, "s": 21440, "text": "size_t" }, { "code": null, "e": 21523, "s": 21447, "text": "This is the unsigned integral type and is the result of the sizeof keyword." }, { "code": null, "e": 21528, "s": 21523, "text": "FILE" }, { "code": null, "e": 21603, "s": 21528, "text": "This is an object type suitable for storing information for a file stream." }, { "code": null, "e": 21610, "s": 21603, "text": "fpos_t" }, { "code": null, "e": 21678, "s": 21610, "text": "This is an object type suitable for storing any position in a file." }, { "code": null, "e": 21735, "s": 21678, "text": "Following are the macros defined in the header stdio.h −" }, { "code": null, "e": 21740, "s": 21735, "text": "NULL" }, { "code": null, "e": 21792, "s": 21740, "text": "This macro is the value of a null pointer constant." }, { "code": null, "e": 21819, "s": 21792, "text": "_IOFBF, _IOLBF and _IONBF" }, { "code": null, "e": 21975, "s": 21819, "text": "These are the macros which expand to integral constant expressions with distinct values and suitable for the use as third argument to the setvbuf function." }, { "code": null, "e": 21982, "s": 21975, "text": "BUFSIZ" }, { "code": null, "e": 22077, "s": 21982, "text": "This macro is an integer, which represents the size of the buffer used by the setbuf function." }, { "code": null, "e": 22081, "s": 22077, "text": "EOF" }, { "code": null, "e": 22170, "s": 22081, "text": "This macro is a negative integer, which indicates that the end-of-file has been reached." }, { "code": null, "e": 22180, "s": 22170, "text": "FOPEN_MAX" }, { "code": null, "e": 22310, "s": 22180, "text": "This macro is an integer, which represents the maximum number of files that the system can guarantee to be opened simultaneously." }, { "code": null, "e": 22323, "s": 22310, "text": "FILENAME_MAX" }, { "code": null, "e": 22550, "s": 22323, "text": "This macro is an integer, which represents the longest length of a char array suitable for holding the longest possible filename. If the implementation imposes no limit, then this value should be the recommended maximum value." }, { "code": null, "e": 22559, "s": 22550, "text": "L_tmpnam" }, { "code": null, "e": 22730, "s": 22559, "text": "This macro is an integer, which represents the longest length of a char array suitable for holding the longest possible temporary filename created by the tmpnam function." }, { "code": null, "e": 22763, "s": 22730, "text": "SEEK_CUR, SEEK_END, and SEEK_SET" }, { "code": null, "e": 22848, "s": 22763, "text": "These macros are used in the fseek function to locate different positions in a file." }, { "code": null, "e": 22856, "s": 22848, "text": "TMP_MAX" }, { "code": null, "e": 22948, "s": 22856, "text": "This macro is the maximum number of unique filenames that the function tmpnam can generate." }, { "code": null, "e": 22974, "s": 22948, "text": "stderr, stdin, and stdout" }, { "code": null, "e": 23099, "s": 22974, "text": "These macros are pointers to FILE types which correspond to the standard error, standard input, and standard output streams." }, { "code": null, "e": 23159, "s": 23099, "text": "Following are the functions defined in the header stdio.h −" }, { "code": null, "e": 23203, "s": 23159, "text": "Closes the stream. All buffers are flushed." }, { "code": null, "e": 23269, "s": 23203, "text": "Clears the end-of-file and error indicators for the given stream." }, { "code": null, "e": 23323, "s": 23269, "text": "Tests the end-of-file indicator for the given stream." }, { "code": null, "e": 23371, "s": 23323, "text": "Tests the error indicator for the given stream." }, { "code": null, "e": 23410, "s": 23371, "text": "Flushes the output buffer of a stream." }, { "code": null, "e": 23477, "s": 23410, "text": "Gets the current file position of the stream and writes it to pos." }, { "code": null, "e": 23541, "s": 23477, "text": "Opens the filename pointed to by filename using the given mode." }, { "code": null, "e": 23608, "s": 23541, "text": "Reads data from the given stream into the array pointed to by ptr." }, { "code": null, "e": 23707, "s": 23608, "text": "Associates a new filename with the given open stream and same time closing the old file in stream." }, { "code": null, "e": 23855, "s": 23707, "text": "Sets the file position of the stream to the given offset. The argument offset signifies the number of bytes to seek from the given whence position." }, { "code": null, "e": 23983, "s": 23855, "text": "Sets the file position of the given stream to the given position. The argument pos is a position given by the function fgetpos." }, { "code": null, "e": 24038, "s": 23983, "text": "Returns the current file position of the given stream." }, { "code": null, "e": 24104, "s": 24038, "text": "Writes data from the array pointed to by ptr to the given stream." }, { "code": null, "e": 24167, "s": 24104, "text": "Deletes the given filename so that it is no longer accessible." }, { "code": null, "e": 24247, "s": 24167, "text": "Causes the filename referred to, by old_filename to be changed to new_filename." }, { "code": null, "e": 24320, "s": 24247, "text": "Sets the file position to the beginning of the file of the given stream." }, { "code": null, "e": 24361, "s": 24320, "text": "Defines how a stream should be buffered." }, { "code": null, "e": 24421, "s": 24361, "text": "Another function to define how a stream should be buffered." }, { "code": null, "e": 24475, "s": 24421, "text": "Creates a temporary file in binary update mode (wb+)." }, { "code": null, "e": 24546, "s": 24475, "text": "Generates and returns a valid temporary filename which does not exist." }, { "code": null, "e": 24582, "s": 24546, "text": "Sends formatted output to a stream." }, { "code": null, "e": 24616, "s": 24582, "text": "Sends formatted output to stdout." }, { "code": null, "e": 24652, "s": 24616, "text": "Sends formatted output to a string." }, { "code": null, "e": 24711, "s": 24652, "text": "Sends formatted output to a stream using an argument list." }, { "code": null, "e": 24768, "s": 24711, "text": "Sends formatted output to stdout using an argument list." }, { "code": null, "e": 24827, "s": 24768, "text": "Sends formatted output to a string using an argument list." }, { "code": null, "e": 24864, "s": 24827, "text": "Reads formatted input from a stream." }, { "code": null, "e": 24898, "s": 24864, "text": "Reads formatted input from stdin." }, { "code": null, "e": 24935, "s": 24898, "text": "Reads formatted input from a string." }, { "code": null, "e": 25056, "s": 24935, "text": "Gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream." }, { "code": null, "e": 25277, "s": 25056, "text": "Reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first." }, { "code": null, "e": 25422, "s": 25277, "text": "Writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream." }, { "code": null, "e": 25506, "s": 25422, "text": "Writes a string to the specified stream up to but not including the null character." }, { "code": null, "e": 25627, "s": 25506, "text": "Gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream." }, { "code": null, "e": 25675, "s": 25627, "text": "Gets a character (an unsigned char) from stdin." }, { "code": null, "e": 25859, "s": 25675, "text": "Reads a line from stdin and stores it into the string pointed to by, str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first." }, { "code": null, "e": 26004, "s": 25859, "text": "Writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream." }, { "code": null, "e": 26084, "s": 26004, "text": "Writes a character (an unsigned char) specified by the argument char to stdout." }, { "code": null, "e": 26201, "s": 26084, "text": "Writes a string to stdout up to but not including the null character. A newline character is appended to the output." }, { "code": null, "e": 26308, "s": 26201, "text": "Pushes the character char (an unsigned char) onto the specified stream so that the next character is read." }, { "code": null, "e": 26424, "s": 26308, "text": "Prints a descriptive error message to stderr. First the string str is printed followed by a colon and then a space." }, { "code": null, "e": 26545, "s": 26424, "text": "The stdlib.h header defines four variable types, several macros, and various functions for performing general functions." }, { "code": null, "e": 26611, "s": 26545, "text": "Following are the variable types defined in the header stdlib.h −" }, { "code": null, "e": 26618, "s": 26611, "text": "size_t" }, { "code": null, "e": 26694, "s": 26618, "text": "This is the unsigned integral type and is the result of the sizeof keyword." }, { "code": null, "e": 26702, "s": 26694, "text": "wchar_t" }, { "code": null, "e": 26768, "s": 26702, "text": "This is an integer type of the size of a wide character constant." }, { "code": null, "e": 26774, "s": 26768, "text": "div_t" }, { "code": null, "e": 26826, "s": 26774, "text": "This is the structure returned by the div function." }, { "code": null, "e": 26833, "s": 26826, "text": "ldiv_t" }, { "code": null, "e": 26886, "s": 26833, "text": "This is the structure returned by the ldiv function." }, { "code": null, "e": 26944, "s": 26886, "text": "Following are the macros defined in the header stdlib.h −" }, { "code": null, "e": 26949, "s": 26944, "text": "NULL" }, { "code": null, "e": 27001, "s": 26949, "text": "This macro is the value of a null pointer constant." }, { "code": null, "e": 27014, "s": 27001, "text": "EXIT_FAILURE" }, { "code": null, "e": 27084, "s": 27014, "text": "This is the value for the exit function to return in case of failure." }, { "code": null, "e": 27097, "s": 27084, "text": "EXIT_SUCCESS" }, { "code": null, "e": 27167, "s": 27097, "text": "This is the value for the exit function to return in case of success." }, { "code": null, "e": 27176, "s": 27167, "text": "RAND_MAX" }, { "code": null, "e": 27239, "s": 27176, "text": "This macro is the maximum value returned by the rand function." }, { "code": null, "e": 27250, "s": 27239, "text": "MB_CUR_MAX" }, { "code": null, "e": 27362, "s": 27250, "text": "This macro is the maximum number of bytes in a multi-byte character set which cannot be larger than MB_LEN_MAX." }, { "code": null, "e": 27422, "s": 27362, "text": "Following are the functions defined in the header stlib.h −" }, { "code": null, "e": 27516, "s": 27422, "text": "Converts the string pointed to, by the argument str to a floating-point number (type double)." }, { "code": null, "e": 27594, "s": 27516, "text": "Converts the string pointed to, by the argument str to an integer (type int)." }, { "code": null, "e": 27681, "s": 27594, "text": "Converts the string pointed to, by the argument str to a long integer (type long int)." }, { "code": null, "e": 27775, "s": 27681, "text": "Converts the string pointed to, by the argument str to a floating-point number (type double)." }, { "code": null, "e": 27862, "s": 27775, "text": "Converts the string pointed to, by the argument str to a long integer (type long int)." }, { "code": null, "e": 27968, "s": 27862, "text": "Converts the string pointed to, by the argument str to an unsigned long integer (type unsigned long int)." }, { "code": null, "e": 28028, "s": 27968, "text": "Allocates the requested memory and returns a pointer to it." }, { "code": null, "e": 28113, "s": 28028, "text": "Deallocates the memory previously allocated by a call to calloc, malloc, or realloc." }, { "code": null, "e": 28173, "s": 28113, "text": "Allocates the requested memory and returns a pointer to it." }, { "code": null, "e": 28290, "s": 28173, "text": "Attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc." }, { "code": null, "e": 28330, "s": 28290, "text": "Causes an abnormal program termination." }, { "code": null, "e": 28416, "s": 28330, "text": "Causes the specified function func to be called when the program terminates normally." }, { "code": null, "e": 28458, "s": 28416, "text": "Causes the program to terminate normally." }, { "code": null, "e": 28561, "s": 28458, "text": "Searches for the environment string pointed to by name and returns the associated value to the string." }, { "code": null, "e": 28668, "s": 28561, "text": "The command specified by string is passed to the host environment to be executed by the command processor." }, { "code": null, "e": 28694, "s": 28668, "text": "Performs a binary search." }, { "code": null, "e": 28710, "s": 28694, "text": "Sorts an array." }, { "code": null, "e": 28743, "s": 28710, "text": "Returns the absolute value of x." }, { "code": null, "e": 28793, "s": 28743, "text": "Divides numer (numerator) by denom (denominator)." }, { "code": null, "e": 28826, "s": 28793, "text": "Returns the absolute value of x." }, { "code": null, "e": 28876, "s": 28826, "text": "Divides numer (numerator) by denom (denominator)." }, { "code": null, "e": 28938, "s": 28876, "text": "Returns a pseudo-random number in the range of 0 to RAND_MAX." }, { "code": null, "e": 29013, "s": 28938, "text": "This function seeds the random number generator used by the function rand." }, { "code": null, "e": 29089, "s": 29013, "text": "Returns the length of a multibyte character pointed to by the argument str." }, { "code": null, "e": 29197, "s": 29089, "text": "Converts the string of multibyte characters pointed to by the argument str to the array pointed to by pwcs." }, { "code": null, "e": 29262, "s": 29197, "text": "Examines the multibyte character pointed to by the argument str." }, { "code": null, "e": 29365, "s": 29262, "text": "Converts the codes stored in the array pwcs to multibyte characters and stores them in the string str." }, { "code": null, "e": 29455, "s": 29365, "text": "Examines the code which corresponds to a multibyte character given by the argument wchar." }, { "code": null, "e": 29574, "s": 29455, "text": "The string.h header defines one variable type, one macro, and various functions for manipulating arrays of characters." }, { "code": null, "e": 29638, "s": 29574, "text": "Following is the variable type defined in the header string.h −" }, { "code": null, "e": 29645, "s": 29638, "text": "size_t" }, { "code": null, "e": 29721, "s": 29645, "text": "This is the unsigned integral type and is the result of the sizeof keyword." }, { "code": null, "e": 29777, "s": 29721, "text": "Following is the macro defined in the header string.h −" }, { "code": null, "e": 29782, "s": 29777, "text": "NULL" }, { "code": null, "e": 29834, "s": 29782, "text": "This macro is the value of a null pointer constant." }, { "code": null, "e": 29895, "s": 29834, "text": "Following are the functions defined in the header string.h −" }, { "code": null, "e": 30035, "s": 29895, "text": "Searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to, by the argument str." }, { "code": null, "e": 30080, "s": 30035, "text": "Compares the first n bytes of str1 and str2." }, { "code": null, "e": 30118, "s": 30080, "text": "Copies n characters from src to dest." }, { "code": null, "e": 30175, "s": 30118, "text": "Another function to copy n characters from str2 to str1." }, { "code": null, "e": 30290, "s": 30175, "text": "Copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str." }, { "code": null, "e": 30373, "s": 30290, "text": "Appends the string pointed to, by src to the end of the string pointed to by dest." }, { "code": null, "e": 30481, "s": 30373, "text": "Appends the string pointed to, by src to the end of the string pointed to, by dest up to n characters long." }, { "code": null, "e": 30600, "s": 30481, "text": "Searches for the first occurrence of the character c (an unsigned char) in the string pointed to, by the argument str." }, { "code": null, "e": 30674, "s": 30600, "text": "Compares the string pointed to, by str1 to the string pointed to by str2." }, { "code": null, "e": 30727, "s": 30674, "text": "Compares at most the first n bytes of str1 and str2." }, { "code": null, "e": 30824, "s": 30727, "text": "Compares string str1 to str2. The result is dependent on the LC_COLLATE setting of the location." }, { "code": null, "e": 30870, "s": 30824, "text": "Copies the string pointed to, by src to dest." }, { "code": null, "e": 30940, "s": 30870, "text": "Copies up to n characters from the string pointed to, by src to dest." }, { "code": null, "e": 31044, "s": 30940, "text": "Calculates the length of the initial segment of str1 which consists entirely of characters not in str2." }, { "code": null, "e": 31149, "s": 31044, "text": "Searches an internal array for the error number errnum and returns a pointer to an error message string." }, { "code": null, "e": 31243, "s": 31149, "text": "Computes the length of the string str up to but not including the terminating null character." }, { "code": null, "e": 31334, "s": 31243, "text": "Finds the first character in the string str1 that matches any character specified in str2." }, { "code": null, "e": 31451, "s": 31334, "text": "Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str." }, { "code": null, "e": 31551, "s": 31451, "text": "Calculates the length of the initial segment of str1 which consists entirely of characters in str2." }, { "code": null, "e": 31691, "s": 31551, "text": "Finds the first occurrence of the entire string needle (not including the terminating null character) which appears in the string haystack." }, { "code": null, "e": 31753, "s": 31691, "text": "Breaks string str into a series of tokens separated by delim." }, { "code": null, "e": 31861, "s": 31753, "text": "Transforms the first n characters of the string src into current locale and places them in the string dest." }, { "code": null, "e": 31972, "s": 31861, "text": "The time.h header defines four variable types, two macro and various functions for manipulating date and time." }, { "code": null, "e": 32036, "s": 31972, "text": "Following are the variable types defined in the header time.h −" }, { "code": null, "e": 32043, "s": 32036, "text": "size_t" }, { "code": null, "e": 32119, "s": 32043, "text": "This is the unsigned integral type and is the result of the sizeof keyword." }, { "code": null, "e": 32127, "s": 32119, "text": "clock_t" }, { "code": null, "e": 32183, "s": 32127, "text": "This is a type suitable for storing the processor time." }, { "code": null, "e": 32193, "s": 32183, "text": "time_t is" }, { "code": null, "e": 32248, "s": 32193, "text": "This is a type suitable for storing the calendar time." }, { "code": null, "e": 32258, "s": 32248, "text": "struct tm" }, { "code": null, "e": 32310, "s": 32258, "text": "This is a structure used to hold the time and date." }, { "code": null, "e": 32358, "s": 32310, "text": "The tm structure has the following definition −" }, { "code": null, "e": 32931, "s": 32358, "text": "struct tm {\n int tm_sec; /* seconds, range 0 to 59 */\n int tm_min; /* minutes, range 0 to 59 */\n int tm_hour; /* hours, range 0 to 23 */\n int tm_mday; /* day of the month, range 1 to 31 */\n int tm_mon; /* month, range 0 to 11 */\n int tm_year; /* The number of years since 1900 */\n int tm_wday; /* day of the week, range 0 to 6 */\n int tm_yday; /* day in the year, range 0 to 365 */\n int tm_isdst; /* daylight saving time */\n};" }, { "code": null, "e": 32987, "s": 32931, "text": "Following are the macros defined in the header time.h −" }, { "code": null, "e": 32992, "s": 32987, "text": "NULL" }, { "code": null, "e": 33044, "s": 32992, "text": "This macro is the value of a null pointer constant." }, { "code": null, "e": 33059, "s": 33044, "text": "CLOCKS_PER_SEC" }, { "code": null, "e": 33124, "s": 33059, "text": "This macro represents the number of processor clocks per second." }, { "code": null, "e": 33183, "s": 33124, "text": "Following are the functions defined in the header time.h −" }, { "code": null, "e": 33273, "s": 33183, "text": "Returns a pointer to a string which represents the day and time of the structure timeptr." }, { "code": null, "e": 33405, "s": 33273, "text": "Returns the processor clock time used since the beginning of an implementation defined era (normally the beginning of the program)." }, { "code": null, "e": 33478, "s": 33405, "text": "Returns a string representing the localtime based on the argument timer." }, { "code": null, "e": 33551, "s": 33478, "text": "Returns the difference of seconds between time1 and time2 (time1-time2)." }, { "code": null, "e": 33696, "s": 33551, "text": "The value of timer is broken up into the structure tm and expressed in Coordinated Universal Time (UTC) also known as Greenwich Mean Time (GMT)." }, { "code": null, "e": 33788, "s": 33696, "text": "The value of timer is broken up into the structure tm and expressed in the local time zone." }, { "code": null, "e": 33887, "s": 33788, "text": "Converts the structure pointed to by timeptr into a time_t value according to the local time zone." }, { "code": null, "e": 34014, "s": 33887, "text": "Formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str." }, { "code": null, "e": 34086, "s": 34014, "text": "Calculates the current calender time and encodes it into time_t format." }, { "code": null, "e": 34119, "s": 34086, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 34134, "s": 34119, "text": " Nishant Malik" }, { "code": null, "e": 34169, "s": 34134, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 34184, "s": 34169, "text": " Nishant Malik" }, { "code": null, "e": 34219, "s": 34184, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 34233, "s": 34219, "text": " Asif Hussain" }, { "code": null, "e": 34266, "s": 34233, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 34284, "s": 34266, "text": " Richa Maheshwari" }, { "code": null, "e": 34319, "s": 34284, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 34338, "s": 34319, "text": " Vandana Annavaram" }, { "code": null, "e": 34371, "s": 34338, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 34383, "s": 34371, "text": " Amit Diwan" }, { "code": null, "e": 34390, "s": 34383, "text": " Print" }, { "code": null, "e": 34401, "s": 34390, "text": " Add Notes" } ]
Time Series of Price Anomaly Detection with LSTM | by Susan Li | Towards Data Science
Autoencoders are an unsupervised learning technique, although they are trained using supervised learning methods. The goal is to minimize reconstruction error based on a loss function, such as the mean squared error. In this post, we will try to detect anomalies in the Johnson & Johnson’s historical stock price time series data with an LSTM autoencoder. The data can be downloaded from Yahoo Finance. The time period I selected was from 1985–09–04 to 2020–09–03. The steps we will follow to detect anomalies in Johnson & Johnson stock price data using an LSTM autoencoder: Train an LSTM autoencoder on the Johnson & Johnson’s stock price data from 1985–09–04 to 2013–09–03. We assume that there were no anomalies and they were normal.Using the LSTM autoencoder to reconstruct the error on the test data from 2013–09–04 to 2020–09–03.If the reconstruction error for the test data is above the threshold, we label the data point as an anomaly. Train an LSTM autoencoder on the Johnson & Johnson’s stock price data from 1985–09–04 to 2013–09–03. We assume that there were no anomalies and they were normal. Using the LSTM autoencoder to reconstruct the error on the test data from 2013–09–04 to 2020–09–03. If the reconstruction error for the test data is above the threshold, we label the data point as an anomaly. We will break down an LSTM autoencoder network to understand them layer-by-layer. Train test split Standardize the data Create sequences Convert input data into 3-D array combining TIME_STEPS. The shape of the array should be [samples, TIME_STEPS, features], as required for LSTM network. We want our network to have memory of 30 days, so we set TIME_STEPS=30. We define the reconstruction LSTM Autoencoder architecture that expects input sequences with 30 time steps and one feature and outputs a sequence with 30 time steps and one feature. RepeatVector() repeats the inputs 30 times. Set return_sequences=True, so the output will still be a sequence. TimeDistributed(Dense(X_train.shape[2])) is added at the end to get the output, where X_train.shape[2] is the number of features in the input data. plt.plot(history.history['loss'], label='Training loss')plt.plot(history.history['val_loss'], label='Validation loss')plt.legend(); model.evaluate(X_test, y_test) Find MAE loss on the training data. Make the max MAE loss value in the training data as the reconstruction error threshold. If the reconstruction loss for a data point in the test set is greater than this reconstruction error threshold value then we will label this data point as an anomaly. anomalies = test_score_df.loc[test_score_df['anomaly'] == True]anomalies.shape As you can see, there are 22 data points in the test set that exceeded the reconstruction error threshold. The model found that some low price anomalies in March and high price anomalies in April. As it was well documented that JNJ stock hit a 2020 low in March, but quickly reaccelerated to a high point less than a month later on bullish expectations for its coronavirus vaccine. Jupyter notebook can be found on Github. Have a great week!
[ { "code": null, "e": 388, "s": 171, "text": "Autoencoders are an unsupervised learning technique, although they are trained using supervised learning methods. The goal is to minimize reconstruction error based on a loss function, such as the mean squared error." }, { "code": null, "e": 527, "s": 388, "text": "In this post, we will try to detect anomalies in the Johnson & Johnson’s historical stock price time series data with an LSTM autoencoder." }, { "code": null, "e": 636, "s": 527, "text": "The data can be downloaded from Yahoo Finance. The time period I selected was from 1985–09–04 to 2020–09–03." }, { "code": null, "e": 746, "s": 636, "text": "The steps we will follow to detect anomalies in Johnson & Johnson stock price data using an LSTM autoencoder:" }, { "code": null, "e": 1115, "s": 746, "text": "Train an LSTM autoencoder on the Johnson & Johnson’s stock price data from 1985–09–04 to 2013–09–03. We assume that there were no anomalies and they were normal.Using the LSTM autoencoder to reconstruct the error on the test data from 2013–09–04 to 2020–09–03.If the reconstruction error for the test data is above the threshold, we label the data point as an anomaly." }, { "code": null, "e": 1277, "s": 1115, "text": "Train an LSTM autoencoder on the Johnson & Johnson’s stock price data from 1985–09–04 to 2013–09–03. We assume that there were no anomalies and they were normal." }, { "code": null, "e": 1377, "s": 1277, "text": "Using the LSTM autoencoder to reconstruct the error on the test data from 2013–09–04 to 2020–09–03." }, { "code": null, "e": 1486, "s": 1377, "text": "If the reconstruction error for the test data is above the threshold, we label the data point as an anomaly." }, { "code": null, "e": 1568, "s": 1486, "text": "We will break down an LSTM autoencoder network to understand them layer-by-layer." }, { "code": null, "e": 1585, "s": 1568, "text": "Train test split" }, { "code": null, "e": 1606, "s": 1585, "text": "Standardize the data" }, { "code": null, "e": 1623, "s": 1606, "text": "Create sequences" }, { "code": null, "e": 1775, "s": 1623, "text": "Convert input data into 3-D array combining TIME_STEPS. The shape of the array should be [samples, TIME_STEPS, features], as required for LSTM network." }, { "code": null, "e": 1847, "s": 1775, "text": "We want our network to have memory of 30 days, so we set TIME_STEPS=30." }, { "code": null, "e": 2029, "s": 1847, "text": "We define the reconstruction LSTM Autoencoder architecture that expects input sequences with 30 time steps and one feature and outputs a sequence with 30 time steps and one feature." }, { "code": null, "e": 2073, "s": 2029, "text": "RepeatVector() repeats the inputs 30 times." }, { "code": null, "e": 2140, "s": 2073, "text": "Set return_sequences=True, so the output will still be a sequence." }, { "code": null, "e": 2288, "s": 2140, "text": "TimeDistributed(Dense(X_train.shape[2])) is added at the end to get the output, where X_train.shape[2] is the number of features in the input data." }, { "code": null, "e": 2420, "s": 2288, "text": "plt.plot(history.history['loss'], label='Training loss')plt.plot(history.history['val_loss'], label='Validation loss')plt.legend();" }, { "code": null, "e": 2451, "s": 2420, "text": "model.evaluate(X_test, y_test)" }, { "code": null, "e": 2487, "s": 2451, "text": "Find MAE loss on the training data." }, { "code": null, "e": 2575, "s": 2487, "text": "Make the max MAE loss value in the training data as the reconstruction error threshold." }, { "code": null, "e": 2743, "s": 2575, "text": "If the reconstruction loss for a data point in the test set is greater than this reconstruction error threshold value then we will label this data point as an anomaly." }, { "code": null, "e": 2822, "s": 2743, "text": "anomalies = test_score_df.loc[test_score_df['anomaly'] == True]anomalies.shape" }, { "code": null, "e": 2929, "s": 2822, "text": "As you can see, there are 22 data points in the test set that exceeded the reconstruction error threshold." }, { "code": null, "e": 3204, "s": 2929, "text": "The model found that some low price anomalies in March and high price anomalies in April. As it was well documented that JNJ stock hit a 2020 low in March, but quickly reaccelerated to a high point less than a month later on bullish expectations for its coronavirus vaccine." } ]
time.perf_counter() function in Python
23 Mar, 2022 The time module provides various time-related functions. We must import the time module before using perf_counter() so we can access the function without throwing any errors.The perf_counter() function always returns the float value of time in seconds. Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid. In between this we can use time.sleep() and likewise functions.Code #1: Understand the usage of the perf_counter . Python3 # Python program to show time by perf_counter()from time import perf_counter # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / countert1_start = perf_counter() for i in range(n): t = int(input()) # user gave input n times if t % m == 0: print(t) # Stop the stopwatch / countert1_stop = perf_counter() print("Elapsed time:", t1_stop, t1_start) print("Elapsed time during the whole program in seconds:", t1_stop-t1_start) Output: pref_counter_ns(): It always gives the integer value of time in nanoseconds. Similar to perf_counter(), but return time as nanoseconds.Code #2: Usage of the perf_counter_ns and how to implement it. Python3 # Python program to show time by# perf_counter_ns()from time import perf_counter_ns # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / countert1_start = perf_counter_ns() for i in range(n): t = int(input()) # user gave input n times if t % m == 0: print(t) # Stop the stopwatch / countert1_stop = perf_counter_ns() print("Elapsed time:", t1_stop, 'ns', t1_start, 'ns') print("Elapsed time during the whole program in ns after n, m inputs:", t1_stop-t1_start, 'ns') Output: Compare both the outputs of the program as perf_counter() returns in seconds and pers_counter_ns() returns in nanoseconds.Advantages of perf_counter() : 1. perf_counter() will give you more precise value than time.clock() function . 2. From Python3.8 time.clock() function will be deleted and perf_counter will be used. 3. We can calculate float and integer both values of time in seconds and nanoseconds. bunnyram19 ign2ncwzil34u2ovu4yn62qdubl0y33ro9mqjcee Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Mar, 2022" }, { "code": null, "e": 766, "s": 52, "text": "The time module provides various time-related functions. We must import the time module before using perf_counter() so we can access the function without throwing any errors.The perf_counter() function always returns the float value of time in seconds. Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid. In between this we can use time.sleep() and likewise functions.Code #1: Understand the usage of the perf_counter . " }, { "code": null, "e": 774, "s": 766, "text": "Python3" }, { "code": "# Python program to show time by perf_counter()from time import perf_counter # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / countert1_start = perf_counter() for i in range(n): t = int(input()) # user gave input n times if t % m == 0: print(t) # Stop the stopwatch / countert1_stop = perf_counter() print(\"Elapsed time:\", t1_stop, t1_start) print(\"Elapsed time during the whole program in seconds:\", t1_stop-t1_start)", "e": 1303, "s": 774, "text": null }, { "code": null, "e": 1313, "s": 1303, "text": "Output: " }, { "code": null, "e": 1513, "s": 1313, "text": "pref_counter_ns(): It always gives the integer value of time in nanoseconds. Similar to perf_counter(), but return time as nanoseconds.Code #2: Usage of the perf_counter_ns and how to implement it. " }, { "code": null, "e": 1521, "s": 1513, "text": "Python3" }, { "code": "# Python program to show time by# perf_counter_ns()from time import perf_counter_ns # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / countert1_start = perf_counter_ns() for i in range(n): t = int(input()) # user gave input n times if t % m == 0: print(t) # Stop the stopwatch / countert1_stop = perf_counter_ns() print(\"Elapsed time:\", t1_stop, 'ns', t1_start, 'ns') print(\"Elapsed time during the whole program in ns after n, m inputs:\", t1_stop-t1_start, 'ns')", "e": 2060, "s": 1521, "text": null }, { "code": null, "e": 2070, "s": 2060, "text": "Output: " }, { "code": null, "e": 2478, "s": 2070, "text": "Compare both the outputs of the program as perf_counter() returns in seconds and pers_counter_ns() returns in nanoseconds.Advantages of perf_counter() : 1. perf_counter() will give you more precise value than time.clock() function . 2. From Python3.8 time.clock() function will be deleted and perf_counter will be used. 3. We can calculate float and integer both values of time in seconds and nanoseconds. " }, { "code": null, "e": 2489, "s": 2478, "text": "bunnyram19" }, { "code": null, "e": 2530, "s": 2489, "text": "ign2ncwzil34u2ovu4yn62qdubl0y33ro9mqjcee" }, { "code": null, "e": 2547, "s": 2530, "text": "Python-Functions" }, { "code": null, "e": 2554, "s": 2547, "text": "Python" } ]
GATE | GATE-CS-2001 | Question 47
28 Jun, 2021 Consider Peterson’s algorithm for mutual exclusion between two concurrent processes i and j. The program executed by process is shown below. repeat flag [i] = true; turn = j; while ( P ) do no-op; Enter critical section, perform actions, then exit critical section flag [ i ] = false; Perform other non-critical section actions. until false; For the program to guarantee mutual exclusion, the predicate P in the while loop should be.(A) flag[j] = true and turn = i(B) flag[j] = true and turn = j(C) flag[i] = true and turn = j(D) flag[i] = true and turn = iAnswer: (B)Explanation: See question 2 of https://www.geeksforgeeks.org/operating-systems-set-2/Quiz of this Question GATE-CS-2001 GATE-GATE-CS-2001 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 193, "s": 52, "text": "Consider Peterson’s algorithm for mutual exclusion between two concurrent processes i and j. The program executed by process is shown below." }, { "code": null, "e": 453, "s": 193, "text": " repeat \n flag [i] = true; \n turn = j; \n while ( P ) do no-op; \n Enter critical section, perform actions, then exit critical \n section \n flag [ i ] = false; \n Perform other non-critical section actions. \n until false; " }, { "code": null, "e": 786, "s": 453, "text": "For the program to guarantee mutual exclusion, the predicate P in the while loop should be.(A) flag[j] = true and turn = i(B) flag[j] = true and turn = j(C) flag[i] = true and turn = j(D) flag[i] = true and turn = iAnswer: (B)Explanation: See question 2 of https://www.geeksforgeeks.org/operating-systems-set-2/Quiz of this Question" }, { "code": null, "e": 799, "s": 786, "text": "GATE-CS-2001" }, { "code": null, "e": 817, "s": 799, "text": "GATE-GATE-CS-2001" }, { "code": null, "e": 822, "s": 817, "text": "GATE" } ]
Python | Replace tuple according to Nth tuple element
15 Oct, 2019 Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it’s application in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + enumerate()This task can be performed using the combination of loops and enumerate function which can help to access to the Nth element and then check and replace when the condition is satisfied. # Python3 code to demonstrate working of# Replace tuple according to Nth tuple element# Using loops + enumerate() # Initializing listtest_list = [('gfg', 1), ('was', 2), ('best', 3)] # printing original listprint("The original list is : " + str(test_list)) # Initializing change recordrepl_rec = ('is', 2) # Initializing N N = 1 # Replace tuple according to Nth tuple element# Using loops + enumerate()for key, val in enumerate(test_list): if val[N] == repl_rec[N]: test_list[key] = repl_rec break # printing resultprint("The tuple after replacement is : " + str(test_list)) The original list is : [('gfg', 1), ('was', 2), ('best', 3)] The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)] Method #2 : Using list comprehensionThis is the one-liner approach to solve this particular problem. In this, we just iterate the list element and keep matching the matching Nth element of tuple and perform replacement. # Python3 code to demonstrate working of# Replace tuple according to Nth tuple element# Using list comprehension # Initializing listtest_list = [('gfg', 1), ('was', 2), ('best', 3)] # printing original listprint("The original list is : " + str(test_list)) # Initializing change recordrepl_rec = ('is', 2) # Initializing N N = 1 # Replace tuple according to Nth tuple element# Using list comprehensionres = [repl_rec if sub[N] == repl_rec[N] else sub for sub in test_list] # printing resultprint("The tuple after replacement is : " + str(res)) The original list is : [('gfg', 1), ('was', 2), ('best', 3)] The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Oct, 2019" }, { "code": null, "e": 333, "s": 28, "text": "Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it’s application in web development domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 554, "s": 333, "text": "Method #1 : Using loop + enumerate()This task can be performed using the combination of loops and enumerate function which can help to access to the Nth element and then check and replace when the condition is satisfied." }, { "code": "# Python3 code to demonstrate working of# Replace tuple according to Nth tuple element# Using loops + enumerate() # Initializing listtest_list = [('gfg', 1), ('was', 2), ('best', 3)] # printing original listprint(\"The original list is : \" + str(test_list)) # Initializing change recordrepl_rec = ('is', 2) # Initializing N N = 1 # Replace tuple according to Nth tuple element# Using loops + enumerate()for key, val in enumerate(test_list): if val[N] == repl_rec[N]: test_list[key] = repl_rec break # printing resultprint(\"The tuple after replacement is : \" + str(test_list))", "e": 1152, "s": 554, "text": null }, { "code": null, "e": 1284, "s": 1152, "text": "The original list is : [('gfg', 1), ('was', 2), ('best', 3)]\nThe tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]\n" }, { "code": null, "e": 1506, "s": 1286, "text": "Method #2 : Using list comprehensionThis is the one-liner approach to solve this particular problem. In this, we just iterate the list element and keep matching the matching Nth element of tuple and perform replacement." }, { "code": "# Python3 code to demonstrate working of# Replace tuple according to Nth tuple element# Using list comprehension # Initializing listtest_list = [('gfg', 1), ('was', 2), ('best', 3)] # printing original listprint(\"The original list is : \" + str(test_list)) # Initializing change recordrepl_rec = ('is', 2) # Initializing N N = 1 # Replace tuple according to Nth tuple element# Using list comprehensionres = [repl_rec if sub[N] == repl_rec[N] else sub for sub in test_list] # printing resultprint(\"The tuple after replacement is : \" + str(res))", "e": 2055, "s": 1506, "text": null }, { "code": null, "e": 2187, "s": 2055, "text": "The original list is : [('gfg', 1), ('was', 2), ('best', 3)]\nThe tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]\n" }, { "code": null, "e": 2208, "s": 2187, "text": "Python list-programs" }, { "code": null, "e": 2215, "s": 2208, "text": "Python" }, { "code": null, "e": 2231, "s": 2215, "text": "Python Programs" } ]
Difference between <div> and <span> Tag in HTML
16 May, 2022 Both the tags (<div> and <span>) are used to represent the part of the webpage, <div> tag is used a as block part of the webpage and <span> tag is used as a inline part of the webpage like below: <div>A Computer Science Portal for Geeks <span>GeeksforGeeks</span></div> HTML <div> tag: The div tag is known as Division tag. The div tag is used in HTML to make divisions of content on the web page like (text, images, header, footer, navigation bar, etc). Div tag has both opening(<div>) and closing (</div>) tags and it is mandatory to close the tag. As we know Div tag is a block-level tag. In this example, the div tag contains the entire width. It will be displayed div tag each time on a new line, not on the same line. Example: html <!DOCTYPE html><html> <head> <title>Div tag</title> <style> div { color: white; background-color: #009900; margin: 2px; font-size: 25px; } </style></head> <body> <div> div tag </div> <div> div tag </div> <div> div tag </div> <div> div tag </div></body> </html> Output: HTML <span> tag: The HTML span element is a generic inline container for inline elements and content. It used to group elements for styling purposes (by using the class or id attributes). A better way to use it when no other semantic element is available. The span tag is very similar to the div tag, but div is a block-level tag and span is an inline tag. Example: html <!DOCTYPE html><html> <head> <title>span tag</title></head> <body> <h2>Welcome To GFG</h2> <!-- Inside paragraph applying span tag with different style --> <p><span style="background-color:lightgreen"> GeeksforGeeks</span> is A Computer Science Portal where you can<span style="color:blue;"> Publish</span> your own <span style="background-color:lightblue;">articles</span> and share your knowledge with the world!! </p></body> </html> Output: Differences between <div> and <span> tag: HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. adnanirshad158 robertschv tejendrasrajawat HTML-Misc HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS HTTP headers | Content-Type Installation of Node.js on Linux 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
[ { "code": null, "e": 53, "s": 25, "text": "\n16 May, 2022" }, { "code": null, "e": 251, "s": 53, "text": "Both the tags (<div> and <span>) are used to represent the part of the webpage, <div> tag is used a as block part of the webpage and <span> tag is used as a inline part of the webpage like below: " }, { "code": null, "e": 326, "s": 251, "text": " <div>A Computer Science Portal for Geeks <span>GeeksforGeeks</span></div>" }, { "code": null, "e": 781, "s": 326, "text": "HTML <div> tag: The div tag is known as Division tag. The div tag is used in HTML to make divisions of content on the web page like (text, images, header, footer, navigation bar, etc). Div tag has both opening(<div>) and closing (</div>) tags and it is mandatory to close the tag. As we know Div tag is a block-level tag. In this example, the div tag contains the entire width. It will be displayed div tag each time on a new line, not on the same line. " }, { "code": null, "e": 792, "s": 781, "text": "Example: " }, { "code": null, "e": 797, "s": 792, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Div tag</title> <style> div { color: white; background-color: #009900; margin: 2px; font-size: 25px; } </style></head> <body> <div> div tag </div> <div> div tag </div> <div> div tag </div> <div> div tag </div></body> </html>", "e": 1142, "s": 797, "text": null }, { "code": null, "e": 1152, "s": 1142, "text": "Output: " }, { "code": null, "e": 1511, "s": 1152, "text": "HTML <span> tag: The HTML span element is a generic inline container for inline elements and content. It used to group elements for styling purposes (by using the class or id attributes). A better way to use it when no other semantic element is available. The span tag is very similar to the div tag, but div is a block-level tag and span is an inline tag. " }, { "code": null, "e": 1522, "s": 1511, "text": "Example: " }, { "code": null, "e": 1527, "s": 1522, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>span tag</title></head> <body> <h2>Welcome To GFG</h2> <!-- Inside paragraph applying span tag with different style --> <p><span style=\"background-color:lightgreen\"> GeeksforGeeks</span> is A Computer Science Portal where you can<span style=\"color:blue;\"> Publish</span> your own <span style=\"background-color:lightblue;\">articles</span> and share your knowledge with the world!! </p></body> </html>", "e": 2018, "s": 1527, "text": null }, { "code": null, "e": 2028, "s": 2018, "text": "Output: " }, { "code": null, "e": 2072, "s": 2028, "text": "Differences between <div> and <span> tag: " }, { "code": null, "e": 2268, "s": 2074, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 2285, "s": 2270, "text": "adnanirshad158" }, { "code": null, "e": 2296, "s": 2285, "text": "robertschv" }, { "code": null, "e": 2313, "s": 2296, "text": "tejendrasrajawat" }, { "code": null, "e": 2323, "s": 2313, "text": "HTML-Misc" }, { "code": null, "e": 2328, "s": 2323, "text": "HTML" }, { "code": null, "e": 2345, "s": 2328, "text": "Web Technologies" }, { "code": null, "e": 2372, "s": 2345, "text": "Web technologies Questions" }, { "code": null, "e": 2377, "s": 2372, "text": "HTML" }, { "code": null, "e": 2475, "s": 2377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2499, "s": 2475, "text": "REST API (Introduction)" }, { "code": null, "e": 2549, "s": 2499, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2586, "s": 2549, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2625, "s": 2586, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2653, "s": 2625, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 2686, "s": 2653, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2747, "s": 2686, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2790, "s": 2747, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2862, "s": 2790, "text": "Differences between Functional Components and Class Components in React" } ]
Preorder to Postorder | Practice | GeeksforGeeks
Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal. In Pre-Order traversal, the root node is visited before the left child and right child nodes. Post-order traversal is one of the multiple methods to traverse a tree. Example 1: Input: N = 5 arr[] = {40,30,35,80,100} Output: 35 30 100 80 40 Explanation: PreOrder: 40 30 35 80 100 InOrder: 30 35 40 80 100 Therefore, the BST will be: 40 / \ 30 80 \ \ 35 100 Hence, the postOrder traversal will be: 35 30 100 80 40 Example 2: Input: N = 8 arr[] = {40,30,32,35,80,90,100,120} Output: 35 32 30 120 100 90 80 40 Your Task: You need to complete the given function and return the root of the tree. The driver code will then use this root to print the post order traversal. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= N <= 103 1 <= arr[i] <= 104 0 sajalsa8pt2 days ago public static Node post_order(int pre[], int size) { //Your code here Node root = new Node(pre[0]); for(int i=1;i<pre.length;i++) insert(root,pre[i]); return root; } public static void insert(Node root, int i) { Node prev = null, curr = root, temp = new Node(i); while(curr!=null) { prev = curr; if(curr.data>i) curr = curr.left; else curr = curr.right; } if(prev.data>i) prev.left = temp; else prev.right = temp; } 0 2019umt13465 days ago class Solution{public: Node* constructTree(int pre[],int &preIndex,int key,int min,int max,int size) { if(preIndex>=size) return NULL; Node* root=NULL; if(key>min && key<max) { root=newNode(key); preIndex++; if(preIndex<size) { root->left=constructTree(pre,preIndex,pre[preIndex],min,key,size); } if(preIndex<size) { root->right=constructTree(pre,preIndex,pre[preIndex],key,max,size); } } return root; } //Function that constructs BST from its preorder traversal. Node* post_order(int pre[], int size) { int preorderIndex=0; return constructTree(pre,preorderIndex,pre[0],INT_MIN,INT_MAX,size); //code here }}; +1 mahesh_phutane1 week ago Java Solution: TC → O(n) SC → O(1) public static Node solve(int[] pre,int size,int min,int max){ if(idx>size) return null; if(pre[idx]<min || pre[idx]>max) return null; Node root = new Node(pre[idx++]); root.left = solve(pre,size,min,root.data); root.right = solve(pre,size,root.data,max); return root; } static int idx = 0; public static Node post_order(int pre[], int size) { idx = 0; return solve(pre,size-1,Integer.MIN_VALUE,Integer.MAX_VALUE); } +1 prashr11 week ago Recursive Solution: class Solution{ public: Node* po_Util(int pre[],int start,int end) { Node* root=newNode(pre[start]); int x=pre[start],s=start; if(start==end) { root->left=root->right=NULL; return root; } start++; while(start<=end && pre[start]<x) start++; if(start>end) { root->right=NULL; root->left=po_Util(pre,s+1,end); } else if(start==s+1) { root->left=NULL; root->right=po_Util(pre,start,end); } else { root->left=po_Util(pre,s+1,start-1); root->right=po_Util(pre,start,end); } return root; } //Function that constructs BST from its preorder traversal. Node* post_order(int pre[], int size) { //code here return po_Util(pre,0,size-1); } }; 0 irockstarpiyush1 week ago C++ -Simple Solution Node* f(int pre[], int &ind, int n, int mn, int mx) { if(ind >= n){ return NULL; } if(!(pre[ind] > mn && pre[ind] < mx)){ return NULL; } Node * node = newNode(pre[ind]); ind++; node->left = f(pre, ind, n, mn, node->data); node->right = f(pre, ind, n, node->data, mx); return node; } Node* post_order(int pre[], int size) { int ind = 0; Node* root = f(pre, ind, size, INT_MIN, INT_MAX); return root; } 0 yuvrajranabtcse202 weeks ago c++ 2 ways soln Node* makeprebystack(int pre[],int size){ stack<Node*> ques; int i=1; Node* root= newNode(pre[0]); Node* p=root; while(i<size){ if(pre[i]<p->data){ p->left=newNode(pre[i++]); ques.push(p); p=p->left; } else if(pre[i]>p->data){ if(ques.empty()){ p->right=newNode(pre[i++]); p=p->right; } else if(ques.top()->data>pre[i]){ p->right=newNode(pre[i++]); p=p->right; } else{ p=ques.top(); ques.pop(); } } } return root; } /*-------------------------------------------------------------*/Node* makeprebyiteration(int pre[],int size,int &i,int start,int end){ if(i>=size)return NULL; Node* root=NULL; int key=pre[i]; if((key>start)&&(key<end)){ Node* root=newNode(key); i++; root->left=makeprebyiteration(pre,size,i,start,key); root->right=makeprebyiteration(pre,size,i,key,end); return root; } return root;} Node* post_order(int pre[], int size) { int i=0; return makeprebyiteration(pre,size,i,INT_MIN,INT_MAX);}}; 0 insanelion2 weeks ago public static Node post_order(int pre[], int size) { //Your code here Node root = new Node(pre[0]); Node cur = root; Stack<Node> st = new Stack<>(); st.push(root); for(int i=1;i<size;i++) { Node node = new Node(pre[i]); if(st.peek().data<pre[i]) { while(!st.isEmpty()&&st.peek().data<pre[i]) { cur = st.pop(); } cur.right = node; cur = cur.right; } else { cur.left = node; cur = cur.left; } st.push(node); } return root; } 0 thakursahabsingh122 weeks ago Java, public static Node post_order(int pre[], int size) { //Your code here return helper(pre, 0, pre.length-1);} public static Node helper(int[] pre, int l, int r){ if(l>r){ return null; } Node root= new Node(pre[l]); int i; for(i=l;i<=r;i++){ if(pre[i]>root.data){ break; } } root.left = helper(pre, l+1, i-1); root.right = helper(pre, i, r); return root; } +1 bagheldikshant1232 weeks ago java Easy Solution using Recursion public static Node post_order(int pre[], int size) { return helper(pre, 0, pre.length-1); } public static Node helper(int[] pre, int l, int r){ if(l>r){ return null; } Node root= new Node(pre[l]); int i; for(i=l;i<=r;i++){ if(pre[i]>root.data){ break; } } root.left = helper(pre, l+1, i-1); root.right = helper(pre, i, r); return root; } +3 avinashdhn19043 weeks ago class Solution{ public: //Function that constructs BST from its preorder traversal. Node *build_tree(int pre[],int n,int &i,int mini,int maxi){ if(i>=n)return NULL; if(pre[i]<mini||pre[i]>maxi)return NULL; Node *root=(Node *)malloc(sizeof(Node)); root->data=pre[i++]; root->left=build_tree(pre,n,i,mini,root->data); root->right=build_tree(pre,n,i,root->data,maxi); return root; } Node* post_order(int pre[], int size) { int i=0,mini=INT_MIN,maxi=INT_MAX; Node* root= build_tree(pre,size,i,mini,maxi); return root; } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 510, "s": 226, "text": "Given an array arr[] of N nodes representing preorder traversal of BST. The task is to print its postorder traversal.\nIn Pre-Order traversal, the root node is visited before the left child and right child nodes.\nPost-order traversal is one of the multiple methods to traverse a tree." }, { "code": null, "e": 521, "s": 510, "text": "Example 1:" }, { "code": null, "e": 839, "s": 521, "text": "Input:\nN = 5\narr[] = {40,30,35,80,100}\nOutput: 35 30 100 80 40\nExplanation: PreOrder: 40 30 35 80 100\nInOrder: 30 35 40 80 100\nTherefore, the BST will be:\n 40\n / \\\n 30 80\n \\ \\ \n 35 100\nHence, the postOrder traversal will\nbe: 35 30 100 80 40" }, { "code": null, "e": 850, "s": 839, "text": "Example 2:" }, { "code": null, "e": 934, "s": 850, "text": "Input:\nN = 8\narr[] = {40,30,32,35,80,90,100,120}\nOutput: 35 32 30 120 100 90 80 40" }, { "code": null, "e": 1093, "s": 934, "text": "Your Task:\nYou need to complete the given function and return the root of the tree. The driver code will then use this root to print the post order traversal." }, { "code": null, "e": 1157, "s": 1093, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1203, "s": 1157, "text": "Constraints:\n1 <= N <= 103\n1 <= arr[i] <= 104" }, { "code": null, "e": 1205, "s": 1203, "text": "0" }, { "code": null, "e": 1226, "s": 1205, "text": "sajalsa8pt2 days ago" }, { "code": null, "e": 1757, "s": 1226, "text": "public static Node post_order(int pre[], int size) \n{\n //Your code here\n Node root = new Node(pre[0]);\n for(int i=1;i<pre.length;i++)\n insert(root,pre[i]);\n return root;\n} \n\npublic static void insert(Node root, int i)\n{\n Node prev = null, curr = root, temp = new Node(i);\n while(curr!=null)\n {\n prev = curr;\n if(curr.data>i)\n curr = curr.left;\n else\n curr = curr.right;\n }\n if(prev.data>i)\n prev.left = temp;\n else\n prev.right = temp;\n}" }, { "code": null, "e": 1759, "s": 1757, "text": "0" }, { "code": null, "e": 1781, "s": 1759, "text": "2019umt13465 days ago" }, { "code": null, "e": 2584, "s": 1781, "text": "class Solution{public: Node* constructTree(int pre[],int &preIndex,int key,int min,int max,int size) { if(preIndex>=size) return NULL; Node* root=NULL; if(key>min && key<max) { root=newNode(key); preIndex++; if(preIndex<size) { root->left=constructTree(pre,preIndex,pre[preIndex],min,key,size); } if(preIndex<size) { root->right=constructTree(pre,preIndex,pre[preIndex],key,max,size); } } return root; } //Function that constructs BST from its preorder traversal. Node* post_order(int pre[], int size) { int preorderIndex=0; return constructTree(pre,preorderIndex,pre[0],INT_MIN,INT_MAX,size); //code here }};" }, { "code": null, "e": 2587, "s": 2584, "text": "+1" }, { "code": null, "e": 2612, "s": 2587, "text": "mahesh_phutane1 week ago" }, { "code": null, "e": 2647, "s": 2612, "text": "Java Solution: TC → O(n) SC → O(1)" }, { "code": null, "e": 3100, "s": 2647, "text": "public static Node solve(int[] pre,int size,int min,int max){\n if(idx>size) return null;\n if(pre[idx]<min || pre[idx]>max) return null;\n Node root = new Node(pre[idx++]);\n root.left = solve(pre,size,min,root.data);\n root.right = solve(pre,size,root.data,max);\n return root;\n}\nstatic int idx = 0;\npublic static Node post_order(int pre[], int size) \n{ \n idx = 0;\n return solve(pre,size-1,Integer.MIN_VALUE,Integer.MAX_VALUE);\n} " }, { "code": null, "e": 3103, "s": 3100, "text": "+1" }, { "code": null, "e": 3121, "s": 3103, "text": "prashr11 week ago" }, { "code": null, "e": 3141, "s": 3121, "text": "Recursive Solution:" }, { "code": null, "e": 4075, "s": 3143, "text": "class Solution{\npublic:\n\n Node* po_Util(int pre[],int start,int end)\n {\n Node* root=newNode(pre[start]);\n int x=pre[start],s=start;\n if(start==end)\n {\n root->left=root->right=NULL;\n return root;\n }\n start++;\n while(start<=end && pre[start]<x)\n start++;\n \n if(start>end)\n {\n root->right=NULL;\n root->left=po_Util(pre,s+1,end);\n }\n else if(start==s+1)\n {\n root->left=NULL;\n root->right=po_Util(pre,start,end);\n }\n else\n {\n root->left=po_Util(pre,s+1,start-1);\n root->right=po_Util(pre,start,end);\n }\n return root;\n }\n //Function that constructs BST from its preorder traversal.\n Node* post_order(int pre[], int size)\n {\n //code here\n return po_Util(pre,0,size-1);\n }\n};" }, { "code": null, "e": 4077, "s": 4075, "text": "0" }, { "code": null, "e": 4103, "s": 4077, "text": "irockstarpiyush1 week ago" }, { "code": null, "e": 4125, "s": 4103, "text": "C++ -Simple Solution " }, { "code": null, "e": 4628, "s": 4125, "text": "Node* f(int pre[], int &ind, int n, int mn, int mx) { if(ind >= n){ return NULL; } if(!(pre[ind] > mn && pre[ind] < mx)){ return NULL; } Node * node = newNode(pre[ind]); ind++; node->left = f(pre, ind, n, mn, node->data); node->right = f(pre, ind, n, node->data, mx); return node; } Node* post_order(int pre[], int size) { int ind = 0; Node* root = f(pre, ind, size, INT_MIN, INT_MAX); return root; }" }, { "code": null, "e": 4630, "s": 4628, "text": "0" }, { "code": null, "e": 4659, "s": 4630, "text": "yuvrajranabtcse202 weeks ago" }, { "code": null, "e": 4675, "s": 4659, "text": "c++ 2 ways soln" }, { "code": null, "e": 5305, "s": 4675, "text": "Node* makeprebystack(int pre[],int size){ stack<Node*> ques; int i=1; Node* root= newNode(pre[0]); Node* p=root; while(i<size){ if(pre[i]<p->data){ p->left=newNode(pre[i++]); ques.push(p); p=p->left; } else if(pre[i]>p->data){ if(ques.empty()){ p->right=newNode(pre[i++]); p=p->right; } else if(ques.top()->data>pre[i]){ p->right=newNode(pre[i++]); p=p->right; } else{ p=ques.top(); ques.pop(); } } } return root; }" }, { "code": null, "e": 5732, "s": 5305, "text": "/*-------------------------------------------------------------*/Node* makeprebyiteration(int pre[],int size,int &i,int start,int end){ if(i>=size)return NULL; Node* root=NULL; int key=pre[i]; if((key>start)&&(key<end)){ Node* root=newNode(key); i++; root->left=makeprebyiteration(pre,size,i,start,key); root->right=makeprebyiteration(pre,size,i,key,end); return root; } return root;}" }, { "code": null, "e": 5850, "s": 5732, "text": " Node* post_order(int pre[], int size) { int i=0; return makeprebyiteration(pre,size,i,INT_MIN,INT_MAX);}};" }, { "code": null, "e": 5852, "s": 5850, "text": "0" }, { "code": null, "e": 5874, "s": 5852, "text": "insanelion2 weeks ago" }, { "code": null, "e": 6472, "s": 5874, "text": "public static Node post_order(int pre[], int size) \n{\n //Your code here\n \n Node root = new Node(pre[0]);\n Node cur = root;\n Stack<Node> st = new Stack<>();\n st.push(root);\n for(int i=1;i<size;i++) {\n Node node = new Node(pre[i]);\n if(st.peek().data<pre[i]) {\n while(!st.isEmpty()&&st.peek().data<pre[i]) {\n cur = st.pop();\n }\n cur.right = node;\n cur = cur.right;\n }\n else {\n cur.left = node;\n cur = cur.left;\n }\n st.push(node);\n }\n return root;\n} " }, { "code": null, "e": 6474, "s": 6472, "text": "0" }, { "code": null, "e": 6504, "s": 6474, "text": "thakursahabsingh122 weeks ago" }, { "code": null, "e": 6510, "s": 6504, "text": "Java," }, { "code": null, "e": 6922, "s": 6510, "text": "public static Node post_order(int pre[], int size) { //Your code here return helper(pre, 0, pre.length-1);} public static Node helper(int[] pre, int l, int r){ if(l>r){ return null; } Node root= new Node(pre[l]); int i; for(i=l;i<=r;i++){ if(pre[i]>root.data){ break; } } root.left = helper(pre, l+1, i-1); root.right = helper(pre, i, r); return root; } " }, { "code": null, "e": 6925, "s": 6922, "text": "+1" }, { "code": null, "e": 6954, "s": 6925, "text": "bagheldikshant1232 weeks ago" }, { "code": null, "e": 6989, "s": 6954, "text": "java Easy Solution using Recursion" }, { "code": null, "e": 7405, "s": 6989, "text": "public static Node post_order(int pre[], int size) \n{\n return helper(pre, 0, pre.length-1);\n} \npublic static Node helper(int[] pre, int l, int r){\n if(l>r){\n return null;\n }\n Node root= new Node(pre[l]);\n int i;\n for(i=l;i<=r;i++){\n if(pre[i]>root.data){\n break;\n }\n }\n root.left = helper(pre, l+1, i-1);\n root.right = helper(pre, i, r);\n return root;\n}" }, { "code": null, "e": 7408, "s": 7405, "text": "+3" }, { "code": null, "e": 7434, "s": 7408, "text": "avinashdhn19043 weeks ago" }, { "code": null, "e": 8076, "s": 7434, "text": "\nclass Solution{\npublic:\n //Function that constructs BST from its preorder traversal.\n Node *build_tree(int pre[],int n,int &i,int mini,int maxi){\n if(i>=n)return NULL;\n if(pre[i]<mini||pre[i]>maxi)return NULL;\n Node *root=(Node *)malloc(sizeof(Node));\n \n root->data=pre[i++];\n \n root->left=build_tree(pre,n,i,mini,root->data);\n root->right=build_tree(pre,n,i,root->data,maxi);\n return root;\n }\n \n Node* post_order(int pre[], int size)\n {\n int i=0,mini=INT_MIN,maxi=INT_MAX;\n Node* root= build_tree(pre,size,i,mini,maxi);\n return root;\n }\n};" }, { "code": null, "e": 8222, "s": 8076, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8258, "s": 8222, "text": " Login to access your submissions. " }, { "code": null, "e": 8268, "s": 8258, "text": "\nProblem\n" }, { "code": null, "e": 8278, "s": 8268, "text": "\nContest\n" }, { "code": null, "e": 8341, "s": 8278, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8526, "s": 8341, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8810, "s": 8526, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 8956, "s": 8810, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 9033, "s": 8956, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 9074, "s": 9033, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 9102, "s": 9074, "text": "Disable browser extensions." }, { "code": null, "e": 9173, "s": 9102, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 9360, "s": 9173, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Lightweight Transactions in Cassandra
20 Nov, 2019 In this article we will discuss Lightweight Transactions(LWT) in Cassandra which is also help to improve performance. Sometimes insert or update operations must be unique which require a read-before-write. The read-before-write has performance implications – Use wisely! This type of problem solved by CQL Lightweight Transactions (LWT) by using an IF clause on inserts and updates. For Example:Creating a keyspace: CREATE KEYSPACE IF NOT EXIST keyspace1 WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 2}; Creating a table: CREATE TABLE User ( U_email text, U_password int, U_id UUID, PRIMARY KEY (email) ); To read used the following CQL query. Select * from keyspace1.User where U_email = ‘[email protected]’; Output: [0 rows] To insert the data into table used the following CQL Query. Insert into keyspace1.User (U_email, U_password, U_id) values (‘[email protected]’, ‘password_A’, uuid()) if not exists; Let’s have a look. Now, LWT created the row. Select * from keyspace1.User where U_email = ‘[email protected]’; Output: LWT on Existing Row: Insert into keyspace1.User (U_email, U_password, U_id) values (‘[email protected]’, ‘password_XYZ’, uuid()) if not exists; Let’s have a look, Here is the output of the above CQL query. Select * from keyspace1.User where U_email = ‘[email protected]’; Output: Lightweight Transactions(LWT) on Updating Row:CQL query for updating an existing row and now we are applying LWT on this. CQL query for updating an existing row. UPDATE keyspace1.User SET U_password = 'password_XYZ' WHERE U_email = '[email protected]' IF U_password = 'password_A' ; Operators can be used for UPDATE command: =, <,, >=, != and IN Let’s have a look, Apache DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS MySQL | Regular expressions (Regexp) Difference between OLAP and OLTP in DBMS What is Temporary Table in SQL? SQL | DDL, DML, TCL and DCL Difference between Where and Having Clause in SQL Introduction of Relational Algebra in DBMS Relational Model in DBMS Difference between Star Schema and Snowflake Schema What is Cursor in SQL ?
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Nov, 2019" }, { "code": null, "e": 146, "s": 28, "text": "In this article we will discuss Lightweight Transactions(LWT) in Cassandra which is also help to improve performance." }, { "code": null, "e": 411, "s": 146, "text": "Sometimes insert or update operations must be unique which require a read-before-write. The read-before-write has performance implications – Use wisely! This type of problem solved by CQL Lightweight Transactions (LWT) by using an IF clause on inserts and updates." }, { "code": null, "e": 444, "s": 411, "text": "For Example:Creating a keyspace:" }, { "code": null, "e": 580, "s": 444, "text": "CREATE KEYSPACE IF NOT EXIST keyspace1 \nWITH replication = {'class': 'SimpleStrategy', \n 'replication_factor' : 2}; " }, { "code": null, "e": 598, "s": 580, "text": "Creating a table:" }, { "code": null, "e": 689, "s": 598, "text": "CREATE TABLE User (\nU_email text,\nU_password int, \nU_id UUID,\nPRIMARY KEY (email)\n); " }, { "code": null, "e": 727, "s": 689, "text": "To read used the following CQL query." }, { "code": null, "e": 795, "s": 727, "text": "Select * \nfrom keyspace1.User \nwhere U_email = ‘[email protected]’; " }, { "code": null, "e": 803, "s": 795, "text": "Output:" }, { "code": null, "e": 812, "s": 803, "text": "[0 rows]" }, { "code": null, "e": 872, "s": 812, "text": "To insert the data into table used the following CQL Query." }, { "code": null, "e": 995, "s": 872, "text": "Insert into keyspace1.User (U_email, U_password, U_id) \nvalues (‘[email protected]’, ‘password_A’, uuid()) \nif not exists; " }, { "code": null, "e": 1014, "s": 995, "text": "Let’s have a look." }, { "code": null, "e": 1040, "s": 1014, "text": "Now, LWT created the row." }, { "code": null, "e": 1108, "s": 1040, "text": "Select * \nfrom keyspace1.User \nwhere U_email = ‘[email protected]’; " }, { "code": null, "e": 1116, "s": 1108, "text": "Output:" }, { "code": null, "e": 1137, "s": 1116, "text": "LWT on Existing Row:" }, { "code": null, "e": 1263, "s": 1137, "text": "Insert into keyspace1.User (U_email, U_password, U_id) \nvalues (‘[email protected]’, ‘password_XYZ’, uuid()) \nif not exists; " }, { "code": null, "e": 1282, "s": 1263, "text": "Let’s have a look," }, { "code": null, "e": 1325, "s": 1282, "text": "Here is the output of the above CQL query." }, { "code": null, "e": 1393, "s": 1325, "text": "Select * \nfrom keyspace1.User \nwhere U_email = ‘[email protected]’; " }, { "code": null, "e": 1401, "s": 1393, "text": "Output:" }, { "code": null, "e": 1563, "s": 1401, "text": "Lightweight Transactions(LWT) on Updating Row:CQL query for updating an existing row and now we are applying LWT on this. CQL query for updating an existing row." }, { "code": null, "e": 1685, "s": 1563, "text": "UPDATE keyspace1.User SET U_password = 'password_XYZ' \nWHERE U_email = '[email protected]'\nIF U_password = 'password_A' ; " }, { "code": null, "e": 1727, "s": 1685, "text": "Operators can be used for UPDATE command:" }, { "code": null, "e": 1749, "s": 1727, "text": "=, <,, >=, != and IN " }, { "code": null, "e": 1768, "s": 1749, "text": "Let’s have a look," }, { "code": null, "e": 1775, "s": 1768, "text": "Apache" }, { "code": null, "e": 1780, "s": 1775, "text": "DBMS" }, { "code": null, "e": 1785, "s": 1780, "text": "DBMS" }, { "code": null, "e": 1883, "s": 1785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1924, "s": 1883, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 1961, "s": 1924, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 2002, "s": 1961, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 2034, "s": 2002, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2062, "s": 2034, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 2112, "s": 2062, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 2155, "s": 2112, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 2180, "s": 2155, "text": "Relational Model in DBMS" }, { "code": null, "e": 2232, "s": 2180, "text": "Difference between Star Schema and Snowflake Schema" } ]
How to make simple PUT request using fetch API by making custom HTTP library ?
18 Jul, 2020 The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. It will be taking a fake API that will contain Array as an example and from that API we will show to PUT/Update data by fetch API method by making custom HTTP library. The API used in this tutorial is: https://jsonplaceholder.typicode.com/users/2 Prerequisite: You should be aware of basics of HTML CSS and JavaScript. Explanation: First of all we need to create index.html file and paste the below code of index.html file into that. This index.html file includes library.js and app.js file at the bottom of the body tag. Now in library.js file, first of all create an ES6 class EasyHTTP and within that class there is async fetch() function that puts the data to the api url. There are two stages of await. First for fetch() and then for its response. Whatever response we receive, we return it to the calling function in app.js file. Now in app.js file first of all instantiate EasyHTTP class. Then by put prototype function, send url to the to the library.js file. Further in this there are two promises to be resolved. First is for any response data and the second is for any error. Filename: index.html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>PUT Request</title></head> <body> <h1> Simple PUT request using fetch API by making custom HTTP library </h1> <!-- Including library.js and app.js --> <script src="library.js"></script> <script src="app.js"></script></body> </html> Filename: library.html // ES6 classclass EasyHTTP { // Make an HTTP PUT Request async put(url, data) { // Awaiting fetch which contains method, // headers and content-type and body const response = await fetch(url, { method: 'PUT', headers: { 'Content-type': 'application/json' }, body: JSON.stringify(data) }); // Awaiting response.json() const resData = await response.json(); // Return response data return resData; }} Filename: app.html // Instantiating new EasyHTTP classconst http = new EasyHTTP;// User Dataconst data = { name: 'sunny yadav', username: 'sunnyyadav', email: '[email protected]' } // Update Posthttp.put('https://jsonplaceholder.typicode.com/users/2', data) // Resolving promise for response data.then(data => console.log(data)) // Resolving promise for error.catch(err => console.log(err)); Output: Open index.html file in the browser then right click-> inspect element->console.The following output you will see for PUT request. JavaScript-Misc Node.js-Misc HTML JavaScript Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2020" }, { "code": null, "e": 420, "s": 28, "text": "The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. It will be taking a fake API that will contain Array as an example and from that API we will show to PUT/Update data by fetch API method by making custom HTTP library. The API used in this tutorial is: https://jsonplaceholder.typicode.com/users/2" }, { "code": null, "e": 492, "s": 420, "text": "Prerequisite: You should be aware of basics of HTML CSS and JavaScript." }, { "code": null, "e": 1009, "s": 492, "text": "Explanation: First of all we need to create index.html file and paste the below code of index.html file into that. This index.html file includes library.js and app.js file at the bottom of the body tag. Now in library.js file, first of all create an ES6 class EasyHTTP and within that class there is async fetch() function that puts the data to the api url. There are two stages of await. First for fetch() and then for its response. Whatever response we receive, we return it to the calling function in app.js file." }, { "code": null, "e": 1260, "s": 1009, "text": "Now in app.js file first of all instantiate EasyHTTP class. Then by put prototype function, send url to the to the library.js file. Further in this there are two promises to be resolved. First is for any response data and the second is for any error." }, { "code": null, "e": 1281, "s": 1260, "text": "Filename: index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>PUT Request</title></head> <body> <h1> Simple PUT request using fetch API by making custom HTTP library </h1> <!-- Including library.js and app.js --> <script src=\"library.js\"></script> <script src=\"app.js\"></script></body> </html>", "e": 1773, "s": 1281, "text": null }, { "code": null, "e": 1796, "s": 1773, "text": "Filename: library.html" }, { "code": "// ES6 classclass EasyHTTP { // Make an HTTP PUT Request async put(url, data) { // Awaiting fetch which contains method, // headers and content-type and body const response = await fetch(url, { method: 'PUT', headers: { 'Content-type': 'application/json' }, body: JSON.stringify(data) }); // Awaiting response.json() const resData = await response.json(); // Return response data return resData; }}", "e": 2264, "s": 1796, "text": null }, { "code": null, "e": 2283, "s": 2264, "text": "Filename: app.html" }, { "code": "// Instantiating new EasyHTTP classconst http = new EasyHTTP;// User Dataconst data = { name: 'sunny yadav', username: 'sunnyyadav', email: '[email protected]' } // Update Posthttp.put('https://jsonplaceholder.typicode.com/users/2', data) // Resolving promise for response data.then(data => console.log(data)) // Resolving promise for error.catch(err => console.log(err));", "e": 2671, "s": 2283, "text": null }, { "code": null, "e": 2810, "s": 2671, "text": "Output: Open index.html file in the browser then right click-> inspect element->console.The following output you will see for PUT request." }, { "code": null, "e": 2826, "s": 2810, "text": "JavaScript-Misc" }, { "code": null, "e": 2839, "s": 2826, "text": "Node.js-Misc" }, { "code": null, "e": 2844, "s": 2839, "text": "HTML" }, { "code": null, "e": 2855, "s": 2844, "text": "JavaScript" }, { "code": null, "e": 2863, "s": 2855, "text": "Node.js" }, { "code": null, "e": 2880, "s": 2863, "text": "Web Technologies" }, { "code": null, "e": 2885, "s": 2880, "text": "HTML" }, { "code": null, "e": 2983, "s": 2885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3031, "s": 2983, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3055, "s": 3031, "text": "REST API (Introduction)" }, { "code": null, "e": 3105, "s": 3055, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 3144, "s": 3105, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3181, "s": 3144, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3242, "s": 3181, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3314, "s": 3242, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3354, "s": 3314, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3406, "s": 3354, "text": "How to append HTML code to a div using JavaScript ?" } ]
HTML | alt attribute
05 Jan, 2022 The HTML alt attribute is used to provide an alternate tag that is used to show or display something if the primary attribute i.e., the <img> tag, fails to display the value assigned to it.Supported tags: area image input <applet> Attribute Values: It contains single value text which is used to specify the alternative text for supported element, if image is not displaying. Example: Img alt attribute. html <!DOCTYPE html> <html> <head> <title> HTML img alt Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h2>HTML img alt Attribute</h2> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png" alt="GeeksforGeeks logo"> </body> </html> Output: Before: After: Example: Area alt attribute. html <!DOCTYPE html> <html> <head> <title> HTML area alt Attribute </title> </head> <body style="text-align:center;"> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20190227165729/area11.png" alt="alt_attribute" width="300" height="119" class="aligncenter" usemap="#shapemap" /> <map name="shapemap"> <!-- area tag contained image. --> <area shape="poly" coords="59, 31, 28, 83, 91, 83" href= "https://media.geeksforgeeks.org/wp-content/uploads/20190227165802/area2.png" alt="Triangle"> <area shape="circle" coords="155, 56, 26" href= "https://media.geeksforgeeks.org/wp-content/uploads/20190227165934/area3.png" alt="Circle"> <area shape="rect" coords="224, 30, 276, 82" href= "https://media.geeksforgeeks.org/wp-content/uploads/20190227170021/area4.png" alt="Square"> </map> </body> </html> Output: Example: Input alt attribute. html <!DOCTYPE html> <html> <head> <title> HTML Input alt Attribute </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML Input alt Attribute</h2> <input id="myImage" type="image" src= "https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png" alt="Submit" width="48" height="48"> </body> </html> Output: Supported Browsers: The browsers supported by HTML | alt attribute are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera ManasChhabra2 hritikbhatnagar2182 vshylaja HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jan, 2022" }, { "code": null, "e": 234, "s": 28, "text": "The HTML alt attribute is used to provide an alternate tag that is used to show or display something if the primary attribute i.e., the <img> tag, fails to display the value assigned to it.Supported tags: " }, { "code": null, "e": 239, "s": 234, "text": "area" }, { "code": null, "e": 245, "s": 239, "text": "image" }, { "code": null, "e": 251, "s": 245, "text": "input" }, { "code": null, "e": 260, "s": 251, "text": "<applet>" }, { "code": null, "e": 405, "s": 260, "text": "Attribute Values: It contains single value text which is used to specify the alternative text for supported element, if image is not displaying." }, { "code": null, "e": 435, "s": 405, "text": "Example: Img alt attribute. " }, { "code": null, "e": 440, "s": 435, "text": "html" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML img alt Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h2>HTML img alt Attribute</h2> <img src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png\" alt=\"GeeksforGeeks logo\"> </body> </html> ", "e": 758, "s": 440, "text": null }, { "code": null, "e": 776, "s": 758, "text": "Output: Before: " }, { "code": null, "e": 785, "s": 776, "text": "After: " }, { "code": null, "e": 816, "s": 785, "text": "Example: Area alt attribute. " }, { "code": null, "e": 821, "s": 816, "text": "html" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML area alt Attribute </title> </head> <body style=\"text-align:center;\"> <img src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190227165729/area11.png\" alt=\"alt_attribute\" width=\"300\" height=\"119\" class=\"aligncenter\" usemap=\"#shapemap\" /> <map name=\"shapemap\"> <!-- area tag contained image. --> <area shape=\"poly\" coords=\"59, 31, 28, 83, 91, 83\" href= \"https://media.geeksforgeeks.org/wp-content/uploads/20190227165802/area2.png\" alt=\"Triangle\"> <area shape=\"circle\" coords=\"155, 56, 26\" href= \"https://media.geeksforgeeks.org/wp-content/uploads/20190227165934/area3.png\" alt=\"Circle\"> <area shape=\"rect\" coords=\"224, 30, 276, 82\" href= \"https://media.geeksforgeeks.org/wp-content/uploads/20190227170021/area4.png\" alt=\"Square\"> </map> </body> </html>", "e": 1756, "s": 821, "text": null }, { "code": null, "e": 1766, "s": 1756, "text": "Output: " }, { "code": null, "e": 1798, "s": 1766, "text": "Example: Input alt attribute. " }, { "code": null, "e": 1803, "s": 1798, "text": "html" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML Input alt Attribute </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>HTML Input alt Attribute</h2> <input id=\"myImage\" type=\"image\" src= \"https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png\" alt=\"Submit\" width=\"48\" height=\"48\"> </body> </html>", "e": 2245, "s": 1803, "text": null }, { "code": null, "e": 2255, "s": 2245, "text": "Output: " }, { "code": null, "e": 2342, "s": 2255, "text": "Supported Browsers: The browsers supported by HTML | alt attribute are listed below: " }, { "code": null, "e": 2356, "s": 2342, "text": "Google Chrome" }, { "code": null, "e": 2374, "s": 2356, "text": "Internet Explorer" }, { "code": null, "e": 2382, "s": 2374, "text": "Firefox" }, { "code": null, "e": 2395, "s": 2382, "text": "Apple Safari" }, { "code": null, "e": 2401, "s": 2395, "text": "Opera" }, { "code": null, "e": 2417, "s": 2403, "text": "ManasChhabra2" }, { "code": null, "e": 2437, "s": 2417, "text": "hritikbhatnagar2182" }, { "code": null, "e": 2446, "s": 2437, "text": "vshylaja" }, { "code": null, "e": 2462, "s": 2446, "text": "HTML-Attributes" }, { "code": null, "e": 2467, "s": 2462, "text": "HTML" }, { "code": null, "e": 2484, "s": 2467, "text": "Web Technologies" }, { "code": null, "e": 2489, "s": 2484, "text": "HTML" }, { "code": null, "e": 2587, "s": 2489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2635, "s": 2587, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2697, "s": 2635, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2747, "s": 2697, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2771, "s": 2747, "text": "REST API (Introduction)" }, { "code": null, "e": 2824, "s": 2771, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2857, "s": 2824, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2919, "s": 2857, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2980, "s": 2919, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3030, "s": 2980, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Network Layer Services- Packetizing, Routing and Forwarding
22 Mar, 2022 Network layer is the third layer in the OSI model of computer networks. It’s main function is to transfer network packets from the source to the destination. It is involved both at the source host and the destination host. At the source, it accepts a packet from the transport layer, encapsulates it in a datagram and then deliver the packet to the data link layer so that it can further be sent to the receiver. At the destination, the datagram is decapsulated, the packet is extracted and delivered to the corresponding transport layer. Features : Main responsibility of Network layer is to carry the data packets from the source to the destination without changing or using it. If the packets are too large for delivery, they are fragmented i.e., broken down into smaller packets. It decides the route to be taken by the packets to travel from the source to the destination among the multiple routes available in a network (also called as routing). The source and destination addresses are added to the data packets inside the network layer. Main responsibility of Network layer is to carry the data packets from the source to the destination without changing or using it. If the packets are too large for delivery, they are fragmented i.e., broken down into smaller packets. It decides the route to be taken by the packets to travel from the source to the destination among the multiple routes available in a network (also called as routing). The source and destination addresses are added to the data packets inside the network layer. The services which are offered by the network layer protocol are as follows: Packetizing – The process of encapsulating the data received from upper layers of the network(also called as payload) in a network layer packet at the source and decapsulating the payload from the network layer packet at the destination is known as packetizing. The source host adds a header that contains the source and destination address and some other relevant information required by the network layer protocol to the payload received from the upper layer protocol, and delivers the packet to the data link layer. The destination host receives the network layer packet from its data link layer, decapsulates the packet, and delivers the payload to the corresponding upper layer protocol. The routers in the path are not allowed to change either the source or the destination address. The routers in the path are not allowed to decapsulate the packets they receive unless they need to be fragmented. Routing and Forwarding – These are two other services offered by the network layer. In a network, there are a number of routes available from the source to the destination. The network layer specifies has some strategies which find out the best possible route. This process is referred to as routing. There are a number of routing protocols which are used in this process and they should be run to help the routers coordinate with each other and help in establishing communication throughout the network. Forwarding is simply defined as the action applied by each router when a packet arrives at one of its interfaces. When a router receives a packet from one of its attached networks, it needs to forward the packet to another attached network (unicast routing) or to some attached networks(in case of multicast routing). Packetizing – The process of encapsulating the data received from upper layers of the network(also called as payload) in a network layer packet at the source and decapsulating the payload from the network layer packet at the destination is known as packetizing. The source host adds a header that contains the source and destination address and some other relevant information required by the network layer protocol to the payload received from the upper layer protocol, and delivers the packet to the data link layer. The destination host receives the network layer packet from its data link layer, decapsulates the packet, and delivers the payload to the corresponding upper layer protocol. The routers in the path are not allowed to change either the source or the destination address. The routers in the path are not allowed to decapsulate the packets they receive unless they need to be fragmented. The source host adds a header that contains the source and destination address and some other relevant information required by the network layer protocol to the payload received from the upper layer protocol, and delivers the packet to the data link layer. The destination host receives the network layer packet from its data link layer, decapsulates the packet, and delivers the payload to the corresponding upper layer protocol. The routers in the path are not allowed to change either the source or the destination address. The routers in the path are not allowed to decapsulate the packets they receive unless they need to be fragmented. Routing and Forwarding – These are two other services offered by the network layer. In a network, there are a number of routes available from the source to the destination. The network layer specifies has some strategies which find out the best possible route. This process is referred to as routing. There are a number of routing protocols which are used in this process and they should be run to help the routers coordinate with each other and help in establishing communication throughout the network. Forwarding is simply defined as the action applied by each router when a packet arrives at one of its interfaces. When a router receives a packet from one of its attached networks, it needs to forward the packet to another attached network (unicast routing) or to some attached networks(in case of multicast routing). Forwarding is simply defined as the action applied by each router when a packet arrives at one of its interfaces. When a router receives a packet from one of its attached networks, it needs to forward the packet to another attached network (unicast routing) or to some attached networks(in case of multicast routing). Some of the other services which are expected from the network layer are: Error Control – Although it can be implemented in the network layer, but it is usually not preferred because the data packet in a network layer maybe fragmented at each router, which makes error checking inefficient in the network layer. Flow Control – It regulates the amount of data a source can send without overloading the receiver. If the source produces a data at a very faster rate than the receiver can consume it, the receiver will be overloaded with data. To control the flow of data, the receiver should send a feedback to the sender to inform the latter that it is overloaded with data. There is a lack of flow control in the design of the network layer. It does not directly provide any flow control. The datagrams are sent by the sender when they are ready, without any attention to the readiness of the receiver. Congestion Control – Congestion occurs when the number of datagrams sent by source is beyond the capacity of network or routers. This is another issue in the network layer protocol. If congestion continues, sometimes a situation may arrive where the system collapses and no datagrams are delivered. Although congestion control is indirectly implemented in network layer, but still there is a lack of congestion control in the network layer. Error Control – Although it can be implemented in the network layer, but it is usually not preferred because the data packet in a network layer maybe fragmented at each router, which makes error checking inefficient in the network layer. Flow Control – It regulates the amount of data a source can send without overloading the receiver. If the source produces a data at a very faster rate than the receiver can consume it, the receiver will be overloaded with data. To control the flow of data, the receiver should send a feedback to the sender to inform the latter that it is overloaded with data. There is a lack of flow control in the design of the network layer. It does not directly provide any flow control. The datagrams are sent by the sender when they are ready, without any attention to the readiness of the receiver. There is a lack of flow control in the design of the network layer. It does not directly provide any flow control. The datagrams are sent by the sender when they are ready, without any attention to the readiness of the receiver. Congestion Control – Congestion occurs when the number of datagrams sent by source is beyond the capacity of network or routers. This is another issue in the network layer protocol. If congestion continues, sometimes a situation may arrive where the system collapses and no datagrams are delivered. Although congestion control is indirectly implemented in network layer, but still there is a lack of congestion control in the network layer. Advantages of Network Layer Services : Packetization service in network layer provides an ease of transportation of the data packets. Packetization also eliminates single points of failure in data communication systems. Routers present in the network layer reduce network traffic by creating collision and broadcast domains. With the help of Forwarding, data packets are transferred from one place to another in the network. Disadvantages of Network Layer Services : There is a lack of flow control in the design of the network layer. Congestion occurs sometimes due to the presence of too many datagrams in a network which are beyond the capacity of network or the routers. Due to this, some routers may drop some of the datagrams and some important piece of information maybe lost. Although indirectly error control is present in network layer, but there is a lack of proper error control mechanisms as due to presence of fragmented data packets, error control becomes difficult to implement. ankitkumarsingh3 nildey21 Computer Networks-Network Layer Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Introduction of Mobile Ad hoc Network (MANET) ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Mar, 2022" }, { "code": null, "e": 594, "s": 54, "text": "Network layer is the third layer in the OSI model of computer networks. It’s main function is to transfer network packets from the source to the destination. It is involved both at the source host and the destination host. At the source, it accepts a packet from the transport layer, encapsulates it in a datagram and then deliver the packet to the data link layer so that it can further be sent to the receiver. At the destination, the datagram is decapsulated, the packet is extracted and delivered to the corresponding transport layer. " }, { "code": null, "e": 607, "s": 594, "text": "Features : " }, { "code": null, "e": 1103, "s": 607, "text": "Main responsibility of Network layer is to carry the data packets from the source to the destination without changing or using it. If the packets are too large for delivery, they are fragmented i.e., broken down into smaller packets. It decides the route to be taken by the packets to travel from the source to the destination among the multiple routes available in a network (also called as routing). The source and destination addresses are added to the data packets inside the network layer. " }, { "code": null, "e": 1235, "s": 1103, "text": "Main responsibility of Network layer is to carry the data packets from the source to the destination without changing or using it. " }, { "code": null, "e": 1339, "s": 1235, "text": "If the packets are too large for delivery, they are fragmented i.e., broken down into smaller packets. " }, { "code": null, "e": 1508, "s": 1339, "text": "It decides the route to be taken by the packets to travel from the source to the destination among the multiple routes available in a network (also called as routing). " }, { "code": null, "e": 1602, "s": 1508, "text": "The source and destination addresses are added to the data packets inside the network layer. " }, { "code": null, "e": 1680, "s": 1602, "text": "The services which are offered by the network layer protocol are as follows: " }, { "code": null, "e": 3409, "s": 1680, "text": "Packetizing – The process of encapsulating the data received from upper layers of the network(also called as payload) in a network layer packet at the source and decapsulating the payload from the network layer packet at the destination is known as packetizing. The source host adds a header that contains the source and destination address and some other relevant information required by the network layer protocol to the payload received from the upper layer protocol, and delivers the packet to the data link layer. The destination host receives the network layer packet from its data link layer, decapsulates the packet, and delivers the payload to the corresponding upper layer protocol. The routers in the path are not allowed to change either the source or the destination address. The routers in the path are not allowed to decapsulate the packets they receive unless they need to be fragmented. Routing and Forwarding – These are two other services offered by the network layer. In a network, there are a number of routes available from the source to the destination. The network layer specifies has some strategies which find out the best possible route. This process is referred to as routing. There are a number of routing protocols which are used in this process and they should be run to help the routers coordinate with each other and help in establishing communication throughout the network. Forwarding is simply defined as the action applied by each router when a packet arrives at one of its interfaces. When a router receives a packet from one of its attached networks, it needs to forward the packet to another attached network (unicast routing) or to some attached networks(in case of multicast routing). " }, { "code": null, "e": 4315, "s": 3409, "text": "Packetizing – The process of encapsulating the data received from upper layers of the network(also called as payload) in a network layer packet at the source and decapsulating the payload from the network layer packet at the destination is known as packetizing. The source host adds a header that contains the source and destination address and some other relevant information required by the network layer protocol to the payload received from the upper layer protocol, and delivers the packet to the data link layer. The destination host receives the network layer packet from its data link layer, decapsulates the packet, and delivers the payload to the corresponding upper layer protocol. The routers in the path are not allowed to change either the source or the destination address. The routers in the path are not allowed to decapsulate the packets they receive unless they need to be fragmented. " }, { "code": null, "e": 4573, "s": 4315, "text": "The source host adds a header that contains the source and destination address and some other relevant information required by the network layer protocol to the payload received from the upper layer protocol, and delivers the packet to the data link layer. " }, { "code": null, "e": 4960, "s": 4573, "text": "The destination host receives the network layer packet from its data link layer, decapsulates the packet, and delivers the payload to the corresponding upper layer protocol. The routers in the path are not allowed to change either the source or the destination address. The routers in the path are not allowed to decapsulate the packets they receive unless they need to be fragmented. " }, { "code": null, "e": 5784, "s": 4960, "text": "Routing and Forwarding – These are two other services offered by the network layer. In a network, there are a number of routes available from the source to the destination. The network layer specifies has some strategies which find out the best possible route. This process is referred to as routing. There are a number of routing protocols which are used in this process and they should be run to help the routers coordinate with each other and help in establishing communication throughout the network. Forwarding is simply defined as the action applied by each router when a packet arrives at one of its interfaces. When a router receives a packet from one of its attached networks, it needs to forward the packet to another attached network (unicast routing) or to some attached networks(in case of multicast routing). " }, { "code": null, "e": 6103, "s": 5784, "text": "Forwarding is simply defined as the action applied by each router when a packet arrives at one of its interfaces. When a router receives a packet from one of its attached networks, it needs to forward the packet to another attached network (unicast routing) or to some attached networks(in case of multicast routing). " }, { "code": null, "e": 6179, "s": 6103, "text": "Some of the other services which are expected from the network layer are: " }, { "code": null, "e": 7451, "s": 6179, "text": "Error Control – Although it can be implemented in the network layer, but it is usually not preferred because the data packet in a network layer maybe fragmented at each router, which makes error checking inefficient in the network layer. Flow Control – It regulates the amount of data a source can send without overloading the receiver. If the source produces a data at a very faster rate than the receiver can consume it, the receiver will be overloaded with data. To control the flow of data, the receiver should send a feedback to the sender to inform the latter that it is overloaded with data. There is a lack of flow control in the design of the network layer. It does not directly provide any flow control. The datagrams are sent by the sender when they are ready, without any attention to the readiness of the receiver. Congestion Control – Congestion occurs when the number of datagrams sent by source is beyond the capacity of network or routers. This is another issue in the network layer protocol. If congestion continues, sometimes a situation may arrive where the system collapses and no datagrams are delivered. Although congestion control is indirectly implemented in network layer, but still there is a lack of congestion control in the network layer. " }, { "code": null, "e": 7691, "s": 7451, "text": "Error Control – Although it can be implemented in the network layer, but it is usually not preferred because the data packet in a network layer maybe fragmented at each router, which makes error checking inefficient in the network layer. " }, { "code": null, "e": 8283, "s": 7691, "text": "Flow Control – It regulates the amount of data a source can send without overloading the receiver. If the source produces a data at a very faster rate than the receiver can consume it, the receiver will be overloaded with data. To control the flow of data, the receiver should send a feedback to the sender to inform the latter that it is overloaded with data. There is a lack of flow control in the design of the network layer. It does not directly provide any flow control. The datagrams are sent by the sender when they are ready, without any attention to the readiness of the receiver. " }, { "code": null, "e": 8514, "s": 8283, "text": "There is a lack of flow control in the design of the network layer. It does not directly provide any flow control. The datagrams are sent by the sender when they are ready, without any attention to the readiness of the receiver. " }, { "code": null, "e": 8956, "s": 8514, "text": "Congestion Control – Congestion occurs when the number of datagrams sent by source is beyond the capacity of network or routers. This is another issue in the network layer protocol. If congestion continues, sometimes a situation may arrive where the system collapses and no datagrams are delivered. Although congestion control is indirectly implemented in network layer, but still there is a lack of congestion control in the network layer. " }, { "code": null, "e": 8996, "s": 8956, "text": "Advantages of Network Layer Services : " }, { "code": null, "e": 9092, "s": 8996, "text": "Packetization service in network layer provides an ease of transportation of the data packets. " }, { "code": null, "e": 9179, "s": 9092, "text": "Packetization also eliminates single points of failure in data communication systems. " }, { "code": null, "e": 9285, "s": 9179, "text": "Routers present in the network layer reduce network traffic by creating collision and broadcast domains. " }, { "code": null, "e": 9386, "s": 9285, "text": "With the help of Forwarding, data packets are transferred from one place to another in the network. " }, { "code": null, "e": 9429, "s": 9386, "text": "Disadvantages of Network Layer Services : " }, { "code": null, "e": 9498, "s": 9429, "text": "There is a lack of flow control in the design of the network layer. " }, { "code": null, "e": 9748, "s": 9498, "text": "Congestion occurs sometimes due to the presence of too many datagrams in a network which are beyond the capacity of network or the routers. Due to this, some routers may drop some of the datagrams and some important piece of information maybe lost. " }, { "code": null, "e": 9961, "s": 9748, "text": "Although indirectly error control is present in network layer, but there is a lack of proper error control mechanisms as due to presence of fragmented data packets, error control becomes difficult to implement. " }, { "code": null, "e": 9980, "s": 9963, "text": "ankitkumarsingh3" }, { "code": null, "e": 9989, "s": 9980, "text": "nildey21" }, { "code": null, "e": 10021, "s": 9989, "text": "Computer Networks-Network Layer" }, { "code": null, "e": 10039, "s": 10021, "text": "Computer Networks" }, { "code": null, "e": 10047, "s": 10039, "text": "GATE CS" }, { "code": null, "e": 10065, "s": 10047, "text": "Computer Networks" }, { "code": null, "e": 10163, "s": 10065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10193, "s": 10163, "text": "GSM in Wireless Communication" }, { "code": null, "e": 10219, "s": 10193, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 10249, "s": 10219, "text": "Wireless Application Protocol" }, { "code": null, "e": 10289, "s": 10249, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 10335, "s": 10289, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 10359, "s": 10335, "text": "ACID Properties in DBMS" }, { "code": null, "e": 10386, "s": 10359, "text": "Types of Operating Systems" }, { "code": null, "e": 10407, "s": 10386, "text": "Normal Forms in DBMS" }, { "code": null, "e": 10456, "s": 10407, "text": "Page Replacement Algorithms in Operating Systems" } ]
Output of C Program | Set 20
10 Jul, 2018 Predict the outputs of following C programs. Question 1 int main(){ int x = 10; static int y = x; if(x == y) printf("Equal"); else if(x > y) printf("Greater"); else printf("Less"); getchar(); return 0;} Output: Compiler ErrorIn C, static variables can only be initialized using constant literals. See this GFact for details. Question 2 #include <stdio.h> int main(){ int i; for (i = 1; i != 10; i += 2) { printf(" GeeksforGeeks "); } getchar(); return 0;} Output: Infinite times GeeksforGeeks The loop termination condition never becomes true and the loop prints GeeksforGeeks infinite times. In general, if a for or while statement uses a loop counter, then it is safer to use a relational operator (such as <) to terminate the loop than using an inequality operator (operator !=). See this for details. Question 3 #include<stdio.h>struct st{ int x; struct st next;}; int main(){ struct st temp; temp.x = 10; temp.next = temp; printf("%d", temp.next.x); getchar(); return 0;} Output: Compiler ErrorA C structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know size of such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler can calculate size of struct. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Runtime Errors Different ways to copy a string in C/C++ Output of C++ Program | Set 1 Output of Java Program | Set 3 Output of C++ programs | Set 47 (Pointers) Output of Java Programs | Set 12 Output of Java Program | Set 7 Output of C programs | Set 59 (Loops and Control Statements) unsigned specifier (%u) in C with Examples Output of Java program | Set 5
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jul, 2018" }, { "code": null, "e": 99, "s": 54, "text": "Predict the outputs of following C programs." }, { "code": null, "e": 110, "s": 99, "text": "Question 1" }, { "code": "int main(){ int x = 10; static int y = x; if(x == y) printf(\"Equal\"); else if(x > y) printf(\"Greater\"); else printf(\"Less\"); getchar(); return 0;}", "e": 280, "s": 110, "text": null }, { "code": null, "e": 402, "s": 280, "text": "Output: Compiler ErrorIn C, static variables can only be initialized using constant literals. See this GFact for details." }, { "code": null, "e": 413, "s": 402, "text": "Question 2" }, { "code": "#include <stdio.h> int main(){ int i; for (i = 1; i != 10; i += 2) { printf(\" GeeksforGeeks \"); } getchar(); return 0;}", "e": 547, "s": 413, "text": null }, { "code": null, "e": 584, "s": 547, "text": "Output: Infinite times GeeksforGeeks" }, { "code": null, "e": 896, "s": 584, "text": "The loop termination condition never becomes true and the loop prints GeeksforGeeks infinite times. In general, if a for or while statement uses a loop counter, then it is safer to use a relational operator (such as <) to terminate the loop than using an inequality operator (operator !=). See this for details." }, { "code": null, "e": 907, "s": 896, "text": "Question 3" }, { "code": "#include<stdio.h>struct st{ int x; struct st next;}; int main(){ struct st temp; temp.x = 10; temp.next = temp; printf(\"%d\", temp.next.x); getchar(); return 0;}", "e": 1095, "s": 907, "text": null }, { "code": null, "e": 1405, "s": 1095, "text": "Output: Compiler ErrorA C structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know size of such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler can calculate size of struct." }, { "code": null, "e": 1553, "s": 1405, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above" }, { "code": null, "e": 1562, "s": 1553, "text": "C-Output" }, { "code": null, "e": 1577, "s": 1562, "text": "Program Output" }, { "code": null, "e": 1675, "s": 1577, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1690, "s": 1675, "text": "Runtime Errors" }, { "code": null, "e": 1731, "s": 1690, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 1761, "s": 1731, "text": "Output of C++ Program | Set 1" }, { "code": null, "e": 1792, "s": 1761, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 1835, "s": 1792, "text": "Output of C++ programs | Set 47 (Pointers)" }, { "code": null, "e": 1868, "s": 1835, "text": "Output of Java Programs | Set 12" }, { "code": null, "e": 1899, "s": 1868, "text": "Output of Java Program | Set 7" }, { "code": null, "e": 1960, "s": 1899, "text": "Output of C programs | Set 59 (Loops and Control Statements)" }, { "code": null, "e": 2003, "s": 1960, "text": "unsigned specifier (%u) in C with Examples" } ]
How to Create Language Translator in Android using Firebase ML Kit?
28 Nov, 2021 In the previous article, we have seen using Language detector in Android using Firebase ML kit. In this article, we will take a look at the implementation of Language translator in Android using Firebase ML Kit in Android. We will be building a simple application in which we will be showing an EditText field and we will add any input to that TextField. Along with that, we will be displaying a Button to translate that text to the German language. After clicking that button our text will be translated to the German language which we can get to see in the text view. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project How to Create Language Translator Android App? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersHow to Create Language Translator Android App? | 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 / 55:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=i58g-EPG5_s" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Connect your app to Firebase After creating a new project in Android Studio connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Firebase ML and then click on Use Firebase ML kit in Android. You can see the option in the below screenshot. After clicking on this option you will get to see the below screen. On this screen click on Connect to Firebase option to connect your app to Firebase. Click on Connect option to connect your app to Firebase and add the below dependency to your build.gradle file. Step 3: Adding dependency for language translation to build.gradle file Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. // dependency for firebase core. implementation’com.google.firebase:firebase-core:15.0.2′ // below two dependency are used for language detection implementation ‘com.google.firebase:firebase-ml-natural-language:22.0.0’ implementation ‘com.google.firebase:firebase-ml-natural-language-translate-model:20.0.8’ Step 4: Adding permissions to access the Internet in your Android App Navigate to the app > AndroidManifest.xml file and add the below code to it. Comments are added in the code to get to know in more detail. XML <!--permission for internet--><uses-permission android:name="android.permission.INTERNET"/> Step 5: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--edit text to enter your input--> <EditText android:id="@+id/idEdtLanguage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:hint="Enter your name to translate" android:padding="4dp" android:textColor="@color/black" android:textSize="20sp" /> <!--button to translate language of the input text--> <Button android:id="@+id/idBtnTranslateLanguage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idTVTranslatedLanguage" android:layout_centerInParent="true" android:text="Translate language" /> <!--text view to display the translated text--> <TextView android:id="@+id/idTVTranslatedLanguage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtLanguage" android:layout_centerHorizontal="true" android:layout_margin="20dp" android:gravity="center_horizontal" android:text="Translated language" android:textAlignment="center" android:textSize="20sp" /> </RelativeLayout> Step 6: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage;import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions; public class MainActivity extends AppCompatActivity { // creating variables for our image view, // text view and two buttons. private EditText edtLanguage; private TextView translateLanguageTV; private Button translateLanguageBtn; // create a variable for our // firebase language translator. FirebaseTranslator englishGermanTranslator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are creating our firebase translate option. FirebaseTranslatorOptions options = new FirebaseTranslatorOptions.Builder() // below line we are specifying our source language. .setSourceLanguage(FirebaseTranslateLanguage.EN) // in below line we are displaying our target language. .setTargetLanguage(FirebaseTranslateLanguage.DE) // after that we are building our options. .build(); // below line is to get instance // for firebase natural language. englishGermanTranslator = FirebaseNaturalLanguage.getInstance().getTranslator(options); // on below line we are initializing our variables. edtLanguage = findViewById(R.id.idEdtLanguage); translateLanguageTV = findViewById(R.id.idTVTranslatedLanguage); translateLanguageBtn = findViewById(R.id.idBtnTranslateLanguage); // adding on click listener for button translateLanguageBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to download language // modal to which we have to translate. String string = edtLanguage.getText().toString(); downloadModal(string); } }); } private void downloadModal(String input) { // below line is use to download the modal which // we will require to translate in german language FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder().requireWifi().build(); // below line is use to download our modal. englishGermanTranslator.downloadModelIfNeeded(conditions).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { // this method is called when modal is downloaded successfully. Toast.makeText(MainActivity.this, "Please wait language modal is being downloaded.", Toast.LENGTH_SHORT).show(); // calling method to translate our entered text. translateLanguage(input); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(MainActivity.this, "Fail to download modal", Toast.LENGTH_SHORT).show(); } }); } private void translateLanguage(String input) { englishGermanTranslator.translate(input).addOnSuccessListener(new OnSuccessListener<String>() { @Override public void onSuccess(String s) { translateLanguageTV.setText(s); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(MainActivity.this, "Fail to translate", Toast.LENGTH_SHORT).show(); } }); }} Now run your app and see the output of the app. Note: When you are using the app for the first time. It will take some time because it will download the modal in the background. We are not adding multiple language support in this application because for each language we have to download the language conversion model so it will make the app heavier and language translation will take so much time. Check out the project on the below link: https://github.com/ChinmayMunje/Firebase-ML-Kit kapoorsagar226 android Technical Scripter 2020 Android Java Machine Learning Technical Scripter Java Android Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Nov, 2021" }, { "code": null, "e": 278, "s": 54, "text": "In the previous article, we have seen using Language detector in Android using Firebase ML kit. In this article, we will take a look at the implementation of Language translator in Android using Firebase ML Kit in Android. " }, { "code": null, "e": 792, "s": 278, "text": "We will be building a simple application in which we will be showing an EditText field and we will add any input to that TextField. Along with that, we will be displaying a Button to translate that text to the German language. After clicking that button our text will be translated to the German language which we can get to see in the text view. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 821, "s": 792, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1732, "s": 821, "text": "How to Create Language Translator Android App? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersHow to Create Language Translator Android App? | 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 / 55:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=i58g-EPG5_s\" 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": 1894, "s": 1732, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1931, "s": 1894, "text": "Step 2: Connect your app to Firebase" }, { "code": null, "e": 2291, "s": 1931, "text": "After creating a new project in Android Studio connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Firebase ML and then click on Use Firebase ML kit in Android. You can see the option in the below screenshot. " }, { "code": null, "e": 2557, "s": 2291, "text": "After clicking on this option you will get to see the below screen. On this screen click on Connect to Firebase option to connect your app to Firebase. Click on Connect option to connect your app to Firebase and add the below dependency to your build.gradle file. " }, { "code": null, "e": 2629, "s": 2557, "text": "Step 3: Adding dependency for language translation to build.gradle file" }, { "code": null, "e": 2748, "s": 2629, "text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 2781, "s": 2748, "text": "// dependency for firebase core." }, { "code": null, "e": 2838, "s": 2781, "text": "implementation’com.google.firebase:firebase-core:15.0.2′" }, { "code": null, "e": 2894, "s": 2838, "text": "// below two dependency are used for language detection" }, { "code": null, "e": 2967, "s": 2894, "text": "implementation ‘com.google.firebase:firebase-ml-natural-language:22.0.0’" }, { "code": null, "e": 3056, "s": 2967, "text": "implementation ‘com.google.firebase:firebase-ml-natural-language-translate-model:20.0.8’" }, { "code": null, "e": 3126, "s": 3056, "text": "Step 4: Adding permissions to access the Internet in your Android App" }, { "code": null, "e": 3267, "s": 3126, "text": "Navigate to the app > AndroidManifest.xml file and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 3271, "s": 3267, "text": "XML" }, { "code": "<!--permission for internet--><uses-permission android:name=\"android.permission.INTERNET\"/>", "e": 3363, "s": 3271, "text": null }, { "code": null, "e": 3411, "s": 3363, "text": "Step 5: Working with the activity_main.xml file" }, { "code": null, "e": 3554, "s": 3411, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 3558, "s": 3554, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--edit text to enter your input--> <EditText android:id=\"@+id/idEdtLanguage\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"50dp\" android:hint=\"Enter your name to translate\" android:padding=\"4dp\" android:textColor=\"@color/black\" android:textSize=\"20sp\" /> <!--button to translate language of the input text--> <Button android:id=\"@+id/idBtnTranslateLanguage\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVTranslatedLanguage\" android:layout_centerInParent=\"true\" android:text=\"Translate language\" /> <!--text view to display the translated text--> <TextView android:id=\"@+id/idTVTranslatedLanguage\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtLanguage\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"20dp\" android:gravity=\"center_horizontal\" android:text=\"Translated language\" android:textAlignment=\"center\" android:textSize=\"20sp\" /> </RelativeLayout>", "e": 5119, "s": 3558, "text": null }, { "code": null, "e": 5167, "s": 5119, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 5357, "s": 5167, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5362, "s": 5357, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage;import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions; public class MainActivity extends AppCompatActivity { // creating variables for our image view, // text view and two buttons. private EditText edtLanguage; private TextView translateLanguageTV; private Button translateLanguageBtn; // create a variable for our // firebase language translator. FirebaseTranslator englishGermanTranslator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are creating our firebase translate option. FirebaseTranslatorOptions options = new FirebaseTranslatorOptions.Builder() // below line we are specifying our source language. .setSourceLanguage(FirebaseTranslateLanguage.EN) // in below line we are displaying our target language. .setTargetLanguage(FirebaseTranslateLanguage.DE) // after that we are building our options. .build(); // below line is to get instance // for firebase natural language. englishGermanTranslator = FirebaseNaturalLanguage.getInstance().getTranslator(options); // on below line we are initializing our variables. edtLanguage = findViewById(R.id.idEdtLanguage); translateLanguageTV = findViewById(R.id.idTVTranslatedLanguage); translateLanguageBtn = findViewById(R.id.idBtnTranslateLanguage); // adding on click listener for button translateLanguageBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to download language // modal to which we have to translate. String string = edtLanguage.getText().toString(); downloadModal(string); } }); } private void downloadModal(String input) { // below line is use to download the modal which // we will require to translate in german language FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder().requireWifi().build(); // below line is use to download our modal. englishGermanTranslator.downloadModelIfNeeded(conditions).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { // this method is called when modal is downloaded successfully. Toast.makeText(MainActivity.this, \"Please wait language modal is being downloaded.\", Toast.LENGTH_SHORT).show(); // calling method to translate our entered text. translateLanguage(input); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(MainActivity.this, \"Fail to download modal\", Toast.LENGTH_SHORT).show(); } }); } private void translateLanguage(String input) { englishGermanTranslator.translate(input).addOnSuccessListener(new OnSuccessListener<String>() { @Override public void onSuccess(String s) { translateLanguageTV.setText(s); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(MainActivity.this, \"Fail to translate\", Toast.LENGTH_SHORT).show(); } }); }}", "e": 9805, "s": 5362, "text": null }, { "code": null, "e": 9853, "s": 9805, "text": "Now run your app and see the output of the app." }, { "code": null, "e": 10206, "s": 9853, "text": "Note: When you are using the app for the first time. It will take some time because it will download the modal in the background. We are not adding multiple language support in this application because for each language we have to download the language conversion model so it will make the app heavier and language translation will take so much time. " }, { "code": null, "e": 10295, "s": 10206, "text": "Check out the project on the below link: https://github.com/ChinmayMunje/Firebase-ML-Kit" }, { "code": null, "e": 10310, "s": 10295, "text": "kapoorsagar226" }, { "code": null, "e": 10318, "s": 10310, "text": "android" }, { "code": null, "e": 10342, "s": 10318, "text": "Technical Scripter 2020" }, { "code": null, "e": 10350, "s": 10342, "text": "Android" }, { "code": null, "e": 10355, "s": 10350, "text": "Java" }, { "code": null, "e": 10372, "s": 10355, "text": "Machine Learning" }, { "code": null, "e": 10391, "s": 10372, "text": "Technical Scripter" }, { "code": null, "e": 10396, "s": 10391, "text": "Java" }, { "code": null, "e": 10404, "s": 10396, "text": "Android" }, { "code": null, "e": 10421, "s": 10404, "text": "Machine Learning" }, { "code": null, "e": 10519, "s": 10421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10588, "s": 10519, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 10620, "s": 10588, "text": "Android SDK and it's Components" }, { "code": null, "e": 10669, "s": 10620, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 10708, "s": 10669, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 10750, "s": 10708, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 10765, "s": 10750, "text": "Arrays in Java" }, { "code": null, "e": 10809, "s": 10765, "text": "Split() String method in Java with examples" }, { "code": null, "e": 10845, "s": 10809, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 10870, "s": 10845, "text": "Reverse a string in Java" } ]
Implementation of CI/CD in .NET application Using Shell Executor on GitLab
01 Mar, 2021 Shell Executor is a very simple executor which helps to build the solution locally on the machine, where GitLab Runner is installed. However, it also helps to run Bash and Windows PowerShell scripts and Windows Batch is deprecated. There will be a few requirements and path configuration need to set up GitLab Runner in Shell Executor mode and start implementation on it. Shell Executor: Shell Executor is a very simple executor that helps to build the solution locally on the machine, where GitLab Runner is installed. In this case, GitLab Runner is installed on Linux Machine, so need to install the required software in the same system. Requirements: Software Description This is the first requirements, to commit the changes on GitLab. It is a version control software that tracks the changing set of files. The work of the GitLab Runner is to pick up and execute the job (when a new commit happens). Download MSBuild.exe and save it in your local directory, It helps to build the project when GitLab Runner pick up the job. If in a machine, Visual Studio is already installed then It will not be needed to install. It can be found C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe (find based on Visual Studio version) Download Nuget.exe and save it, in the same directory where MSBuild is available. Path Configuration: Software/File Path Description After Successfully installation of Git on the machine. The below path needs to set to communicate with GitLab repository. Go to System Environment Variable, add these two with User Variable path C:\Program Files\Git C:\Program Files\Git\bin Nuget.exe path will also be needed in Yml file, while configuration with GitLab. For Example, C:\Tools\Nuget\nuget.exe or where your Nuget is available. This is useful to run the test cases of .Net,in Visual Studio 2019, it is available in C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\mstest.exe This file should be inside the root directory of the project which contains all the CI/CD configuration including software and script path. Here, you can mention how this repository should run. Before adding this file to the root directory, should check it is a valid yml file or not. GitLab Runner Set Up: Follow the below steps to download and configure the GitLab Runner. 1. Download GitLab Runner for Windows 2. After downloading successfully, save it in your directory (For ex: C:\Tools\GitLab-Runner), and rename it with the following command gitlab-runner.exe 3. Open Command Prompt on Admin Mode, go to GitLab-Runner directory and check the status of it using gitlab-runner status 4. If it is already running, stop it before registering a repository with GitLab Runner gitlab-runner.exe stop 5. Once GitLab Runner has successfully stopped then use the following command for the repository registration gitlab-runner.exe register 6. When you do repository registration with GitLab Runner, the below questions have to answer. Enter your GitLab instance URL: It can be different with each organization and format will be like http://gitlab.example.com Path: Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner Enter the gitlab-ci token for this runner: It will be a unique token of each project which will need while registration and it can be found Path: Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner Enter the gitlab-ci description for this runner: Put Runner name(any name), which will help you to remember that which runner’ is running Enter the gitlab-ci tags for this runner: It is an optional, if you want to start GitLab runner when specific tag is available in yml file. Enter the executor: There will be list of several executors, and type shell(as GitLab Runner will run our system) 7. After successful registration, start the GitLab Runner gitlab-runner start 8. To verify that GitLab Runner has registered the respective repository and the runner has been started. Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner, There will be a green color circle will be available, and displaying message will be Runners activated for this project. Note: If the circle is gray, it means the runner has not started and starts again. Windows GitLab Runner Command Description .gitlab-ci.yml: This is a format of .gitlab-ci.yml and changes it based on requirements variables: NUGET_PATH: 'C:\Tools\Nuget\nuget.exe' MSBUILD_PATH: 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe' MSTEST_PATH: 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\mstest.exe' TEST_FOLDER: '.\test\bin\Release' stages: - build - test - deploy before_script: - '& "$env:NUGET_PATH" restore sourcecode\project.sln' # sourcecode\project.sln-This path includes project solution where is available and restoring - '& "$env:NUGET_PATH" restore test\test.sln' # This path includes test solution where is available. and restoring build_job: stage: build only: - developer #this branch will run on GitLab Runner and can change it. script: - '& "$env:MSBUILD_PATH" sourcecode\project.sln /p:DeployOnBuild=true /p:Configuration=Release /p:Platform="Any CPU" /P:PublishProfile=FolderProfile.pubxml' - '& "$env:MSBUILD_PATH" test\test.sln /p:DeployOnBuild=true /p:Configuration=Release /p:Platform="Any CPU" /P:PublishProfile=FolderProfile.pubxml' artifacts: expire_in: 365 days #artifcats will be stored only 365 days after this it will expire paths: - '.\sourcecode\project.sln\bin\Release\Publish\' - '.\sourcecode\project.sln\bin\Publish\' - '$env:TEST_FOLDER' - '.\$env:MSTEST_PATH\*.*' test_job: stage: test only: - developer #this branch will run on GitLab Runner and can change it. script: - .\test\test.bat #This is bat file, if the test are written in script format dependencies: - build_job deploy_job: stage: deploy only: - developer #this branch will run on GitLab Runner and can change it. script: - 'xcopy /y /s ".\sourcecode\project.sln\bin\Release\Publish\*.*" "C:\solutionDir"' #Path where you want to store the solution dependencies: #after successfully build, only test stage will run - build_job - test_job Code Commit: After successful configuration, do commit and see the job status on GitLab. Go to Project repository → Select CI/CD menu Dot-NET Advanced Computer Subject C# Git Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Copying Files to and from Docker Containers Basics of API Testing Using Postman Markov Decision Process Getting Started with System Design Difference between Abstract Class and Interface in C# C# Dictionary with examples C# | How to check whether a List contains a specified element C# | Arrays of Strings C# | IsNullOrEmpty() Method
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Mar, 2021" }, { "code": null, "e": 426, "s": 54, "text": "Shell Executor is a very simple executor which helps to build the solution locally on the machine, where GitLab Runner is installed. However, it also helps to run Bash and Windows PowerShell scripts and Windows Batch is deprecated. There will be a few requirements and path configuration need to set up GitLab Runner in Shell Executor mode and start implementation on it." }, { "code": null, "e": 694, "s": 426, "text": "Shell Executor: Shell Executor is a very simple executor that helps to build the solution locally on the machine, where GitLab Runner is installed. In this case, GitLab Runner is installed on Linux Machine, so need to install the required software in the same system." }, { "code": null, "e": 708, "s": 694, "text": "Requirements:" }, { "code": null, "e": 717, "s": 708, "text": "Software" }, { "code": null, "e": 731, "s": 717, "text": "Description " }, { "code": null, "e": 868, "s": 731, "text": "This is the first requirements, to commit the changes on GitLab. It is a version control software that tracks the changing set of files." }, { "code": null, "e": 961, "s": 868, "text": "The work of the GitLab Runner is to pick up and execute the job (when a new commit happens)." }, { "code": null, "e": 1325, "s": 961, "text": "Download MSBuild.exe and save it in your local directory, It helps to build the project when GitLab Runner pick up the job. If in a machine, Visual Studio is already installed then It will not be needed to install. It can be found C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\MSBuild\\Current\\Bin\\MSBuild.exe (find based on Visual Studio version)" }, { "code": null, "e": 1407, "s": 1325, "text": "Download Nuget.exe and save it, in the same directory where MSBuild is available." }, { "code": null, "e": 1428, "s": 1407, "text": " Path Configuration:" }, { "code": null, "e": 1442, "s": 1428, "text": "Software/File" }, { "code": null, "e": 1460, "s": 1442, "text": "Path Description " }, { "code": null, "e": 1655, "s": 1460, "text": "After Successfully installation of Git on the machine. The below path needs to set to communicate with GitLab repository. Go to System Environment Variable, add these two with User Variable path" }, { "code": null, "e": 1676, "s": 1655, "text": "C:\\Program Files\\Git" }, { "code": null, "e": 1701, "s": 1676, "text": "C:\\Program Files\\Git\\bin" }, { "code": null, "e": 1855, "s": 1701, "text": "Nuget.exe path will also be needed in Yml file, while configuration with GitLab. For Example, C:\\Tools\\Nuget\\nuget.exe or where your Nuget is available. " }, { "code": null, "e": 2028, "s": 1855, "text": "This is useful to run the test cases of .Net,in Visual Studio 2019, it is available in C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\Common7\\IDE\\mstest.exe" }, { "code": null, "e": 2313, "s": 2028, "text": "This file should be inside the root directory of the project which contains all the CI/CD configuration including software and script path. Here, you can mention how this repository should run. Before adding this file to the root directory, should check it is a valid yml file or not." }, { "code": null, "e": 2404, "s": 2313, "text": " GitLab Runner Set Up: Follow the below steps to download and configure the GitLab Runner." }, { "code": null, "e": 2442, "s": 2404, "text": "1. Download GitLab Runner for Windows" }, { "code": null, "e": 2578, "s": 2442, "text": "2. After downloading successfully, save it in your directory (For ex: C:\\Tools\\GitLab-Runner), and rename it with the following command" }, { "code": null, "e": 2596, "s": 2578, "text": "gitlab-runner.exe" }, { "code": null, "e": 2698, "s": 2596, "text": "3. Open Command Prompt on Admin Mode, go to GitLab-Runner directory and check the status of it using " }, { "code": null, "e": 2719, "s": 2698, "text": "gitlab-runner status" }, { "code": null, "e": 2808, "s": 2719, "text": "4. If it is already running, stop it before registering a repository with GitLab Runner " }, { "code": null, "e": 2831, "s": 2808, "text": "gitlab-runner.exe stop" }, { "code": null, "e": 2941, "s": 2831, "text": "5. Once GitLab Runner has successfully stopped then use the following command for the repository registration" }, { "code": null, "e": 2968, "s": 2941, "text": "gitlab-runner.exe register" }, { "code": null, "e": 3063, "s": 2968, "text": "6. When you do repository registration with GitLab Runner, the below questions have to answer." }, { "code": null, "e": 3208, "s": 3063, "text": "Enter your GitLab instance URL: It can be different with each organization and format will be like http://gitlab.example.com " }, { "code": null, "e": 3329, "s": 3208, "text": "Path: Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner" }, { "code": null, "e": 3473, "s": 3329, "text": "Enter the gitlab-ci token for this runner: It will be a unique token of each project which will need while registration and it can be found " }, { "code": null, "e": 3594, "s": 3473, "text": "Path: Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner" }, { "code": null, "e": 3732, "s": 3594, "text": "Enter the gitlab-ci description for this runner: Put Runner name(any name), which will help you to remember that which runner’ is running" }, { "code": null, "e": 3872, "s": 3732, "text": "Enter the gitlab-ci tags for this runner: It is an optional, if you want to start GitLab runner when specific tag is available in yml file." }, { "code": null, "e": 3986, "s": 3872, "text": "Enter the executor: There will be list of several executors, and type shell(as GitLab Runner will run our system)" }, { "code": null, "e": 4045, "s": 3986, "text": "7. After successful registration, start the GitLab Runner " }, { "code": null, "e": 4065, "s": 4045, "text": "gitlab-runner start" }, { "code": null, "e": 4410, "s": 4065, "text": "8. To verify that GitLab Runner has registered the respective repository and the runner has been started. Go to GitLab Account → Select repository which you want to register with runner → Settings → CI/CD → Expand Runner, There will be a green color circle will be available, and displaying message will be Runners activated for this project. " }, { "code": null, "e": 4493, "s": 4410, "text": "Note: If the circle is gray, it means the runner has not started and starts again." }, { "code": null, "e": 4524, "s": 4493, "text": " Windows GitLab Runner Command" }, { "code": null, "e": 4537, "s": 4524, "text": "Description " }, { "code": null, "e": 4627, "s": 4537, "text": ".gitlab-ci.yml: This is a format of .gitlab-ci.yml and changes it based on requirements " }, { "code": null, "e": 6586, "s": 4627, "text": "variables:\n NUGET_PATH: 'C:\\Tools\\Nuget\\nuget.exe'\n MSBUILD_PATH: 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\MSBuild\\Current\\Bin\\MSBuild.exe'\n MSTEST_PATH: 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\Common7\\IDE\\mstest.exe'\n TEST_FOLDER: '.\\test\\bin\\Release'\n \nstages:\n - build\n - test\n - deploy\n \nbefore_script: \n - '& \"$env:NUGET_PATH\" restore sourcecode\\project.sln' # sourcecode\\project.sln-This path includes project solution where is available and restoring\n - '& \"$env:NUGET_PATH\" restore test\\test.sln' # This path includes test solution where is available. and restoring \n \nbuild_job:\n stage: build\n only:\n - developer #this branch will run on GitLab Runner and can change it. \n script: \n - '& \"$env:MSBUILD_PATH\" sourcecode\\project.sln /p:DeployOnBuild=true /p:Configuration=Release /p:Platform=\"Any CPU\" /P:PublishProfile=FolderProfile.pubxml' \n - '& \"$env:MSBUILD_PATH\" test\\test.sln /p:DeployOnBuild=true /p:Configuration=Release /p:Platform=\"Any CPU\" /P:PublishProfile=FolderProfile.pubxml' \n \n artifacts:\n expire_in: 365 days #artifcats will be stored only 365 days after this it will expire \n paths:\n - '.\\sourcecode\\project.sln\\bin\\Release\\Publish\\'\n - '.\\sourcecode\\project.sln\\bin\\Publish\\'\n - '$env:TEST_FOLDER'\n - '.\\$env:MSTEST_PATH\\*.*'\n\ntest_job:\n stage: test\n only:\n - developer #this branch will run on GitLab Runner and can change it. \n script:\n - .\\test\\test.bat #This is bat file, if the test are written in script format \n \n dependencies:\n - build_job\n\ndeploy_job:\n stage: deploy\n only:\n - developer #this branch will run on GitLab Runner and can change it. \n script:\n - 'xcopy /y /s \".\\sourcecode\\project.sln\\bin\\Release\\Publish\\*.*\" \"C:\\solutionDir\"' #Path where you want to store the solution \n \n \n dependencies: #after successfully build, only test stage will run \n - build_job\n - test_job" }, { "code": null, "e": 6721, "s": 6586, "text": "Code Commit: After successful configuration, do commit and see the job status on GitLab. Go to Project repository → Select CI/CD menu " }, { "code": null, "e": 6729, "s": 6721, "text": "Dot-NET" }, { "code": null, "e": 6755, "s": 6729, "text": "Advanced Computer Subject" }, { "code": null, "e": 6758, "s": 6755, "text": "C#" }, { "code": null, "e": 6762, "s": 6758, "text": "Git" }, { "code": null, "e": 6860, "s": 6762, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6896, "s": 6860, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 6940, "s": 6896, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 6976, "s": 6940, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 7000, "s": 6976, "text": "Markov Decision Process" }, { "code": null, "e": 7035, "s": 7000, "text": "Getting Started with System Design" }, { "code": null, "e": 7089, "s": 7035, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 7117, "s": 7089, "text": "C# Dictionary with examples" }, { "code": null, "e": 7179, "s": 7117, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 7202, "s": 7179, "text": "C# | Arrays of Strings" } ]
GATE | GATE CS 2012 | Question 17
28 Jun, 2021 Let G be a simple undirected planar graph on 10 vertices with 15 edges. If G is a connected graph, then the number of bounded faces in any embedding of G on the plane is equal to(A) 3(B) 4(C) 5(D) 6Answer: (D)Explanation: If the graph is planar, then it must follow below Euler’s Formula for planar graphs v - e + f = 2 v is number of vertices e is number of edges f is number of faces including bounded and unbounded 10 - 15 + f = 2 f = 7 There is always one unbounded face, so the number of bounded faces = 6 Quiz of this Question GATE-CS-2012 GATE-GATE CS 2012 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE CS 2008 | Question 40 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 360, "s": 54, "text": "Let G be a simple undirected planar graph on 10 vertices with 15 edges. If G is a connected graph, then the number of bounded faces in any embedding of G on the plane is equal to(A) 3(B) 4(C) 5(D) 6Answer: (D)Explanation: If the graph is planar, then it must follow below Euler’s Formula for planar graphs" }, { "code": null, "e": 567, "s": 360, "text": "v - e + f = 2\nv is number of vertices\ne is number of edges\nf is number of faces including bounded and unbounded\n\n10 - 15 + f = 2\nf = 7\nThere is always one unbounded face, so the number of bounded faces = 6" }, { "code": null, "e": 589, "s": 567, "text": "Quiz of this Question" }, { "code": null, "e": 602, "s": 589, "text": "GATE-CS-2012" }, { "code": null, "e": 620, "s": 602, "text": "GATE-GATE CS 2012" }, { "code": null, "e": 625, "s": 620, "text": "GATE" }, { "code": null, "e": 723, "s": 625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 765, "s": 723, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 827, "s": 765, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 869, "s": 827, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 903, "s": 869, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 937, "s": 903, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 979, "s": 937, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1021, "s": 979, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1055, "s": 1021, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 1089, "s": 1055, "text": "GATE | GATE CS 1996 | Question 38" } ]
Python | Numpy matrix.diagonal()
12 Apr, 2019 With the help of Numpy matrix.diagonal() method, we are able to find a diagonal element from a given matrix and gives output as one dimensional matrix. Syntax : matrix.diagonal() Return : Return diagonal element of a matrix Example #1 :In this example we can see that with the help of matrix.diagonal() method we are able to find the elements in a diagonal of a matrix. # import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[6, 2; 3, 4]') # applying matrix.diagonal() methodgeeks = gfg.diagonal() print(geeks) [[6 4]] Example #2 : # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.diagonal() methodgeeks = gfg.diagonal() print(geeks) [[1 5 9]] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Apr, 2019" }, { "code": null, "e": 205, "s": 53, "text": "With the help of Numpy matrix.diagonal() method, we are able to find a diagonal element from a given matrix and gives output as one dimensional matrix." }, { "code": null, "e": 232, "s": 205, "text": "Syntax : matrix.diagonal()" }, { "code": null, "e": 277, "s": 232, "text": "Return : Return diagonal element of a matrix" }, { "code": null, "e": 423, "s": 277, "text": "Example #1 :In this example we can see that with the help of matrix.diagonal() method we are able to find the elements in a diagonal of a matrix." }, { "code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[6, 2; 3, 4]') # applying matrix.diagonal() methodgeeks = gfg.diagonal() print(geeks)", "e": 626, "s": 423, "text": null }, { "code": null, "e": 635, "s": 626, "text": "[[6 4]]\n" }, { "code": null, "e": 648, "s": 635, "text": "Example #2 :" }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.diagonal() methodgeeks = gfg.diagonal() print(geeks)", "e": 868, "s": 648, "text": null }, { "code": null, "e": 879, "s": 868, "text": "[[1 5 9]]\n" }, { "code": null, "e": 908, "s": 879, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 921, "s": 908, "text": "Python-numpy" }, { "code": null, "e": 928, "s": 921, "text": "Python" } ]
Difference between Abstraction and Encapsulation in C++
06 Oct, 2021 Abstraction: In OOPs, Abstraction is the method of getting information where the information needed will be taken in such a simplest way that solely the required components are extracted, and also the ones that are considered less significant are unnoticed. The concept of abstraction only shows necessary information to the users. It reduces the complexity of the program by hiding the implementation complexities of programs. Example of Abstraction: CPP #include <iostream>using namespace std; class Summation {private: // private variables int a, b, c;public: void sum(int x, int y) { a = x; b = y; c = a + b; cout<<"Sum of the two number is : "<<c<<endl; }};int main(){ Summation s; s.sum(5, 4); return 0;} Output: Sum of the two number is: 9 In the this example, we can see that abstraction has achieved by using class. The class ‘Summation’ holds the private members a, b and c, which are only accessible by the member functions of that class.Encapsulation: Encapsulation is the process or method to contain the information. Encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside world. This method encapsulates the data and function together inside a class which also results in data abstraction. Example of Encapsulation: CPP #include <iostream>using namespace std; class EncapsulationExample {private: // we declare a as private to hide it from outside int a; public: // set() function to set the value of a void set(int x) { a = x; } // get() function to return the value of a int get() { return a; }}; // main functionint main(){ EncapsulationExample e1; e1.set(10); cout<<e1.get(); return 0;} Output: 10 In the this program, the variable a is made private so that this variable can be accessed and manipulated only by using the methods get() and set() that are present within the class. Therefore we can say that, the variable a and the methods set() as well as get() have binded together that is nothing but encapsulation.Difference between Abstraction and Encapsulation: tanya_dixit17 cpp-class C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Oct, 2021" }, { "code": null, "e": 507, "s": 54, "text": "Abstraction: In OOPs, Abstraction is the method of getting information where the information needed will be taken in such a simplest way that solely the required components are extracted, and also the ones that are considered less significant are unnoticed. The concept of abstraction only shows necessary information to the users. It reduces the complexity of the program by hiding the implementation complexities of programs. Example of Abstraction: " }, { "code": null, "e": 511, "s": 507, "text": "CPP" }, { "code": "#include <iostream>using namespace std; class Summation {private: // private variables int a, b, c;public: void sum(int x, int y) { a = x; b = y; c = a + b; cout<<\"Sum of the two number is : \"<<c<<endl; }};int main(){ Summation s; s.sum(5, 4); return 0;}", "e": 818, "s": 511, "text": null }, { "code": null, "e": 828, "s": 818, "text": "Output: " }, { "code": null, "e": 857, "s": 828, "text": "Sum of the two number is: 9 " }, { "code": null, "e": 1412, "s": 857, "text": "In the this example, we can see that abstraction has achieved by using class. The class ‘Summation’ holds the private members a, b and c, which are only accessible by the member functions of that class.Encapsulation: Encapsulation is the process or method to contain the information. Encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside world. This method encapsulates the data and function together inside a class which also results in data abstraction. Example of Encapsulation: " }, { "code": null, "e": 1416, "s": 1412, "text": "CPP" }, { "code": "#include <iostream>using namespace std; class EncapsulationExample {private: // we declare a as private to hide it from outside int a; public: // set() function to set the value of a void set(int x) { a = x; } // get() function to return the value of a int get() { return a; }}; // main functionint main(){ EncapsulationExample e1; e1.set(10); cout<<e1.get(); return 0;}", "e": 1847, "s": 1416, "text": null }, { "code": null, "e": 1857, "s": 1847, "text": "Output: " }, { "code": null, "e": 1860, "s": 1857, "text": "10" }, { "code": null, "e": 2230, "s": 1860, "text": "In the this program, the variable a is made private so that this variable can be accessed and manipulated only by using the methods get() and set() that are present within the class. Therefore we can say that, the variable a and the methods set() as well as get() have binded together that is nothing but encapsulation.Difference between Abstraction and Encapsulation: " }, { "code": null, "e": 2246, "s": 2232, "text": "tanya_dixit17" }, { "code": null, "e": 2256, "s": 2246, "text": "cpp-class" }, { "code": null, "e": 2260, "s": 2256, "text": "C++" }, { "code": null, "e": 2279, "s": 2260, "text": "Difference Between" }, { "code": null, "e": 2283, "s": 2279, "text": "CPP" } ]
COUNT() Function in MySQL - GeeksforGeeks
22 Jan, 2021 COUNT() function : This function in MySQL is used to find the number of indexes as returned from the query selected. Features : This function is used to find the number of indexes as returned from the query selected. This function comes under Numeric Functions. This function accepts only one parameter namely expression. This function ignore NULL values and doesn’t count them. Syntax : COUNT(expression) Parameter : This method accepts only one parameter as given below: expression: Specified expression which can either be a field or a string type value. Returns : It returns the number of indexes as returned from the query selected. Example-1 : Using COUNT() function and getting the output. CREATE TABLE product ( user_id int NOT NULL AUTO_INCREMENT, product_1 VARCHAR(10), product_2 VARCHAR(10), price int , PRIMARY KEY(user_id) ); INSERT product(product_1, price) VALUES ('rice', 400); INSERT product(product_2, price) VALUES ('grains', 600); SELECT COUNT(user_id) FROM product; Output : 2 Example-2 : Using COUNT() function and counting float values. CREATE TABLE floats ( user_id int NOT NULL AUTO_INCREMENT, float_val float, PRIMARY KEY(user_id) ); INSERT floats(float_val) VALUES (3.5); INSERT floats(float_val) VALUES (2.1); INSERT floats(float_val) VALUES (6.3); INSERT floats(float_val) VALUES (9.9); INSERT floats(float_val) VALUES (7.0); SELECT COUNT(float_val) FROM floats; Output : 5 Example-3 : Using COUNT() function and getting the output where MRP is greater than the number of counts of MRP. CREATE TABLE package ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10), mrp int, PRIMARY KEY(user_id) ); INSERT package(item, mrp) VALUES ('book1', 3); INSERT package(item, mrp) VALUES ('book2', 350); INSERT package(item, mrp) VALUES ('book3', 400); SELECT * FROM package WHERE mrp > (SELECT COUNT(mrp) FROM package); Output : user_id | item | mrp -------------------------------- 2 | book2 | 350 -------------------------------- 3 | book3 | 400 Example-4 : Using COUNT() function and getting the records of (MRP-sales price). CREATE TABLE package01 ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10), mrp int, sp int, PRIMARY KEY(user_id) ); INSERT package01(item, mrp, sp) VALUES ('book1', 250, 240); INSERT package01(item, mrp, sp) VALUES ('book2', 350, 320); INSERT package01(item, mrp) VALUES ('book3', 400); SELECT COUNT(mrp-sp) FROM package01; Output : 2 Application : This function is used to find the number of indexes as returned from the query selected. DBMS-SQL mysql 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? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery How to Write a SQL Query For a Specific Date Range and Date Time? SQL Query to Convert VARCHAR to INT How to Select Data Between Two Dates and Times in SQL Server? SQL - SELECT from Multiple Tables with MS SQL Server SQL Query to Delete Duplicate Rows
[ { "code": null, "e": 24268, "s": 24240, "text": "\n22 Jan, 2021" }, { "code": null, "e": 24287, "s": 24268, "text": "COUNT() function :" }, { "code": null, "e": 24385, "s": 24287, "text": "This function in MySQL is used to find the number of indexes as returned from the query selected." }, { "code": null, "e": 24396, "s": 24385, "text": "Features :" }, { "code": null, "e": 24485, "s": 24396, "text": "This function is used to find the number of indexes as returned from the query selected." }, { "code": null, "e": 24530, "s": 24485, "text": "This function comes under Numeric Functions." }, { "code": null, "e": 24590, "s": 24530, "text": "This function accepts only one parameter namely expression." }, { "code": null, "e": 24647, "s": 24590, "text": "This function ignore NULL values and doesn’t count them." }, { "code": null, "e": 24656, "s": 24647, "text": "Syntax :" }, { "code": null, "e": 24674, "s": 24656, "text": "COUNT(expression)" }, { "code": null, "e": 24686, "s": 24674, "text": "Parameter :" }, { "code": null, "e": 24741, "s": 24686, "text": "This method accepts only one parameter as given below:" }, { "code": null, "e": 24826, "s": 24741, "text": "expression: Specified expression which can either be a field or a string type value." }, { "code": null, "e": 24836, "s": 24826, "text": "Returns :" }, { "code": null, "e": 24906, "s": 24836, "text": "It returns the number of indexes as returned from the query selected." }, { "code": null, "e": 24918, "s": 24906, "text": "Example-1 :" }, { "code": null, "e": 24965, "s": 24918, "text": "Using COUNT() function and getting the output." }, { "code": null, "e": 25268, "s": 24965, "text": "CREATE TABLE product\n( \nuser_id int NOT NULL AUTO_INCREMENT, \nproduct_1 VARCHAR(10),\nproduct_2 VARCHAR(10),\nprice int , \nPRIMARY KEY(user_id) \n);\nINSERT product(product_1, price) \nVALUES ('rice', 400);\n\nINSERT product(product_2, price) \nVALUES ('grains', 600);\n\nSELECT COUNT(user_id) FROM product;" }, { "code": null, "e": 25277, "s": 25268, "text": "Output :" }, { "code": null, "e": 25279, "s": 25277, "text": "2" }, { "code": null, "e": 25291, "s": 25279, "text": "Example-2 :" }, { "code": null, "e": 25341, "s": 25291, "text": "Using COUNT() function and counting float values." }, { "code": null, "e": 25694, "s": 25341, "text": "CREATE TABLE floats\n( \nuser_id int NOT NULL AUTO_INCREMENT, \nfloat_val float,\nPRIMARY KEY(user_id) \n);\nINSERT floats(float_val) \nVALUES (3.5);\n\nINSERT floats(float_val) \nVALUES (2.1);\n\nINSERT floats(float_val) \nVALUES (6.3);\n\nINSERT floats(float_val) \nVALUES (9.9);\n\nINSERT floats(float_val) \nVALUES (7.0);\n\nSELECT COUNT(float_val) FROM floats;" }, { "code": null, "e": 25703, "s": 25694, "text": "Output :" }, { "code": null, "e": 25705, "s": 25703, "text": "5" }, { "code": null, "e": 25717, "s": 25705, "text": "Example-3 :" }, { "code": null, "e": 25818, "s": 25717, "text": "Using COUNT() function and getting the output where MRP is greater than the number of counts of MRP." }, { "code": null, "e": 26159, "s": 25818, "text": "CREATE TABLE package\n( \nuser_id int NOT NULL AUTO_INCREMENT, \nitem VARCHAR(10),\nmrp int,\nPRIMARY KEY(user_id) \n);\nINSERT package(item, mrp) \nVALUES ('book1', 3);\n\nINSERT package(item, mrp) \nVALUES ('book2', 350);\n\nINSERT package(item, mrp) \nVALUES ('book3', 400);\n\nSELECT * FROM package\nWHERE mrp > (SELECT COUNT(mrp) FROM package);" }, { "code": null, "e": 26168, "s": 26159, "text": "Output :" }, { "code": null, "e": 26315, "s": 26168, "text": " user_id | item | mrp\n--------------------------------\n 2 | book2 | 350\n--------------------------------\n 3 | book3 | 400" }, { "code": null, "e": 26327, "s": 26315, "text": "Example-4 :" }, { "code": null, "e": 26396, "s": 26327, "text": "Using COUNT() function and getting the records of (MRP-sales price)." }, { "code": null, "e": 26742, "s": 26396, "text": "CREATE TABLE package01\n( \nuser_id int NOT NULL AUTO_INCREMENT, \nitem VARCHAR(10),\nmrp int,\nsp int,\nPRIMARY KEY(user_id) \n);\nINSERT package01(item, mrp, sp) \nVALUES ('book1', 250, 240);\n\nINSERT package01(item, mrp, sp) \nVALUES ('book2', 350, 320);\n\nINSERT package01(item, mrp) \nVALUES ('book3', 400);\n\nSELECT COUNT(mrp-sp) FROM package01;" }, { "code": null, "e": 26751, "s": 26742, "text": "Output :" }, { "code": null, "e": 26753, "s": 26751, "text": "2" }, { "code": null, "e": 26767, "s": 26753, "text": "Application :" }, { "code": null, "e": 26856, "s": 26767, "text": "This function is used to find the number of indexes as returned from the query selected." }, { "code": null, "e": 26865, "s": 26856, "text": "DBMS-SQL" }, { "code": null, "e": 26871, "s": 26865, "text": "mysql" }, { "code": null, "e": 26875, "s": 26871, "text": "SQL" }, { "code": null, "e": 26879, "s": 26875, "text": "SQL" }, { "code": null, "e": 26977, "s": 26879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27043, "s": 26977, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27075, "s": 27043, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27153, "s": 27075, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27170, "s": 27153, "text": "SQL using Python" }, { "code": null, "e": 27185, "s": 27170, "text": "SQL | Subquery" }, { "code": null, "e": 27251, "s": 27185, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27287, "s": 27251, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27349, "s": 27287, "text": "How to Select Data Between Two Dates and Times in SQL Server?" }, { "code": null, "e": 27402, "s": 27349, "text": "SQL - SELECT from Multiple Tables with MS SQL Server" } ]
Groovy - getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. public long getTime() None. The number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date. Following is an example of the usage of this method − class Example { static void main(String[] args) { Date olddate = new Date("05/11/2015"); Date newdate = new Date("05/11/2015"); Date latestdate = new Date(); System.out.println(olddate.getTime()); System.out.println(newdate.getTime()); System.out.println(latestdate.getTime()); } } When we run the above program, we will get the following result − 1431288000000 1431288000000 1449769878348 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2342, "s": 2238, "text": "Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object." }, { "code": null, "e": 2365, "s": 2342, "text": "public long getTime()\n" }, { "code": null, "e": 2371, "s": 2365, "text": "None." }, { "code": null, "e": 2460, "s": 2371, "text": "The number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date." }, { "code": null, "e": 2514, "s": 2460, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 2852, "s": 2514, "text": "class Example { \n static void main(String[] args) { \n Date olddate = new Date(\"05/11/2015\");\n Date newdate = new Date(\"05/11/2015\"); \n Date latestdate = new Date(); \n\t\t\n System.out.println(olddate.getTime()); \n System.out.println(newdate.getTime()); \n System.out.println(latestdate.getTime()); \n } \n}\t " }, { "code": null, "e": 2918, "s": 2852, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 2963, "s": 2918, "text": "1431288000000 \n1431288000000 \n1449769878348\n" }, { "code": null, "e": 2996, "s": 2963, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 3014, "s": 2996, "text": " Krishna Sakinala" }, { "code": null, "e": 3049, "s": 3014, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3067, "s": 3049, "text": " Packt Publishing" }, { "code": null, "e": 3074, "s": 3067, "text": " Print" }, { "code": null, "e": 3085, "s": 3074, "text": " Add Notes" } ]
How to set background color in jQuery?
To set the background color using jQuery, use the jQuery css() property. We will set background color on mouse hover with the jQuery on() method. You can try to run the following color to set background color in jQuery. Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("body").on({ mouseenter: function(){ $(this).css("background-color", "gray"); }, }); }); </script> </head> <body> <p>Move the mouse pointer on the page to change the background color.</p> </body> </html>
[ { "code": null, "e": 1208, "s": 1062, "text": "To set the background color using jQuery, use the jQuery css() property. We will set background color on mouse hover with the jQuery on() method." }, { "code": null, "e": 1282, "s": 1208, "text": "You can try to run the following color to set background color in jQuery." }, { "code": null, "e": 1292, "s": 1282, "text": "Live Demo" }, { "code": null, "e": 1698, "s": 1292, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"body\").on({\n mouseenter: function(){\n $(this).css(\"background-color\", \"gray\");\n }, \n }); \n});\n</script>\n</head>\n<body>\n<p>Move the mouse pointer on the page to change the background color.</p>\n</body>\n</html>" } ]
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 - GeeksforGeeks
18 Jan, 2022 What is Minimum Spanning Tree? Given a connected and undirected graph, a spanning tree of that graph is a subgraph that is a tree and connects all the vertices together. A single graph can have many different spanning trees. A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected, undirected graph is a spanning tree with a weight less than or equal to the weight of every other spanning tree. The weight of a spanning tree is the sum of weights given to each edge of the spanning tree.How many edges does a minimum spanning tree has? A minimum spanning tree has (V – 1) edges where V is the number of vertices in the given graph. What are the applications of the Minimum Spanning Tree? See this for applications of MST. Below are the steps for finding MST using Kruskal’s algorithm 1. Sort all the edges in non-decreasing order of their weight. 2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. 3. Repeat step#2 until there are (V-1) edges in the spanning tree. Step #2 uses the Union-Find algorithm to detect cycles. So we recommend reading the following post as a prerequisite. Union-Find Algorithm | Set 1 (Detect Cycle in a Graph) Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)The algorithm is a Greedy Algorithm. The Greedy Choice is to pick the smallest weight edge that does not cause a cycle in the MST constructed so far. Let us understand it with an example: Consider the below input graph. The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will be having (9 – 1) = 8 edges. After sorting: Weight Src Dest 1 7 6 2 8 2 2 6 5 4 0 1 4 2 5 6 8 6 7 2 3 7 7 8 8 0 7 8 1 2 9 3 4 10 5 4 11 1 7 14 3 5 Now pick all edges one by one from the sorted list of edges 1. Pick edge 7-6: No cycle is formed, include it. 2. Pick edge 8-2: No cycle is formed, include it. 3. Pick edge 6-5: No cycle is formed, include it. 4. Pick edge 0-1: No cycle is formed, include it. 5. Pick edge 2-5: No cycle is formed, include it. 6. Pick edge 8-6: Since including this edge results in the cycle, discard it.7. Pick edge 2-3: No cycle is formed, include it. 8. Pick edge 7-8: Since including this edge results in the cycle, discard it.9. Pick edge 0-7: No cycle is formed, include it. 10. Pick edge 1-2: Since including this edge results in the cycle, discard it.11. Pick edge 3-4: No cycle is formed, include it. Since the number of edges included equals (V – 1), the algorithm stops here. Below is the implementation of the above idea: Java Python3 C# C++ // Java program for Kruskal's algorithm to// find Minimum Spanning Tree of a given//connected, undirected and weighted graphimport java.util.*;import java.lang.*;import java.io.*; class Graph { // A class to represent a graph edge class Edge implements Comparable<Edge> { int src, dest, weight; // Comparator function used for // sorting edgesbased on their weight public int compareTo(Edge compareEdge) { return this.weight - compareEdge.weight; } }; // A class to represent a subset for // union-find class subset { int parent, rank; }; int V, E; // V-> no. of vertices & E->no.of edges Edge edge[]; // collection of all edges // Creates a graph with V vertices and E edges Graph(int v, int e) { V = v; E = e; edge = new Edge[E]; for (int i = 0; i < e; ++i) edge[i] = new Edge(); } // A utility function to find set of an // element i (uses path compression technique) int find(subset subsets[], int i) { // find root and make root as parent of i // (path compression) if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; } // A function that does union of two sets // of x and y (uses union by rank) void Union(subset subsets[], int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root // of high rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as // root and increment its rank by one else { subsets[yroot].parent = xroot; subsets[xroot].rank++; } } // The main function to construct MST using Kruskal's // algorithm void KruskalMST() { // Tnis will store the resultant MST Edge result[] = new Edge[V]; // An index variable, used for result[] int e = 0; // An index variable, used for sorted edges int i = 0; for (i = 0; i < V; ++i) result[i] = new Edge(); // Step 1: Sort all the edges in non-decreasing // order of their weight. If we are not allowed to // change the given graph, we can create a copy of // array of edges Arrays.sort(edge); // Allocate memory for creating V subsets subset subsets[] = new subset[V]; for (i = 0; i < V; ++i) subsets[i] = new subset(); // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; // Index used to pick next edge // Number of edges to be taken is equal to V-1 while (e < V - 1) { // Step 2: Pick the smallest edge. And increment // the index for next iteration Edge next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); // If including this edge does't cause cycle, // include it in result and increment the index // of result for next edge if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } // Else discard the next_edge } // print the contents of result[] to display // the built MST System.out.println("Following are the edges in " + "the constructed MST"); int minimumCost = 0; for (i = 0; i < e; ++i) { System.out.println(result[i].src + " -- " + result[i].dest + " == " + result[i].weight); minimumCost += result[i].weight; } System.out.println("Minimum Cost Spanning Tree " + minimumCost); } // Driver Code public static void main(String[] args) { /* Let us create following weighted graph 10 0--------1 | \ | 6| 5\ |15 | \ | 2--------3 4 */ int V = 4; // Number of vertices in graph int E = 5; // Number of edges in graph Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = 10; // add edge 0-2 graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 6; // add edge 0-3 graph.edge[2].src = 0; graph.edge[2].dest = 3; graph.edge[2].weight = 5; // add edge 1-3 graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 15; // add edge 2-3 graph.edge[4].src = 2; graph.edge[4].dest = 3; graph.edge[4].weight = 4; // Function call graph.KruskalMST(); }}// This code is contributed by Aakash Hasija # Python program for Kruskal's algorithm to find# Minimum Spanning Tree of a given connected,# undirected and weighted graph from collections import defaultdict # Class to represent a graph class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = [] # default dictionary # to store graph # function to add an edge to graph def addEdge(self, u, v, w): self.graph.append([u, v, w]) # A utility function to find set of an element i # (uses path compression technique) def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) # A function that does union of two sets of x and y # (uses union by rank) def union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) # Attach smaller rank tree under root of # high rank tree (Union by Rank) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot # If ranks are same, then make one as root # and increment its rank by one else: parent[yroot] = xroot rank[xroot] += 1 # The main function to construct MST using Kruskal's # algorithm def KruskalMST(self): result = [] # This will store the resultant MST # An index variable, used for sorted edges i = 0 # An index variable, used for result[] e = 0 # Step 1: Sort all the edges in # non-decreasing order of their # weight. If we are not allowed to change the # given graph, we can create a copy of graph self.graph = sorted(self.graph, key=lambda item: item[2]) parent = [] rank = [] # Create V subsets with single elements for node in range(self.V): parent.append(node) rank.append(0) # Number of edges to be taken is equal to V-1 while e < self.V - 1: # Step 2: Pick the smallest edge and increment # the index for next iteration u, v, w = self.graph[i] i = i + 1 x = self.find(parent, u) y = self.find(parent, v) # If including this edge does't # cause cycle, include it in result # and increment the indexof result # for next edge if x != y: e = e + 1 result.append([u, v, w]) self.union(parent, rank, x, y) # Else discard the edge minimumCost = 0 print ("Edges in the constructed MST") for u, v, weight in result: minimumCost += weight print("%d -- %d == %d" % (u, v, weight)) print("Minimum Spanning Tree" , minimumCost) # Driver codeg = Graph(4)g.addEdge(0, 1, 10)g.addEdge(0, 2, 6)g.addEdge(0, 3, 5)g.addEdge(1, 3, 15)g.addEdge(2, 3, 4) # Function callg.KruskalMST() # This code is contributed by Neelam Yadav // C# Code for above approachusing System; class Graph { // A class to represent a graph edge class Edge : IComparable<Edge> { public int src, dest, weight; // Comparator function used for sorting edges // based on their weight public int CompareTo(Edge compareEdge) { return this.weight - compareEdge.weight; } } // A class to represent // a subset for union-find public class subset { public int parent, rank; }; int V, E; // V-> no. of vertices & E->no.of edges Edge[] edge; // collection of all edges // Creates a graph with V vertices and E edges Graph(int v, int e) { V = v; E = e; edge = new Edge[E]; for (int i = 0; i < e; ++i) edge[i] = new Edge(); } // A utility function to find set of an element i // (uses path compression technique) int find(subset[] subsets, int i) { // find root and make root as // parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; } // A function that does union of // two sets of x and y (uses union by rank) void Union(subset[] subsets, int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root of // high rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root // and increment its rank by one else { subsets[yroot].parent = xroot; subsets[xroot].rank++; } } // The main function to construct MST // using Kruskal's algorithm void KruskalMST() { // This will store the // resultant MST Edge[] result = new Edge[V]; int e = 0; // An index variable, used for result[] int i = 0; // An index variable, used for sorted edges for (i = 0; i < V; ++i) result[i] = new Edge(); // Step 1: Sort all the edges in non-decreasing // order of their weight. If we are not allowed // to change the given graph, we can create // a copy of array of edges Array.Sort(edge); // Allocate memory for creating V subsets subset[] subsets = new subset[V]; for (i = 0; i < V; ++i) subsets[i] = new subset(); // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; // Index used to pick next edge // Number of edges to be taken is equal to V-1 while (e < V - 1) { // Step 2: Pick the smallest edge. And increment // the index for next iteration Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); // If including this edge does't cause cycle, // include it in result and increment the index // of result for next edge if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } // Else discard the next_edge } // print the contents of result[] to display // the built MST Console.WriteLine("Following are the edges in " + "the constructed MST"); int minimumCost = 0 for (i = 0; i < e; ++i) { Console.WriteLine(result[i].src + " -- " + result[i].dest + " == " + result[i].weight); minimumCost += result[i].weight; } Console.WriteLine("Minimum Cost Spanning Tree" + minimumCost); Console.ReadLine(); } // Driver Code public static void Main(String[] args) { /* Let us create following weighted graph 10 0--------1 | \ | 6| 5\ |15 | \ | 2--------3 4 */ int V = 4; // Number of vertices in graph int E = 5; // Number of edges in graph Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = 10; // add edge 0-2 graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 6; // add edge 0-3 graph.edge[2].src = 0; graph.edge[2].dest = 3; graph.edge[2].weight = 5; // add edge 1-3 graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 15; // add edge 2-3 graph.edge[4].src = 2; graph.edge[4].dest = 3; graph.edge[4].weight = 4; // Function call graph.KruskalMST(); }} // This code is contributed by Aakash Hasija #include <bits/stdc++.h>using namespace std;// DSU data structure// path compression + rank by union class DSU{ int *parent; int *rank; public: DSU(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = -1; rank[i] = 1; } } // Find function int find(int i) { if (parent[i] == -1) return i; return parent[i] = find(parent[i]); } // union function void unite(int x, int y) { int s1 = find(x); int s2 = find(y); if (s1 != s2) { if (rank[s1] < rank[s2]) { parent[s1] = s2; rank[s2] += rank[s1]; } else { parent[s2] = s1; rank[s1] += rank[s2]; } } }}; class Graph{ vector<vector<int>> edgelist; int V; public: Graph(int V) { this->V = V; } void addEdge(int x, int y, int w) { edgelist.push_back({w, x, y}); } int kruskals_mst() { // 1. Sort all edges sort(edgelist.begin(), edgelist.end()); // Initialize the DSU DSU s(V); int ans = 0; for (auto edge : edgelist) { int w = edge[0]; int x = edge[1]; int y = edge[2]; // take that edge in MST if it does form a cycle if (s.find(x) != s.find(y)) { s.unite(x, y); ans += w; } } return ans; }};int main(){ Graph g(4); g.addEdge(0, 1, 1); g.addEdge(1, 3, 3); g.addEdge(3, 2, 4); g.addEdge(2, 0, 2); g.addEdge(0, 3, 2); g.addEdge(1, 2, 2); // int n, m; // cin >> n >> m; // Graph g(n); // for (int i = 0; i < m; i++) // { // int x, y, w; // cin >> x >> y >> w; // g.addEdge(x, y, w); // } cout << g.kruskals_mst(); return 0;} Following are the edges in the constructed MST 2 -- 3 == 4 0 -- 3 == 5 0 -- 1 == 10 Minimum Cost Spanning Tree: 19 Time Complexity: O(ElogE) or O(ElogV). Sorting of edges takes O(ELogE) time. After sorting, we iterate through all edges and apply the find-union algorithm. The find and union operations can take at most O(LogV) time. So overall complexity is O(ELogE + ELogV) time. The value of E can be at most O(V2), so O(LogV) is O(LogE) the same. Therefore, the overall time complexity is O(ElogE) or O(ElogV) YouTubeGeeksforGeeks500K subscribersKruskal’s Algorithm for Minimum Spanning Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3rrNH_AizMA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: http://www.ics.uci.edu/~eppstein/161/960206.html http://en.wikipedia.org/wiki/Minimum_spanning_treeThis article is compiled by Aashish Barnwal and reviewed by the GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. MoustafaElsayed rathbhupendra reddybharathab426 mkshah141 dhyeydhyey7654 hitesh_tripathi neerajx86 siddhantgore rahulv91199 om_mishra mittalshubham05 ankushpachpor sumitgumber28 amartyaghoshgfg Kruskal Kruskal'sAlgorithm MST Graph Greedy Greedy Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Floyd Warshall Algorithm | DP-16 Traveling Salesman Problem (TSP) Implementation Minimum number of swaps required to sort an array Program for array rotation Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Fractional Knapsack Problem Minimum Number of Platforms Required for a Railway/Bus Station Delete an element from array (Using two traversals and one traversal)
[ { "code": null, "e": 30545, "s": 30517, "text": "\n18 Jan, 2022" }, { "code": null, "e": 31299, "s": 30545, "text": "What is Minimum Spanning Tree? Given a connected and undirected graph, a spanning tree of that graph is a subgraph that is a tree and connects all the vertices together. A single graph can have many different spanning trees. A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected, undirected graph is a spanning tree with a weight less than or equal to the weight of every other spanning tree. The weight of a spanning tree is the sum of weights given to each edge of the spanning tree.How many edges does a minimum spanning tree has? A minimum spanning tree has (V – 1) edges where V is the number of vertices in the given graph. What are the applications of the Minimum Spanning Tree? See this for applications of MST." }, { "code": null, "e": 31361, "s": 31299, "text": "Below are the steps for finding MST using Kruskal’s algorithm" }, { "code": null, "e": 31643, "s": 31361, "text": "1. Sort all the edges in non-decreasing order of their weight. 2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. 3. Repeat step#2 until there are (V-1) edges in the spanning tree." }, { "code": null, "e": 32103, "s": 31643, "text": "Step #2 uses the Union-Find algorithm to detect cycles. So we recommend reading the following post as a prerequisite. Union-Find Algorithm | Set 1 (Detect Cycle in a Graph) Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)The algorithm is a Greedy Algorithm. The Greedy Choice is to pick the smallest weight edge that does not cause a cycle in the MST constructed so far. Let us understand it with an example: Consider the below input graph. " }, { "code": null, "e": 32219, "s": 32103, "text": "The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will be having (9 – 1) = 8 edges. " }, { "code": null, "e": 32522, "s": 32219, "text": "After sorting:\n\nWeight Src Dest\n1 7 6\n2 8 2\n2 6 5\n4 0 1\n4 2 5\n6 8 6\n7 2 3\n7 7 8\n8 0 7\n8 1 2\n9 3 4\n10 5 4\n11 1 7\n14 3 5" }, { "code": null, "e": 32634, "s": 32522, "text": "Now pick all edges one by one from the sorted list of edges 1. Pick edge 7-6: No cycle is formed, include it. " }, { "code": null, "e": 32686, "s": 32634, "text": "2. Pick edge 8-2: No cycle is formed, include it. " }, { "code": null, "e": 32738, "s": 32686, "text": "3. Pick edge 6-5: No cycle is formed, include it. " }, { "code": null, "e": 32790, "s": 32738, "text": "4. Pick edge 0-1: No cycle is formed, include it. " }, { "code": null, "e": 32842, "s": 32790, "text": "5. Pick edge 2-5: No cycle is formed, include it. " }, { "code": null, "e": 32971, "s": 32842, "text": "6. Pick edge 8-6: Since including this edge results in the cycle, discard it.7. Pick edge 2-3: No cycle is formed, include it. " }, { "code": null, "e": 33100, "s": 32971, "text": "8. Pick edge 7-8: Since including this edge results in the cycle, discard it.9. Pick edge 0-7: No cycle is formed, include it. " }, { "code": null, "e": 33231, "s": 33100, "text": "10. Pick edge 1-2: Since including this edge results in the cycle, discard it.11. Pick edge 3-4: No cycle is formed, include it. " }, { "code": null, "e": 33309, "s": 33231, "text": "Since the number of edges included equals (V – 1), the algorithm stops here. " }, { "code": null, "e": 33356, "s": 33309, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 33361, "s": 33356, "text": "Java" }, { "code": null, "e": 33369, "s": 33361, "text": "Python3" }, { "code": null, "e": 33372, "s": 33369, "text": "C#" }, { "code": null, "e": 33376, "s": 33372, "text": "C++" }, { "code": "// Java program for Kruskal's algorithm to// find Minimum Spanning Tree of a given//connected, undirected and weighted graphimport java.util.*;import java.lang.*;import java.io.*; class Graph { // A class to represent a graph edge class Edge implements Comparable<Edge> { int src, dest, weight; // Comparator function used for // sorting edgesbased on their weight public int compareTo(Edge compareEdge) { return this.weight - compareEdge.weight; } }; // A class to represent a subset for // union-find class subset { int parent, rank; }; int V, E; // V-> no. of vertices & E->no.of edges Edge edge[]; // collection of all edges // Creates a graph with V vertices and E edges Graph(int v, int e) { V = v; E = e; edge = new Edge[E]; for (int i = 0; i < e; ++i) edge[i] = new Edge(); } // A utility function to find set of an // element i (uses path compression technique) int find(subset subsets[], int i) { // find root and make root as parent of i // (path compression) if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; } // A function that does union of two sets // of x and y (uses union by rank) void Union(subset subsets[], int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root // of high rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as // root and increment its rank by one else { subsets[yroot].parent = xroot; subsets[xroot].rank++; } } // The main function to construct MST using Kruskal's // algorithm void KruskalMST() { // Tnis will store the resultant MST Edge result[] = new Edge[V]; // An index variable, used for result[] int e = 0; // An index variable, used for sorted edges int i = 0; for (i = 0; i < V; ++i) result[i] = new Edge(); // Step 1: Sort all the edges in non-decreasing // order of their weight. If we are not allowed to // change the given graph, we can create a copy of // array of edges Arrays.sort(edge); // Allocate memory for creating V subsets subset subsets[] = new subset[V]; for (i = 0; i < V; ++i) subsets[i] = new subset(); // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; // Index used to pick next edge // Number of edges to be taken is equal to V-1 while (e < V - 1) { // Step 2: Pick the smallest edge. And increment // the index for next iteration Edge next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); // If including this edge does't cause cycle, // include it in result and increment the index // of result for next edge if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } // Else discard the next_edge } // print the contents of result[] to display // the built MST System.out.println(\"Following are the edges in \" + \"the constructed MST\"); int minimumCost = 0; for (i = 0; i < e; ++i) { System.out.println(result[i].src + \" -- \" + result[i].dest + \" == \" + result[i].weight); minimumCost += result[i].weight; } System.out.println(\"Minimum Cost Spanning Tree \" + minimumCost); } // Driver Code public static void main(String[] args) { /* Let us create following weighted graph 10 0--------1 | \\ | 6| 5\\ |15 | \\ | 2--------3 4 */ int V = 4; // Number of vertices in graph int E = 5; // Number of edges in graph Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = 10; // add edge 0-2 graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 6; // add edge 0-3 graph.edge[2].src = 0; graph.edge[2].dest = 3; graph.edge[2].weight = 5; // add edge 1-3 graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 15; // add edge 2-3 graph.edge[4].src = 2; graph.edge[4].dest = 3; graph.edge[4].weight = 4; // Function call graph.KruskalMST(); }}// This code is contributed by Aakash Hasija", "e": 38711, "s": 33376, "text": null }, { "code": "# Python program for Kruskal's algorithm to find# Minimum Spanning Tree of a given connected,# undirected and weighted graph from collections import defaultdict # Class to represent a graph class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = [] # default dictionary # to store graph # function to add an edge to graph def addEdge(self, u, v, w): self.graph.append([u, v, w]) # A utility function to find set of an element i # (uses path compression technique) def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) # A function that does union of two sets of x and y # (uses union by rank) def union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) # Attach smaller rank tree under root of # high rank tree (Union by Rank) if rank[xroot] < rank[yroot]: parent[xroot] = yroot elif rank[xroot] > rank[yroot]: parent[yroot] = xroot # If ranks are same, then make one as root # and increment its rank by one else: parent[yroot] = xroot rank[xroot] += 1 # The main function to construct MST using Kruskal's # algorithm def KruskalMST(self): result = [] # This will store the resultant MST # An index variable, used for sorted edges i = 0 # An index variable, used for result[] e = 0 # Step 1: Sort all the edges in # non-decreasing order of their # weight. If we are not allowed to change the # given graph, we can create a copy of graph self.graph = sorted(self.graph, key=lambda item: item[2]) parent = [] rank = [] # Create V subsets with single elements for node in range(self.V): parent.append(node) rank.append(0) # Number of edges to be taken is equal to V-1 while e < self.V - 1: # Step 2: Pick the smallest edge and increment # the index for next iteration u, v, w = self.graph[i] i = i + 1 x = self.find(parent, u) y = self.find(parent, v) # If including this edge does't # cause cycle, include it in result # and increment the indexof result # for next edge if x != y: e = e + 1 result.append([u, v, w]) self.union(parent, rank, x, y) # Else discard the edge minimumCost = 0 print (\"Edges in the constructed MST\") for u, v, weight in result: minimumCost += weight print(\"%d -- %d == %d\" % (u, v, weight)) print(\"Minimum Spanning Tree\" , minimumCost) # Driver codeg = Graph(4)g.addEdge(0, 1, 10)g.addEdge(0, 2, 6)g.addEdge(0, 3, 5)g.addEdge(1, 3, 15)g.addEdge(2, 3, 4) # Function callg.KruskalMST() # This code is contributed by Neelam Yadav", "e": 41799, "s": 38711, "text": null }, { "code": "// C# Code for above approachusing System; class Graph { // A class to represent a graph edge class Edge : IComparable<Edge> { public int src, dest, weight; // Comparator function used for sorting edges // based on their weight public int CompareTo(Edge compareEdge) { return this.weight - compareEdge.weight; } } // A class to represent // a subset for union-find public class subset { public int parent, rank; }; int V, E; // V-> no. of vertices & E->no.of edges Edge[] edge; // collection of all edges // Creates a graph with V vertices and E edges Graph(int v, int e) { V = v; E = e; edge = new Edge[E]; for (int i = 0; i < e; ++i) edge[i] = new Edge(); } // A utility function to find set of an element i // (uses path compression technique) int find(subset[] subsets, int i) { // find root and make root as // parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; } // A function that does union of // two sets of x and y (uses union by rank) void Union(subset[] subsets, int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root of // high rank tree (Union by Rank) if (subsets[xroot].rank < subsets[yroot].rank) subsets[xroot].parent = yroot; else if (subsets[xroot].rank > subsets[yroot].rank) subsets[yroot].parent = xroot; // If ranks are same, then make one as root // and increment its rank by one else { subsets[yroot].parent = xroot; subsets[xroot].rank++; } } // The main function to construct MST // using Kruskal's algorithm void KruskalMST() { // This will store the // resultant MST Edge[] result = new Edge[V]; int e = 0; // An index variable, used for result[] int i = 0; // An index variable, used for sorted edges for (i = 0; i < V; ++i) result[i] = new Edge(); // Step 1: Sort all the edges in non-decreasing // order of their weight. If we are not allowed // to change the given graph, we can create // a copy of array of edges Array.Sort(edge); // Allocate memory for creating V subsets subset[] subsets = new subset[V]; for (i = 0; i < V; ++i) subsets[i] = new subset(); // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; // Index used to pick next edge // Number of edges to be taken is equal to V-1 while (e < V - 1) { // Step 2: Pick the smallest edge. And increment // the index for next iteration Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); // If including this edge does't cause cycle, // include it in result and increment the index // of result for next edge if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } // Else discard the next_edge } // print the contents of result[] to display // the built MST Console.WriteLine(\"Following are the edges in \" + \"the constructed MST\"); int minimumCost = 0 for (i = 0; i < e; ++i) { Console.WriteLine(result[i].src + \" -- \" + result[i].dest + \" == \" + result[i].weight); minimumCost += result[i].weight; } Console.WriteLine(\"Minimum Cost Spanning Tree\" + minimumCost); Console.ReadLine(); } // Driver Code public static void Main(String[] args) { /* Let us create following weighted graph 10 0--------1 | \\ | 6| 5\\ |15 | \\ | 2--------3 4 */ int V = 4; // Number of vertices in graph int E = 5; // Number of edges in graph Graph graph = new Graph(V, E); // add edge 0-1 graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = 10; // add edge 0-2 graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 6; // add edge 0-3 graph.edge[2].src = 0; graph.edge[2].dest = 3; graph.edge[2].weight = 5; // add edge 1-3 graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 15; // add edge 2-3 graph.edge[4].src = 2; graph.edge[4].dest = 3; graph.edge[4].weight = 4; // Function call graph.KruskalMST(); }} // This code is contributed by Aakash Hasija", "e": 47023, "s": 41799, "text": null }, { "code": "#include <bits/stdc++.h>using namespace std;// DSU data structure// path compression + rank by union class DSU{ int *parent; int *rank; public: DSU(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = -1; rank[i] = 1; } } // Find function int find(int i) { if (parent[i] == -1) return i; return parent[i] = find(parent[i]); } // union function void unite(int x, int y) { int s1 = find(x); int s2 = find(y); if (s1 != s2) { if (rank[s1] < rank[s2]) { parent[s1] = s2; rank[s2] += rank[s1]; } else { parent[s2] = s1; rank[s1] += rank[s2]; } } }}; class Graph{ vector<vector<int>> edgelist; int V; public: Graph(int V) { this->V = V; } void addEdge(int x, int y, int w) { edgelist.push_back({w, x, y}); } int kruskals_mst() { // 1. Sort all edges sort(edgelist.begin(), edgelist.end()); // Initialize the DSU DSU s(V); int ans = 0; for (auto edge : edgelist) { int w = edge[0]; int x = edge[1]; int y = edge[2]; // take that edge in MST if it does form a cycle if (s.find(x) != s.find(y)) { s.unite(x, y); ans += w; } } return ans; }};int main(){ Graph g(4); g.addEdge(0, 1, 1); g.addEdge(1, 3, 3); g.addEdge(3, 2, 4); g.addEdge(2, 0, 2); g.addEdge(0, 3, 2); g.addEdge(1, 2, 2); // int n, m; // cin >> n >> m; // Graph g(n); // for (int i = 0; i < m; i++) // { // int x, y, w; // cin >> x >> y >> w; // g.addEdge(x, y, w); // } cout << g.kruskals_mst(); return 0;}", "e": 49000, "s": 47023, "text": null }, { "code": null, "e": 49118, "s": 49003, "text": "Following are the edges in the constructed MST\n2 -- 3 == 4\n0 -- 3 == 5\n0 -- 1 == 10\nMinimum Cost Spanning Tree: 19" }, { "code": null, "e": 49518, "s": 49120, "text": "Time Complexity: O(ElogE) or O(ElogV). Sorting of edges takes O(ELogE) time. After sorting, we iterate through all edges and apply the find-union algorithm. The find and union operations can take at most O(LogV) time. So overall complexity is O(ELogE + ELogV) time. The value of E can be at most O(V2), so O(LogV) is O(LogE) the same. Therefore, the overall time complexity is O(ElogE) or O(ElogV)" }, { "code": null, "e": 50364, "s": 49520, "text": "YouTubeGeeksforGeeks500K subscribersKruskal’s Algorithm for Minimum Spanning Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:04•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=3rrNH_AizMA\" 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": 50686, "s": 50366, "text": "References: http://www.ics.uci.edu/~eppstein/161/960206.html http://en.wikipedia.org/wiki/Minimum_spanning_treeThis article is compiled by Aashish Barnwal and reviewed by the GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 50704, "s": 50688, "text": "MoustafaElsayed" }, { "code": null, "e": 50718, "s": 50704, "text": "rathbhupendra" }, { "code": null, "e": 50736, "s": 50718, "text": "reddybharathab426" }, { "code": null, "e": 50746, "s": 50736, "text": "mkshah141" }, { "code": null, "e": 50761, "s": 50746, "text": "dhyeydhyey7654" }, { "code": null, "e": 50777, "s": 50761, "text": "hitesh_tripathi" }, { "code": null, "e": 50787, "s": 50777, "text": "neerajx86" }, { "code": null, "e": 50800, "s": 50787, "text": "siddhantgore" }, { "code": null, "e": 50812, "s": 50800, "text": "rahulv91199" }, { "code": null, "e": 50822, "s": 50812, "text": "om_mishra" }, { "code": null, "e": 50838, "s": 50822, "text": "mittalshubham05" }, { "code": null, "e": 50852, "s": 50838, "text": "ankushpachpor" }, { "code": null, "e": 50866, "s": 50852, "text": "sumitgumber28" }, { "code": null, "e": 50882, "s": 50866, "text": "amartyaghoshgfg" }, { "code": null, "e": 50890, "s": 50882, "text": "Kruskal" }, { "code": null, "e": 50909, "s": 50890, "text": "Kruskal'sAlgorithm" }, { "code": null, "e": 50913, "s": 50909, "text": "MST" }, { "code": null, "e": 50919, "s": 50913, "text": "Graph" }, { "code": null, "e": 50926, "s": 50919, "text": "Greedy" }, { "code": null, "e": 50933, "s": 50926, "text": "Greedy" }, { "code": null, "e": 50939, "s": 50933, "text": "Graph" }, { "code": null, "e": 51037, "s": 50939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51068, "s": 51037, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 51136, "s": 51068, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 51169, "s": 51136, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 51217, "s": 51169, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 51267, "s": 51217, "text": "Minimum number of swaps required to sort an array" }, { "code": null, "e": 51294, "s": 51267, "text": "Program for array rotation" }, { "code": null, "e": 51375, "s": 51294, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 51403, "s": 51375, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 51466, "s": 51403, "text": "Minimum Number of Platforms Required for a Railway/Bus Station" } ]
col-lg-* Bootstrap class
The input-lg is used to set the width of forms in Bootstrap. You can try to run the following code to implement col-lg Bootstrap class − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <form role = "form"> <div class = "row"> <div class = "col-lg-2"> <input type = "text" class = "form-control" placeholder = ".col-lg-2"> </div> <div class = "col-lg-3"> <input type = "text" class = "form-control" placeholder = ".col-lg-3"> </div> <div class = "col-lg-4"> <input type = "text" class = "form-control" placeholder = ".col-lg-4"> </div> </div> </form> </body> </html>
[ { "code": null, "e": 1123, "s": 1062, "text": "The input-lg is used to set the width of forms in Bootstrap." }, { "code": null, "e": 1199, "s": 1123, "text": "You can try to run the following code to implement col-lg Bootstrap class −" }, { "code": null, "e": 1209, "s": 1199, "text": "Live Demo" }, { "code": null, "e": 2025, "s": 1209, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <form role = \"form\">\n <div class = \"row\">\n <div class = \"col-lg-2\">\n <input type = \"text\" class = \"form-control\" placeholder = \".col-lg-2\">\n </div>\n <div class = \"col-lg-3\">\n <input type = \"text\" class = \"form-control\" placeholder = \".col-lg-3\">\n </div>\n <div class = \"col-lg-4\">\n <input type = \"text\" class = \"form-control\" placeholder = \".col-lg-4\">\n </div>\n </div>\n </form>\n </body>\n</html>" } ]
Retrieving Elements from Collection in C#
Let us see an example of a list collection. We have set the elements − List<int> list = new List<int>(); list.Add(20); list.Add(40); list.Add(60); list.Add(80); Now let’s say we need to retrieve the first element from the list. For that, set the index like this − int a = list[0]; The following is an example showing how to retrieve elements from a list collection − using System; using System.Collections.Generic; class Demo { static void Main(String[] args) { List<int> list = new List<int>(); list.Add(20); list.Add(40); list.Add(60); list.Add(80); foreach (int val in list) { Console.WriteLine(val); } int a = list[0]; Console.WriteLine("First element: "+a); } }
[ { "code": null, "e": 1106, "s": 1062, "text": "Let us see an example of a list collection." }, { "code": null, "e": 1133, "s": 1106, "text": "We have set the elements −" }, { "code": null, "e": 1223, "s": 1133, "text": "List<int> list = new List<int>();\nlist.Add(20);\nlist.Add(40);\nlist.Add(60);\nlist.Add(80);" }, { "code": null, "e": 1326, "s": 1223, "text": "Now let’s say we need to retrieve the first element from the list. For that, set the index like this −" }, { "code": null, "e": 1343, "s": 1326, "text": "int a = list[0];" }, { "code": null, "e": 1429, "s": 1343, "text": "The following is an example showing how to retrieve elements from a list collection −" }, { "code": null, "e": 1802, "s": 1429, "text": "using System;\nusing System.Collections.Generic;\n\nclass Demo {\n\n static void Main(String[] args) {\n List<int> list = new List<int>();\n list.Add(20);\n list.Add(40);\n list.Add(60);\n list.Add(80);\n\n foreach (int val in list) {\n Console.WriteLine(val);\n }\n\n int a = list[0];\n Console.WriteLine(\"First element: \"+a);\n }\n}" } ]
Adding unique constraint to ALTER TABLE in MySQL
Let us first create a table − mysql> create table DemoTable1811 ( FirstName varchar(20), LastName varchar(20) ); Query OK, 0 rows affected (0.00 sec) Here is the query to add index mysql> alter table DemoTable1811 ADD UNIQUE unique_index_first_last_name(FirstName, LastName); Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0 Insert some records in the table using insert command − mysql> insert into DemoTable1811 values('John','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1811 values('John','Doe'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1811 values('Adam','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1811 values('John','Doe'); ERROR 1062 (23000): Duplicate entry 'John-Doe' for key 'unique_index_first_last_name' Display all records from the table using select statement − mysql> select * from DemoTable1811; This will produce the following output − +-----------+----------+ | FirstName | LastName | +-----------+----------+ | Adam | Smith | | John | Doe | | John | Smith | +-----------+----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1232, "s": 1092, "text": "mysql> create table DemoTable1811\n (\n FirstName varchar(20),\n LastName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1263, "s": 1232, "text": "Here is the query to add index" }, { "code": null, "e": 1434, "s": 1263, "text": "mysql> alter table DemoTable1811 ADD UNIQUE unique_index_first_last_name(FirstName, LastName);\nQuery OK, 0 rows affected (0.00 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1490, "s": 1434, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1908, "s": 1490, "text": "mysql> insert into DemoTable1811 values('John','Smith');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1811 values('John','Doe');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1811 values('Adam','Smith');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1811 values('John','Doe');\nERROR 1062 (23000): Duplicate entry 'John-Doe' for key 'unique_index_first_last_name'" }, { "code": null, "e": 1968, "s": 1908, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2004, "s": 1968, "text": "mysql> select * from DemoTable1811;" }, { "code": null, "e": 2045, "s": 2004, "text": "This will produce the following output −" }, { "code": null, "e": 2245, "s": 2045, "text": "+-----------+----------+\n| FirstName | LastName |\n+-----------+----------+\n| Adam | Smith |\n| John | Doe |\n| John | Smith |\n+-----------+----------+\n3 rows in set (0.00 sec)" } ]
How I taught my computer to play Spot it! using OpenCV and Deep Learning | by Hennie de Harder | Towards Data Science
A hobby of mine is playing board games and because I have some knowledge about CNNs, I decided to build an application that can beat humans in a card game. I wanted to build the model from scratch with my own dataset, to see how well a model from scratch with a small dataset would perform. I chose to start with a not-too-hard game, Spot it! (a.k.a. Dobble). In the case you don’t know Spot it! yet, here follows a short game explanation: Spot it! is a simple pattern recognition game in which players try to find an image shown on two cards. Each card in original Spot it! features eight different symbols, with the symbols varying in size from one card to the next. Any two cards have exactly one symbol in common. If you’re the first one who finds that symbol, you win the card. Whoever has collected the most cards when the 55-card deck runs out wins. The first step of any data science problem is gathering data. I took some pictures with my phone, six of each card. That makes a total of 330 pictures. Four of them are shown below. You might think: is this enough to build a perfect Convolutional Neural Network? I will get back to that! Okay, we have the data, what’s next? This is probably the most important part in order to succeed: processing the images. We need to extract the symbols shown on each card. There are some difficulties here. You can see in the pictures above that some symbols might be harder to extract: the snowman and ghost (third picture) and igloo (fourth picture) have a light color, and the stains (second picture) and exclamation mark (fourth picture) exist of multiple parts. To handle the light color symbols we add contrast to the images. After that we resize and save the image. We use the Lab color space for adding contrast. L stands for lightness, a is the color component ranging from green to magenta and b is the color component ranging from blue to yellow. We can extract these components easily with OpenCV: import cv2import imutilsimgname = 'picture1'image = cv2.imread(f’{imgname}.jpg’)lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)l, a, b = cv2.split(lab) Now we add contrast to the Light component, merge the components back together and convert the image back to normal: clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))cl = clahe.apply(l)limg = cv2.merge((cl,a,b))final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR) Then we resize and save the image: resized = cv2.resize(final, (800, 800))# save the imagecv2.imwrite(f'{imgname}processed.jpg', blurred) Done! Now the image is processed we can start with detecting the card on the image. It's possible to find the outer contours with OpenCV. Then we need to convert the image to gray scale, choose a threshold (190 in this case) to create a black and white image, and find the contours. In code: image = cv2.imread(f’{imgname}processed.jpg’)gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)thresh = cv2.threshold(gray, 190, 255, cv2.THRESH_BINARY)[1]# find contourscnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cnts = imutils.grab_contours(cnts)output = image.copy()# draw contours on imagefor c in cnts: cv2.drawContours(output, [c], -1, (255, 0, 0), 3) If we sort the outer contours by area, we can find the contour with the biggest area: this is the card. We can create a white background to extract the symbols. # sort by area, grab the biggest onecnts = sorted(cnts, key=cv2.contourArea, reverse=True)[0]# create mask with the biggest contourmask = np.zeros(gray.shape,np.uint8)mask = cv2.drawContours(mask, [cnts], -1, 255, cv2.FILLED)# card in foregroundfg_masked = cv2.bitwise_and(image, image, mask=mask)# white background (use inverted mask)mask = cv2.bitwise_not(mask)bk = np.full(image.shape, 255, dtype=np.uint8)bk_masked = cv2.bitwise_and(bk, bk, mask=mask)# combine back- and foregroundfinal = cv2.bitwise_or(fg_masked, bk_masked) Now it's symbol detection time! We can use the last image to detect outer contours again, these contours are the symbols. If we create a square around each symbol we can extract this region. The code is a bit longer: # just like before (with detecting the card)gray = cv2.cvtColor(final, cv2.COLOR_RGB2GRAY)thresh = cv2.threshold(gray, 195, 255, cv2.THRESH_BINARY)[1]thresh = cv2.bitwise_not(thresh)cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cnts = imutils.grab_contours(cnts)cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:10]# handle each contouri = 0for c in cnts: if cv2.contourArea(c) > 1000: # draw mask, keep contour mask = np.zeros(gray.shape, np.uint8) mask = cv2.drawContours(mask, [c], -1, 255, cv2.FILLED) # white background fg_masked = cv2.bitwise_and(image, image, mask=mask) mask = cv2.bitwise_not(mask) bk = np.full(image.shape, 255, dtype=np.uint8) bk_masked = cv2.bitwise_and(bk, bk, mask=mask) finalcont = cv2.bitwise_or(fg_masked, bk_masked) # bounding rectangle around contour output = finalcont.copy() x,y,w,h = cv2.boundingRect(c) # squares io rectangles if w < h: x += int((w-h)/2) w = h else: y += int((h-w)/2) h = w # take out the square with the symbol roi = finalcont[y:y+h, x:x+w] roi = cv2.resize(roi, (400,400)) # save the symbol cv2.imwrite(f"{imgname}_icon{i}.jpg", roi) i += 1 Now comes the boring part! It's time to sort the symbols. We need a train, test and validation directory, containing 57 directories each (we have 57 different symbols). The folder structure looks like this: symbols ├── test │ ├── anchor │ ├── apple │ │ ... │ └── zebra ├── train │ ├── anchor │ ├── apple │ │ ... │ └── zebra └── validation ├── anchor ├── apple │ ... └── zebra It takes some time to put the extracted symbols (over 2500) in the right directories! I have code for creating the subfolders, the test and validation set on GitHub. Maybe it's better to do the sorting with a clustering algorithm next time... Afther the boring part comes the cool part. Let’s build and train a CNN. You can find information about CNNs in this post. This is a multiclass, single-label classification problem. We want one label for every symbol. That’s why it's necessary to choose a last-layer activation softmax with 57 nodes and a categorical crossentropy loss function. The architecture of the final model looks like this: # importsfrom keras import layersfrom keras import modelsfrom keras import optimizersfrom keras.preprocessing.image import ImageDataGeneratorimport matplotlib.pyplot as plt# layers, activation layer with 57 nodes (one for every symbol)model = models.Sequential()model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(400, 400, 3)))model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(128, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(256, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(256, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(128, (3, 3), activation='relu'))model.add(layers.Flatten())model.add(layers.Dropout(0.5)) model.add(layers.Dense(512, activation='relu'))model.add(layers.Dense(57, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc']) For better performance I used data augmentation. Data augmentation is the process of increasing the amount and diversity of input data. This is possible by rotating, shifting, zooming, cropping and flipping existing images. It’s easy to perform data augmentation with Keras: # specify the directoriestrain_dir = 'symbols/train'validation_dir = 'symbols/validation'test_dir = 'symbols/test'# data augmentation with ImageDataGenerator from Keras (only train)train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=40, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.1, zoom_range=0.1, horizontal_flip=True, vertical_flip=True)test_datagen = ImageDataGenerator(rescale=1./255)train_generator = train_datagen.flow_from_directory(train_dir, target_size=(400,400), batch_size=20, class_mode='categorical')validation_generator = test_datagen.flow_from_directory(validation_dir, target_size=(400,400), batch_size=20, class_mode='categorical') In case you wondered, an augmented ghost looks like this: Let’s fit the model, save it to use for predictions and check out the results. history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=100, validation_data=validation_generator, validation_steps=50)# don't forget to save your model!model.save('models/model.h5') The baseline model I trained was without data augmentation, dropout and had less layers. This model gave the following results: You can clearly see this model is overfitting. The results of the final model (from the code in earlier paragraphs) are a lot better. In the image below you can see the accuracy and loss of the train and validation set. With the test set this model made only one mistake: it predicted a bomb as a drop. I decided to stick with the model, the accuracy was 0.995 on the test set. Now it’s possible to predict the common symbol on two cards. We can use two images, make predictions for each image separately and use an intersection to see what symbol the cards both have. This gives three possibilities: Something went wrong during prediction time: there are no common symbols found. There’s exactly one symbol in the intersection (can be wrong or right). There’s more than one symbol in the intersection. In this case I selected the symbol with the highest probability (mean of both predictions). The code is on GitHub for predicting all combinations of two images in a directory, the main.py file. Some results: Is this a perfect performing model? Unfortunately, no! When I took new pictures of cards and let the model predict the common symbol, it had some issues with the snowman. Sometimes it predicted an eye or a zebra as a snowman! That gives some strange results: Is this model better than humans? It depends: humans can do it perfectly, but the model is faster! I timed the computer: I gave it the 55 card deck and asked the common symbol for every combination of two cards. That’s a total of 1485 combinations. This took the computer less than 140 seconds. The computer made some mistakes, but it will definitely beat any human when it comes to speed! I don’t think it’s really hard to build a 100% performing model. It can e.g. be done by using transfer learning. To understand what the model is doing we could visualize the layers for a test image. Things to try next time! I hope you enjoyed reading this post! ❤ Don’t forget to subscribe if you’d like to get an email whenever I publish a new article.
[ { "code": null, "e": 532, "s": 172, "text": "A hobby of mine is playing board games and because I have some knowledge about CNNs, I decided to build an application that can beat humans in a card game. I wanted to build the model from scratch with my own dataset, to see how well a model from scratch with a small dataset would perform. I chose to start with a not-too-hard game, Spot it! (a.k.a. Dobble)." }, { "code": null, "e": 1029, "s": 532, "text": "In the case you don’t know Spot it! yet, here follows a short game explanation: Spot it! is a simple pattern recognition game in which players try to find an image shown on two cards. Each card in original Spot it! features eight different symbols, with the symbols varying in size from one card to the next. Any two cards have exactly one symbol in common. If you’re the first one who finds that symbol, you win the card. Whoever has collected the most cards when the 55-card deck runs out wins." }, { "code": null, "e": 1317, "s": 1029, "text": "The first step of any data science problem is gathering data. I took some pictures with my phone, six of each card. That makes a total of 330 pictures. Four of them are shown below. You might think: is this enough to build a perfect Convolutional Neural Network? I will get back to that!" }, { "code": null, "e": 1890, "s": 1317, "text": "Okay, we have the data, what’s next? This is probably the most important part in order to succeed: processing the images. We need to extract the symbols shown on each card. There are some difficulties here. You can see in the pictures above that some symbols might be harder to extract: the snowman and ghost (third picture) and igloo (fourth picture) have a light color, and the stains (second picture) and exclamation mark (fourth picture) exist of multiple parts. To handle the light color symbols we add contrast to the images. After that we resize and save the image." }, { "code": null, "e": 2127, "s": 1890, "text": "We use the Lab color space for adding contrast. L stands for lightness, a is the color component ranging from green to magenta and b is the color component ranging from blue to yellow. We can extract these components easily with OpenCV:" }, { "code": null, "e": 2276, "s": 2127, "text": "import cv2import imutilsimgname = 'picture1'image = cv2.imread(f’{imgname}.jpg’)lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)l, a, b = cv2.split(lab)" }, { "code": null, "e": 2393, "s": 2276, "text": "Now we add contrast to the Light component, merge the components back together and convert the image back to normal:" }, { "code": null, "e": 2542, "s": 2393, "text": "clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))cl = clahe.apply(l)limg = cv2.merge((cl,a,b))final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)" }, { "code": null, "e": 2577, "s": 2542, "text": "Then we resize and save the image:" }, { "code": null, "e": 2680, "s": 2577, "text": "resized = cv2.resize(final, (800, 800))# save the imagecv2.imwrite(f'{imgname}processed.jpg', blurred)" }, { "code": null, "e": 2686, "s": 2680, "text": "Done!" }, { "code": null, "e": 2972, "s": 2686, "text": "Now the image is processed we can start with detecting the card on the image. It's possible to find the outer contours with OpenCV. Then we need to convert the image to gray scale, choose a threshold (190 in this case) to create a black and white image, and find the contours. In code:" }, { "code": null, "e": 3367, "s": 2972, "text": "image = cv2.imread(f’{imgname}processed.jpg’)gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)thresh = cv2.threshold(gray, 190, 255, cv2.THRESH_BINARY)[1]# find contourscnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cnts = imutils.grab_contours(cnts)output = image.copy()# draw contours on imagefor c in cnts: cv2.drawContours(output, [c], -1, (255, 0, 0), 3)" }, { "code": null, "e": 3528, "s": 3367, "text": "If we sort the outer contours by area, we can find the contour with the biggest area: this is the card. We can create a white background to extract the symbols." }, { "code": null, "e": 4058, "s": 3528, "text": "# sort by area, grab the biggest onecnts = sorted(cnts, key=cv2.contourArea, reverse=True)[0]# create mask with the biggest contourmask = np.zeros(gray.shape,np.uint8)mask = cv2.drawContours(mask, [cnts], -1, 255, cv2.FILLED)# card in foregroundfg_masked = cv2.bitwise_and(image, image, mask=mask)# white background (use inverted mask)mask = cv2.bitwise_not(mask)bk = np.full(image.shape, 255, dtype=np.uint8)bk_masked = cv2.bitwise_and(bk, bk, mask=mask)# combine back- and foregroundfinal = cv2.bitwise_or(fg_masked, bk_masked)" }, { "code": null, "e": 4275, "s": 4058, "text": "Now it's symbol detection time! We can use the last image to detect outer contours again, these contours are the symbols. If we create a square around each symbol we can extract this region. The code is a bit longer:" }, { "code": null, "e": 5610, "s": 4275, "text": "# just like before (with detecting the card)gray = cv2.cvtColor(final, cv2.COLOR_RGB2GRAY)thresh = cv2.threshold(gray, 195, 255, cv2.THRESH_BINARY)[1]thresh = cv2.bitwise_not(thresh)cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cnts = imutils.grab_contours(cnts)cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:10]# handle each contouri = 0for c in cnts: if cv2.contourArea(c) > 1000: # draw mask, keep contour mask = np.zeros(gray.shape, np.uint8) mask = cv2.drawContours(mask, [c], -1, 255, cv2.FILLED) # white background fg_masked = cv2.bitwise_and(image, image, mask=mask) mask = cv2.bitwise_not(mask) bk = np.full(image.shape, 255, dtype=np.uint8) bk_masked = cv2.bitwise_and(bk, bk, mask=mask) finalcont = cv2.bitwise_or(fg_masked, bk_masked) # bounding rectangle around contour output = finalcont.copy() x,y,w,h = cv2.boundingRect(c) # squares io rectangles if w < h: x += int((w-h)/2) w = h else: y += int((h-w)/2) h = w # take out the square with the symbol roi = finalcont[y:y+h, x:x+w] roi = cv2.resize(roi, (400,400)) # save the symbol cv2.imwrite(f\"{imgname}_icon{i}.jpg\", roi) i += 1" }, { "code": null, "e": 5817, "s": 5610, "text": "Now comes the boring part! It's time to sort the symbols. We need a train, test and validation directory, containing 57 directories each (we have 57 different symbols). The folder structure looks like this:" }, { "code": null, "e": 6024, "s": 5817, "text": "symbols ├── test │ ├── anchor │ ├── apple │ │ ... │ └── zebra ├── train │ ├── anchor │ ├── apple │ │ ... │ └── zebra └── validation ├── anchor ├── apple │ ... └── zebra" }, { "code": null, "e": 6267, "s": 6024, "text": "It takes some time to put the extracted symbols (over 2500) in the right directories! I have code for creating the subfolders, the test and validation set on GitHub. Maybe it's better to do the sorting with a clustering algorithm next time..." }, { "code": null, "e": 6390, "s": 6267, "text": "Afther the boring part comes the cool part. Let’s build and train a CNN. You can find information about CNNs in this post." }, { "code": null, "e": 6613, "s": 6390, "text": "This is a multiclass, single-label classification problem. We want one label for every symbol. That’s why it's necessary to choose a last-layer activation softmax with 57 nodes and a categorical crossentropy loss function." }, { "code": null, "e": 6666, "s": 6613, "text": "The architecture of the final model looks like this:" }, { "code": null, "e": 7744, "s": 6666, "text": "# importsfrom keras import layersfrom keras import modelsfrom keras import optimizersfrom keras.preprocessing.image import ImageDataGeneratorimport matplotlib.pyplot as plt# layers, activation layer with 57 nodes (one for every symbol)model = models.Sequential()model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(400, 400, 3)))model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(128, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(256, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(256, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(128, (3, 3), activation='relu'))model.add(layers.Flatten())model.add(layers.Dropout(0.5)) model.add(layers.Dense(512, activation='relu'))model.add(layers.Dense(57, activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc'])" }, { "code": null, "e": 8019, "s": 7744, "text": "For better performance I used data augmentation. Data augmentation is the process of increasing the amount and diversity of input data. This is possible by rotating, shifting, zooming, cropping and flipping existing images. It’s easy to perform data augmentation with Keras:" }, { "code": null, "e": 8702, "s": 8019, "text": "# specify the directoriestrain_dir = 'symbols/train'validation_dir = 'symbols/validation'test_dir = 'symbols/test'# data augmentation with ImageDataGenerator from Keras (only train)train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=40, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.1, zoom_range=0.1, horizontal_flip=True, vertical_flip=True)test_datagen = ImageDataGenerator(rescale=1./255)train_generator = train_datagen.flow_from_directory(train_dir, target_size=(400,400), batch_size=20, class_mode='categorical')validation_generator = test_datagen.flow_from_directory(validation_dir, target_size=(400,400), batch_size=20, class_mode='categorical')" }, { "code": null, "e": 8760, "s": 8702, "text": "In case you wondered, an augmented ghost looks like this:" }, { "code": null, "e": 8839, "s": 8760, "text": "Let’s fit the model, save it to use for predictions and check out the results." }, { "code": null, "e": 9041, "s": 8839, "text": "history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=100, validation_data=validation_generator, validation_steps=50)# don't forget to save your model!model.save('models/model.h5')" }, { "code": null, "e": 9169, "s": 9041, "text": "The baseline model I trained was without data augmentation, dropout and had less layers. This model gave the following results:" }, { "code": null, "e": 9389, "s": 9169, "text": "You can clearly see this model is overfitting. The results of the final model (from the code in earlier paragraphs) are a lot better. In the image below you can see the accuracy and loss of the train and validation set." }, { "code": null, "e": 9547, "s": 9389, "text": "With the test set this model made only one mistake: it predicted a bomb as a drop. I decided to stick with the model, the accuracy was 0.995 on the test set." }, { "code": null, "e": 9770, "s": 9547, "text": "Now it’s possible to predict the common symbol on two cards. We can use two images, make predictions for each image separately and use an intersection to see what symbol the cards both have. This gives three possibilities:" }, { "code": null, "e": 9850, "s": 9770, "text": "Something went wrong during prediction time: there are no common symbols found." }, { "code": null, "e": 9922, "s": 9850, "text": "There’s exactly one symbol in the intersection (can be wrong or right)." }, { "code": null, "e": 10064, "s": 9922, "text": "There’s more than one symbol in the intersection. In this case I selected the symbol with the highest probability (mean of both predictions)." }, { "code": null, "e": 10166, "s": 10064, "text": "The code is on GitHub for predicting all combinations of two images in a directory, the main.py file." }, { "code": null, "e": 10180, "s": 10166, "text": "Some results:" }, { "code": null, "e": 10439, "s": 10180, "text": "Is this a perfect performing model? Unfortunately, no! When I took new pictures of cards and let the model predict the common symbol, it had some issues with the snowman. Sometimes it predicted an eye or a zebra as a snowman! That gives some strange results:" }, { "code": null, "e": 10829, "s": 10439, "text": "Is this model better than humans? It depends: humans can do it perfectly, but the model is faster! I timed the computer: I gave it the 55 card deck and asked the common symbol for every combination of two cards. That’s a total of 1485 combinations. This took the computer less than 140 seconds. The computer made some mistakes, but it will definitely beat any human when it comes to speed!" }, { "code": null, "e": 11053, "s": 10829, "text": "I don’t think it’s really hard to build a 100% performing model. It can e.g. be done by using transfer learning. To understand what the model is doing we could visualize the layers for a test image. Things to try next time!" }, { "code": null, "e": 11093, "s": 11053, "text": "I hope you enjoyed reading this post! ❤" } ]
PL/SQL - CONTINUE Statement
The CONTINUE statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. In other words, it forces the next iteration of the loop to take place, skipping any code in between. The syntax for a CONTINUE statement is as follows − CONTINUE; DECLARE a number(2) := 10; BEGIN -- while loop execution WHILE a < 20 LOOP dbms_output.put_line ('value of a: ' || a); a := a + 1; IF a = 15 THEN -- skip the loop using the CONTINUE statement a := a + 1; CONTINUE; END IF; END LOOP; END; / When the above code is executed at the SQL prompt, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 PL/SQL procedure successfully completed.
[ { "code": null, "e": 2433, "s": 2199, "text": "The CONTINUE statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. In other words, it forces the next iteration of the loop to take place, skipping any code in between." }, { "code": null, "e": 2485, "s": 2433, "text": "The syntax for a CONTINUE statement is as follows −" }, { "code": null, "e": 2496, "s": 2485, "text": "CONTINUE;\n" }, { "code": null, "e": 2814, "s": 2496, "text": "DECLARE \n a number(2) := 10; \nBEGIN \n -- while loop execution \n WHILE a < 20 LOOP \n dbms_output.put_line ('value of a: ' || a); \n a := a + 1; \n IF a = 15 THEN \n -- skip the loop using the CONTINUE statement \n a := a + 1; \n CONTINUE; \n END IF; \n END LOOP; \nEND; \n/ " }, { "code": null, "e": 2900, "s": 2814, "text": "When the above code is executed at the SQL prompt, it produces the following result −" } ]
UUIDField – Django Models
12 Feb, 2020 UUIDField is a special field to store universally unique identifiers. It uses Python’s UUID class. UUID, Universal Unique Identifier, is a python library that helps in generating random objects of 128 bits as ids. It provides the uniqueness as it generates ids on the basis of time, Computer hardware (MAC etc.). Universally unique identifiers are a good alternative to AutoField for primary_key. The database will not generate the UUID for you, so it is recommended to use default. For example, import uuidfrom django.db import models class MyUUIDModel(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) # other fields Syntax field_name = models.UUIDField(**options) Illustration of UUIDField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into models.py file of geeks app. from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.UUIDField() Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now when we run makemigrations command from the terminal, Python manage.py makemigrations A new folder named migrations would be created in geeks directory with a file named 0001_initial.py # Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.UUIDField() )), ], ), ] Thus, an geeks_field UUIDField is created when you run makemigrations on the project.It is a field to store python’s UUID instance. UUID, Universal Unique Identifier, is a python library which helps in generating random objects of 128 bits as ids. To know more about UUID visit Generating Random id’s using UUID in Python. Let’s try to save a uuid object into the UUIDField. # importing the model# from geeks appfrom geeks.models import GeeksModel # importing uuidimport uuid # creating an instance of# uuid objecttest = uuid.uuid4() # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = test)geek_object.save() Now let’s check it in admin server. We have created an instance of GeeksModel Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to UUIDField will enable it to store empty values for that table in relational database.Here are the option and attributes that an UUIDField can use. NaveenArora Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Feb, 2020" }, { "code": null, "e": 536, "s": 53, "text": "UUIDField is a special field to store universally unique identifiers. It uses Python’s UUID class. UUID, Universal Unique Identifier, is a python library that helps in generating random objects of 128 bits as ids. It provides the uniqueness as it generates ids on the basis of time, Computer hardware (MAC etc.). Universally unique identifiers are a good alternative to AutoField for primary_key. The database will not generate the UUID for you, so it is recommended to use default." }, { "code": null, "e": 549, "s": 536, "text": "For example," }, { "code": "import uuidfrom django.db import models class MyUUIDModel(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) # other fields", "e": 751, "s": 549, "text": null }, { "code": null, "e": 758, "s": 751, "text": "Syntax" }, { "code": null, "e": 799, "s": 758, "text": "field_name = models.UUIDField(**options)" }, { "code": null, "e": 909, "s": 799, "text": "Illustration of UUIDField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 996, "s": 909, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 1047, "s": 996, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1080, "s": 1047, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1139, "s": 1080, "text": "Enter the following code into models.py file of geeks app." }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.UUIDField()", "e": 1290, "s": 1139, "text": null }, { "code": null, "e": 1326, "s": 1290, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 1564, "s": 1326, "text": null }, { "code": null, "e": 1622, "s": 1564, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 1654, "s": 1622, "text": "Python manage.py makemigrations" }, { "code": null, "e": 1754, "s": 1654, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py" }, { "code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.UUIDField() )), ], ), ]", "e": 2358, "s": 1754, "text": null }, { "code": null, "e": 2490, "s": 2358, "text": "Thus, an geeks_field UUIDField is created when you run makemigrations on the project.It is a field to store python’s UUID instance." }, { "code": null, "e": 2733, "s": 2490, "text": "UUID, Universal Unique Identifier, is a python library which helps in generating random objects of 128 bits as ids. To know more about UUID visit Generating Random id’s using UUID in Python. Let’s try to save a uuid object into the UUIDField." }, { "code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # importing uuidimport uuid # creating an instance of# uuid objecttest = uuid.uuid4() # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = test)geek_object.save()", "e": 3010, "s": 2733, "text": null }, { "code": null, "e": 3088, "s": 3010, "text": "Now let’s check it in admin server. We have created an instance of GeeksModel" }, { "code": null, "e": 3427, "s": 3088, "text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to UUIDField will enable it to store empty values for that table in relational database.Here are the option and attributes that an UUIDField can use." }, { "code": null, "e": 3439, "s": 3427, "text": "NaveenArora" }, { "code": null, "e": 3453, "s": 3439, "text": "Django-models" }, { "code": null, "e": 3467, "s": 3453, "text": "Python Django" }, { "code": null, "e": 3474, "s": 3467, "text": "Python" }, { "code": null, "e": 3572, "s": 3474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3590, "s": 3572, "text": "Python Dictionary" }, { "code": null, "e": 3632, "s": 3590, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3654, "s": 3632, "text": "Enumerate() in Python" }, { "code": null, "e": 3689, "s": 3654, "text": "Read a file line by line in Python" }, { "code": null, "e": 3715, "s": 3689, "text": "Python String | replace()" }, { "code": null, "e": 3747, "s": 3715, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3776, "s": 3747, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3803, "s": 3776, "text": "Python Classes and Objects" }, { "code": null, "e": 3833, "s": 3803, "text": "Iterate over a list in Python" } ]
How to Calculate Cronbach’s Alpha in R?
10 Jan, 2022 In this article, we will learn how to calculate Cronbach’s Alpha in the R Programming Language. Cronbach’s Alpha helps us to measure the internal consistency of a group of data. It is a coefficient of reliability. It helps us to validate the consistency of a questionnaire or survey. The Cronbach’s Alpha ranges between 0 and 1. The higher value for Cronbach’s Alpha means more reliable the group of data is. The following table shows the meaning behind the different ranges of values of Cronbach’s Alpha. To calculate Cronbach’s Alpha in the R Language, we use the cronbach.alpha() function of the ltm package library. To use ltm package library, we first need to install the library using the following syntax: install.packages("ltm") After installing the ltm package library we can load the library using the library() function and use the cronbach.alpha() function to calculate the coefficient of reliability. The cronbach.alpha() function takes the data frame as an argument and returns an object of class cronbachAlpha with the following components. alpha: determines the value of Cronbach’s alpha. n: determines the number of sample units in the data frame. p: determines the total number of items. standardized: determines a copy of the standardized argument. name: determines the name of argument data which is one of the column variables. To use the cronbach.alpha() function for computation of cronbach’s alpha we use the following syntax. Syntax: cronbach.alpha(data, standardized, CI ) where, data: determines the data frame to be used. standardized: It is a boolean. If TRUE, the standardized Cronbach’s alpha is computed. CI: It is a boolean. If TRUE a Bootstrap confidence interval for Cronbach’s alpha is computed. Example: Here, is an example of a basic Cronbach’s Alpha calculation. R # create sample datasample_data < - data.frame(var1=c(1, 2, 1, 2, 1, 2, 1, 3, 3, 1, 4), var2=c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3), var3=c(2, 1, 3, 1, 2, 3, 3, 4, 4, 2, 1)) # load library ltmlibrary(ltm) # calculate cronbach's alphacronbach.alpha(sample_data) Output: Cronbach's alpha for the 'sample_data' data-set Items: 3 Sample units: 11 alpha: 0.231 Here, the alpha value of 0.231 means that the sample_data dataset is highly inconsistent. Example: Here, is an example of a detailed Cronbach’s Alpha calculation along with standardized computation and bootstrap confidence. R # create sample datasample_data < - data.frame(var1=c(1, 2, 1, 2, 1, 2, 1, 3, 3, 1, 4), var2=c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3), var3=c(2, 1, 3, 1, 2, 3, 3, 4, 4, 2, 1)) # load library ltmlibrary(ltm) # calculate cronbach's alphacronbach.alpha(sample_data, CI=TRUE, standardized=TRUE) Output: Standardized Cronbach's alpha for the 'sample_data' data-set Items: 3 Sample units: 11 alpha: 0.238 Bootstrap 95% CI based on 1000 samples 2.5% 97.5% -1.849 0.820 Here, we can see detailed analysis which shows 95% confidence interval is in the range of -1.849 to 0.820, which implies a very inconsistent dataframe. simmytarika5 Picked R-DataFrame R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2022" }, { "code": null, "e": 124, "s": 28, "text": "In this article, we will learn how to calculate Cronbach’s Alpha in the R Programming Language." }, { "code": null, "e": 534, "s": 124, "text": "Cronbach’s Alpha helps us to measure the internal consistency of a group of data. It is a coefficient of reliability. It helps us to validate the consistency of a questionnaire or survey. The Cronbach’s Alpha ranges between 0 and 1. The higher value for Cronbach’s Alpha means more reliable the group of data is. The following table shows the meaning behind the different ranges of values of Cronbach’s Alpha." }, { "code": null, "e": 741, "s": 534, "text": "To calculate Cronbach’s Alpha in the R Language, we use the cronbach.alpha() function of the ltm package library. To use ltm package library, we first need to install the library using the following syntax:" }, { "code": null, "e": 765, "s": 741, "text": "install.packages(\"ltm\")" }, { "code": null, "e": 1084, "s": 765, "text": "After installing the ltm package library we can load the library using the library() function and use the cronbach.alpha() function to calculate the coefficient of reliability. The cronbach.alpha() function takes the data frame as an argument and returns an object of class cronbachAlpha with the following components." }, { "code": null, "e": 1133, "s": 1084, "text": "alpha: determines the value of Cronbach’s alpha." }, { "code": null, "e": 1193, "s": 1133, "text": "n: determines the number of sample units in the data frame." }, { "code": null, "e": 1234, "s": 1193, "text": "p: determines the total number of items." }, { "code": null, "e": 1296, "s": 1234, "text": "standardized: determines a copy of the standardized argument." }, { "code": null, "e": 1377, "s": 1296, "text": "name: determines the name of argument data which is one of the column variables." }, { "code": null, "e": 1479, "s": 1377, "text": "To use the cronbach.alpha() function for computation of cronbach’s alpha we use the following syntax." }, { "code": null, "e": 1487, "s": 1479, "text": "Syntax:" }, { "code": null, "e": 1527, "s": 1487, "text": "cronbach.alpha(data, standardized, CI )" }, { "code": null, "e": 1534, "s": 1527, "text": "where," }, { "code": null, "e": 1578, "s": 1534, "text": "data: determines the data frame to be used." }, { "code": null, "e": 1665, "s": 1578, "text": "standardized: It is a boolean. If TRUE, the standardized Cronbach’s alpha is computed." }, { "code": null, "e": 1760, "s": 1665, "text": "CI: It is a boolean. If TRUE a Bootstrap confidence interval for Cronbach’s alpha is computed." }, { "code": null, "e": 1769, "s": 1760, "text": "Example:" }, { "code": null, "e": 1830, "s": 1769, "text": "Here, is an example of a basic Cronbach’s Alpha calculation." }, { "code": null, "e": 1832, "s": 1830, "text": "R" }, { "code": "# create sample datasample_data < - data.frame(var1=c(1, 2, 1, 2, 1, 2, 1, 3, 3, 1, 4), var2=c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3), var3=c(2, 1, 3, 1, 2, 3, 3, 4, 4, 2, 1)) # load library ltmlibrary(ltm) # calculate cronbach's alphacronbach.alpha(sample_data)", "e": 2141, "s": 1832, "text": null }, { "code": null, "e": 2149, "s": 2141, "text": "Output:" }, { "code": null, "e": 2236, "s": 2149, "text": "Cronbach's alpha for the 'sample_data' data-set\nItems: 3\nSample units: 11\nalpha: 0.231" }, { "code": null, "e": 2326, "s": 2236, "text": "Here, the alpha value of 0.231 means that the sample_data dataset is highly inconsistent." }, { "code": null, "e": 2335, "s": 2326, "text": "Example:" }, { "code": null, "e": 2460, "s": 2335, "text": "Here, is an example of a detailed Cronbach’s Alpha calculation along with standardized computation and bootstrap confidence." }, { "code": null, "e": 2462, "s": 2460, "text": "R" }, { "code": "# create sample datasample_data < - data.frame(var1=c(1, 2, 1, 2, 1, 2, 1, 3, 3, 1, 4), var2=c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3), var3=c(2, 1, 3, 1, 2, 3, 3, 4, 4, 2, 1)) # load library ltmlibrary(ltm) # calculate cronbach's alphacronbach.alpha(sample_data, CI=TRUE, standardized=TRUE)", "e": 2799, "s": 2462, "text": null }, { "code": null, "e": 2807, "s": 2799, "text": "Output:" }, { "code": null, "e": 2978, "s": 2807, "text": "Standardized Cronbach's alpha for the 'sample_data' data-set\nItems: 3\nSample units: 11\nalpha: 0.238\n\nBootstrap 95% CI based on 1000 samples\n 2.5% 97.5% \n-1.849 0.820 " }, { "code": null, "e": 3130, "s": 2978, "text": "Here, we can see detailed analysis which shows 95% confidence interval is in the range of -1.849 to 0.820, which implies a very inconsistent dataframe." }, { "code": null, "e": 3143, "s": 3130, "text": "simmytarika5" }, { "code": null, "e": 3150, "s": 3143, "text": "Picked" }, { "code": null, "e": 3162, "s": 3150, "text": "R-DataFrame" }, { "code": null, "e": 3175, "s": 3162, "text": "R-Statistics" }, { "code": null, "e": 3186, "s": 3175, "text": "R Language" } ]
How to Install SQLmap in Windows?
09 Nov, 2021 Sqlmap is an open-source penetration testing tool. It comes with a powerful detection engine. It automates the process of detecting & taking over the database server. There is total of six SQL injection tool techniques are present. This is the highest amount of tool present than others. When we are going to extract the password from a vulnerable database, often the passwords are in hash form. It can detect the hash & can mention which type of hash was that. It supports extracting user, password hashes, table,s etc. We can download & update any file from the database server underlying file system. Step 1: Browse to this link. Step 2: Click on the zip file on the right side & download the file. Step 3: Then you have to extract the zip file. And then rename it to ‘sqlmap’ Step 4: Then cut the folder & paste it to your pc C drive Step 5: Open Command Prompt from the start menu. Step 6: Write down the following command one by one cd ../ ../ dir Step 7: Then write another some commands cd sqlmap sqlmap.py It will give the proper output & hence your installation is successful. DBMS-SQL Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to download and install Python Latest Version on Android How to Add External JAR File to an IntelliJ IDEA Project? How to Fix “passwd: Authentication token manipulation error” in Linux Spring Boot | How to publish JSON messages on Apache Kafka How to install Python on Windows? Installation of Node.js on Linux Installation of Node.js on Windows How to Install Jupyter Notebook on MacOS? How to Install and Use NVM on Windows? How to Install Pygame on Windows ?
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Nov, 2021" }, { "code": null, "e": 490, "s": 28, "text": "Sqlmap is an open-source penetration testing tool. It comes with a powerful detection engine. It automates the process of detecting & taking over the database server. There is total of six SQL injection tool techniques are present. This is the highest amount of tool present than others. When we are going to extract the password from a vulnerable database, often the passwords are in hash form. It can detect the hash & can mention which type of hash was that." }, { "code": null, "e": 549, "s": 490, "text": "It supports extracting user, password hashes, table,s etc." }, { "code": null, "e": 632, "s": 549, "text": "We can download & update any file from the database server underlying file system." }, { "code": null, "e": 662, "s": 632, "text": "Step 1: Browse to this link. " }, { "code": null, "e": 731, "s": 662, "text": "Step 2: Click on the zip file on the right side & download the file." }, { "code": null, "e": 809, "s": 731, "text": "Step 3: Then you have to extract the zip file. And then rename it to ‘sqlmap’" }, { "code": null, "e": 867, "s": 809, "text": "Step 4: Then cut the folder & paste it to your pc C drive" }, { "code": null, "e": 916, "s": 867, "text": "Step 5: Open Command Prompt from the start menu." }, { "code": null, "e": 968, "s": 916, "text": "Step 6: Write down the following command one by one" }, { "code": null, "e": 983, "s": 968, "text": "cd ../ ../\ndir" }, { "code": null, "e": 1024, "s": 983, "text": "Step 7: Then write another some commands" }, { "code": null, "e": 1044, "s": 1024, "text": "cd sqlmap\nsqlmap.py" }, { "code": null, "e": 1116, "s": 1044, "text": "It will give the proper output & hence your installation is successful." }, { "code": null, "e": 1125, "s": 1116, "text": "DBMS-SQL" }, { "code": null, "e": 1132, "s": 1125, "text": "Picked" }, { "code": null, "e": 1139, "s": 1132, "text": "How To" }, { "code": null, "e": 1158, "s": 1139, "text": "Installation Guide" }, { "code": null, "e": 1256, "s": 1158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1317, "s": 1256, "text": "How to download and install Python Latest Version on Android" }, { "code": null, "e": 1375, "s": 1317, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 1445, "s": 1375, "text": "How to Fix “passwd: Authentication token manipulation error” in Linux" }, { "code": null, "e": 1504, "s": 1445, "text": "Spring Boot | How to publish JSON messages on Apache Kafka" }, { "code": null, "e": 1538, "s": 1504, "text": "How to install Python on Windows?" }, { "code": null, "e": 1571, "s": 1538, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1606, "s": 1571, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 1648, "s": 1606, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 1687, "s": 1648, "text": "How to Install and Use NVM on Windows?" } ]
JavaScript Promise finally() Method
17 Mar, 2021 The finally() method of the Promise object is used to return a Promise when a Promise is settled, that is, it is either fulfilled or rejected. A Promise is a JavaScript object which generates a value after an asynchronous function executes successfully. When it does not execute successfully due to a timeout, then it generates an error. It can be used to perform cleanup tasks once the promise is settled as it is always executed irrespective of whether the promise is fulfilled or rejected. It also prevents the duplication of code in the then() and catch() methods of the Promise. Syntax: task.finally(function() { // Task to be performed when // the promise is settled }); Parameters: This method has a single parameter as mentioned above and described below: onFinally: It is the function that will be called when the Promise is settled. Return Value: It returns a Promise whose finally handler is set to the specified function. The below example demonstrates the finally() method: Example: Javascript // Define the Promiselet task = new Promise((resolve, reject) => { setTimeout(() => { // Reject the Promise reject("Promise has been rejected!"); }, 2000);}); task .then( (data) => { console.log(data); }, // Handle any error (error) => { console.log("Error:", error); } ) // Specify the code to be executed // after the Promise is settled .finally(() => { console.log( "This is finally() block that is " + "executed after Promise is settled" ); }); Output: Error: Promise has been rejected! This is finally() block that is executed after Promise is settled JavaScript-Methods Picked 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 Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Mar, 2021" }, { "code": null, "e": 390, "s": 52, "text": "The finally() method of the Promise object is used to return a Promise when a Promise is settled, that is, it is either fulfilled or rejected. A Promise is a JavaScript object which generates a value after an asynchronous function executes successfully. When it does not execute successfully due to a timeout, then it generates an error." }, { "code": null, "e": 636, "s": 390, "text": "It can be used to perform cleanup tasks once the promise is settled as it is always executed irrespective of whether the promise is fulfilled or rejected. It also prevents the duplication of code in the then() and catch() methods of the Promise." }, { "code": null, "e": 644, "s": 636, "text": "Syntax:" }, { "code": null, "e": 734, "s": 644, "text": "task.finally(function() {\n // Task to be performed when\n // the promise is settled \n});" }, { "code": null, "e": 821, "s": 734, "text": "Parameters: This method has a single parameter as mentioned above and described below:" }, { "code": null, "e": 900, "s": 821, "text": "onFinally: It is the function that will be called when the Promise is settled." }, { "code": null, "e": 991, "s": 900, "text": "Return Value: It returns a Promise whose finally handler is set to the specified function." }, { "code": null, "e": 1044, "s": 991, "text": "The below example demonstrates the finally() method:" }, { "code": null, "e": 1053, "s": 1044, "text": "Example:" }, { "code": null, "e": 1064, "s": 1053, "text": "Javascript" }, { "code": "// Define the Promiselet task = new Promise((resolve, reject) => { setTimeout(() => { // Reject the Promise reject(\"Promise has been rejected!\"); }, 2000);}); task .then( (data) => { console.log(data); }, // Handle any error (error) => { console.log(\"Error:\", error); } ) // Specify the code to be executed // after the Promise is settled .finally(() => { console.log( \"This is finally() block that is \" + \"executed after Promise is settled\" ); });", "e": 1576, "s": 1064, "text": null }, { "code": null, "e": 1584, "s": 1576, "text": "Output:" }, { "code": null, "e": 1684, "s": 1584, "text": "Error: Promise has been rejected!\nThis is finally() block that is executed after Promise is settled" }, { "code": null, "e": 1703, "s": 1684, "text": "JavaScript-Methods" }, { "code": null, "e": 1710, "s": 1703, "text": "Picked" }, { "code": null, "e": 1721, "s": 1710, "text": "JavaScript" }, { "code": null, "e": 1738, "s": 1721, "text": "Web Technologies" }, { "code": null, "e": 1836, "s": 1738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1897, "s": 1836, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1937, "s": 1897, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1979, "s": 1937, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2020, "s": 1979, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2042, "s": 2020, "text": "JavaScript | Promises" }, { "code": null, "e": 2075, "s": 2042, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2137, "s": 2075, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2198, "s": 2137, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2248, "s": 2198, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to get the child element of a parent using JavaScript ?
22 Nov, 2021 In this article, we will learn to get the child element of the parent using Javascript. Given an HTML document and the task is to select a particular element and get all the child elements of the parent element with the help of JavaScript. For this, there are 2 ways to get the child element: By using the children property By using querySelector Method We will discuss both approaches & understand their implementation through the examples. The DOM children property is used to return HTMLcollection of all the child elements of the specified element. Approach 1: Select an element whose child element is going to be selected. Use .children property to get access of all the children of the element. Select the particular child based on the index. Example 1: This example implements the .children property to get the HTMLcollection of all the child elements of the specified element. HTML <!DOCTYPE HTML><html> <head> <title>Finding child element of parent with pure JavaScript.</title> <style> .parent { background: green; color: white; } .child { background: blue; color: white; margin: 10px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"></p> <div class="parent" id="parent"> Parent <div class="child"> Child </div> </div> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button select the child node."; function GFG_Fun() { parent = document.getElementById('parent'); children = parent.children[0]; down.innerHTML = "Text of child node is - '" + children.innerHTML + "'"; } </script></body> </html> Output: class Property The querySelector() method in HTML is used to return the first element that matches a specified CSS selector(s) in the document. Approach 2: Select the parent element whose child element is going to be selected. Use .querySelector() method on parent. Use the className of the child to select that particular child. Example 1: This example implements the .querySelector() method to get the first element to match for the specified CSS selector(s) in the document. HTML <!DOCTYPE HTML><html> <head> <title>How to get the child element of a parent using JavaScript ?</title> <style> .parent { background: green; color: white; } .child1 { background: blue; color: white; margin: 10px; } .child2 { background: red; color: white; margin: 10px; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div class="parent" id="parent"> Parent <div class="child child1"> Child1 </div> <div class="child child2"> Child2 </div> </div> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button select the child node."; function GFG_Fun() { parent = document.getElementById('parent'); children = parent.querySelectorAll('.child'); down.innerHTML = "Text of child node is - '" + children[0].innerHTML + "' and '" + children[1].innerHTML + "'"; } </script></body> </html> Output: .querySelector() Method bhaskargeeksforgeeks JavaScript-Questions JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Nov, 2021" }, { "code": null, "e": 345, "s": 52, "text": "In this article, we will learn to get the child element of the parent using Javascript. Given an HTML document and the task is to select a particular element and get all the child elements of the parent element with the help of JavaScript. For this, there are 2 ways to get the child element:" }, { "code": null, "e": 376, "s": 345, "text": "By using the children property" }, { "code": null, "e": 406, "s": 376, "text": "By using querySelector Method" }, { "code": null, "e": 494, "s": 406, "text": "We will discuss both approaches & understand their implementation through the examples." }, { "code": null, "e": 606, "s": 494, "text": "The DOM children property is used to return HTMLcollection of all the child elements of the specified element. " }, { "code": null, "e": 618, "s": 606, "text": "Approach 1:" }, { "code": null, "e": 681, "s": 618, "text": "Select an element whose child element is going to be selected." }, { "code": null, "e": 754, "s": 681, "text": "Use .children property to get access of all the children of the element." }, { "code": null, "e": 802, "s": 754, "text": "Select the particular child based on the index." }, { "code": null, "e": 938, "s": 802, "text": "Example 1: This example implements the .children property to get the HTMLcollection of all the child elements of the specified element." }, { "code": null, "e": 943, "s": 938, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <title>Finding child element of parent with pure JavaScript.</title> <style> .parent { background: green; color: white; } .child { background: blue; color: white; margin: 10px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"></p> <div class=\"parent\" id=\"parent\"> Parent <div class=\"child\"> Child </div> </div> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button select the child node.\"; function GFG_Fun() { parent = document.getElementById('parent'); children = parent.children[0]; down.innerHTML = \"Text of child node is - '\" + children.innerHTML + \"'\"; } </script></body> </html>", "e": 2106, "s": 943, "text": null }, { "code": null, "e": 2114, "s": 2106, "text": "Output:" }, { "code": null, "e": 2129, "s": 2114, "text": "class Property" }, { "code": null, "e": 2258, "s": 2129, "text": "The querySelector() method in HTML is used to return the first element that matches a specified CSS selector(s) in the document." }, { "code": null, "e": 2270, "s": 2258, "text": "Approach 2:" }, { "code": null, "e": 2341, "s": 2270, "text": "Select the parent element whose child element is going to be selected." }, { "code": null, "e": 2380, "s": 2341, "text": "Use .querySelector() method on parent." }, { "code": null, "e": 2444, "s": 2380, "text": "Use the className of the child to select that particular child." }, { "code": null, "e": 2592, "s": 2444, "text": "Example 1: This example implements the .querySelector() method to get the first element to match for the specified CSS selector(s) in the document." }, { "code": null, "e": 2597, "s": 2592, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <title>How to get the child element of a parent using JavaScript ?</title> <style> .parent { background: green; color: white; } .child1 { background: blue; color: white; margin: 10px; } .child2 { background: red; color: white; margin: 10px; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div class=\"parent\" id=\"parent\"> Parent <div class=\"child child1\"> Child1 </div> <div class=\"child child2\"> Child2 </div> </div> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button select the child node.\"; function GFG_Fun() { parent = document.getElementById('parent'); children = parent.querySelectorAll('.child'); down.innerHTML = \"Text of child node is - '\" + children[0].innerHTML + \"' and '\" + children[1].innerHTML + \"'\"; } </script></body> </html>", "e": 3986, "s": 2597, "text": null }, { "code": null, "e": 3994, "s": 3986, "text": "Output:" }, { "code": null, "e": 4018, "s": 3994, "text": ".querySelector() Method" }, { "code": null, "e": 4039, "s": 4018, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 4060, "s": 4039, "text": "JavaScript-Questions" }, { "code": null, "e": 4071, "s": 4060, "text": "JavaScript" }, { "code": null, "e": 4088, "s": 4071, "text": "Web Technologies" }, { "code": null, "e": 4115, "s": 4088, "text": "Web technologies Questions" } ]
Quantitative Aptitude – Time, Work and Distance
03 Dec, 2021 Quantitative Aptitude or commonly called as the mathematical section of Aptitude is a crucial part in getting placement in many companies that prefer quantitative ability evaluation. Many big companies like Infosys, TCS and many others have their first round an Aptitude Test. To correctly crack the test in time, it’s important to learn to understand how the solution to a particular type of situation or question is reached. There are many easy, shorthand tricks and various formulas for easy understanding and quick answering of the questions under this section. There are many topics that come under quantitative aptitude like, Time and Work Probability Boats and Streams Permutation and Combination Simple and Compound Interest Heights and Distances, etc. Time and Work Probability Boats and Streams Permutation and Combination Simple and Compound Interest Heights and Distances, etc. Here we will discuss how to solve questions based on relation between Time and Work. Note: If X is two times better than Y in completing the work then: Time taken by X to finish work : Time taken by Y to finish work = 1:3 Work done by A : Work done by B = 3:1 Here, ” : ” denotes ratio. How to find no. of days taken to complete given amount of work: If X’s 1 day’s work = 1/m then it will take X, m days to finish given work. How to find amount of work done from given number of days: If X can do some work in m days, then work done by X in one day = 1/m If X is two times better than Y in completing the work then: Time taken by X to finish work : Time taken by Y to finish work = 1:3 Work done by A : Work done by B = 3:1 Here, ” : ” denotes ratio. How to find no. of days taken to complete given amount of work: If X’s 1 day’s work = 1/m then it will take X, m days to finish given work. How to find amount of work done from given number of days: If X can do some work in m days, then work done by X in one day = 1/m Que-1: A and B together can do a piece of work in 8 days. If A alone can do the same work in 12 days, then B alone can do the same work in? Explanation: Let B take x days to complete the work alone. So, 1/x + 1/12 = 1/8 => 1/x = 1/8 – 1/12 = 1/24 => x = 24 Que-2: If 3 men or 4 women can construct a wall in 43 days, then the number of days that 7 men and 5 women take to construct it is? Explanation : 3 men = 4 women or 1 man = 4/3 women Therefore, 7 men + 5 women = (7 × 4/3 + 5) women i.e., 43/3 women 4 women can construct the wall in 43 days Therefore, 43/3 women can construct it in = 12 days Que-3: Arnold alone can do some work in 6 days and Brat alone can do the same work in 8 days. Arnold and Brat decided to do it for $3200. With the help of Carl, they completed the work in 3 days. How much is to be paid to Carl? Explanation : Carl’s 1 day’s work = 1/3 – (1/6 + 1/8) = 1/3 – 7/24 = 1/24 Arnold’s wages : Brat’s wages : Carl’s wages can be written as -> 1/6 : 1/8 : 1/24 = 4:3:1 So, Carl’s share, = 1/8 * 3200 = $400 Que-4: A tank has four inlet pipes.When first three inlet pipes are opened together, tank can be filled in 12 min and when the last three inlet pipes are opened together, tank can be filled in 15 minutes and by the first and last inlets only, tank can be filled in 24 minutes. What is the time taken by last pipe to fill half of the tank? Explanation : Let the four inlet pipes be P, Q, R and S respectively. Given, P + Q + R together can fill the tank in = 12 min Q + R + S together can fill the tank in = 15 min P + S together can fill the tank in = 24 min So, Total capacity of the tank = 120 units (L.C.M of time taken by all 4 inlet pipes be P, Q, R, and S). Now, Efficiency of inlet pipes P + Q + R = Total capacity of the tank/ Time taken by P + Q + R together to fill the tank = 120/12 = 10 units/minute Similarly, Efficiency of inlet pipes Q + R + S = 120/15 = 8 units/minute and Efficiency of inlet pipes P + S = 120/24 = 5 units/minute On Adding all the obtained efficiencies, we get, 2(P + Q + R + S) = 23 units/minute Efficiency of (P + Q + R + S) = (23/2) units/minute Efficiency of S, = (23/2) – Efficiency of (P + Q + R) = (23/2) – 10 = 3/2 units/minute Time taken by last pipe (S) to fill half of the tank = (1/2) * [Total capacity of the tank/Efficiency of pipe S] = (1/2) * [120/(3/2)] = (1/2) * [(120 * 2)/3] = 40 mins Que-5: Either 6 women or 17 men can paint a wall in 33 days. The number of days required to paint three such walls by 12 women and 32 men working at same rate? Explanation : 6 women = 17 men 1 women = 17/6 men Total work = 17*33 One day efficiency of 12 women and 32 men = 12 women + 32 men = (12*17)/6 men + 32 men = 34 men + 32 men = 66 men Days required for 12 women and 32 men = (17*33)/66 = 8.5 days The number of days required to paint three such walls = 8.5*3 = 25.5 days surindertarika1234 Technical Scripter 2019 Computer Subject Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Checking in Compiler Design Difference Between Edge Computing and Fog Computing Optimization of Basic Blocks OSI Security Architecture Token, Patterns, and Lexems Compiler Design - Variants of Syntax Tree Difference Between User Mode and Kernel Mode Evaluation Order For SDD 50 Common Ports You Should Know Firewall Design Principles
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Dec, 2021" }, { "code": null, "e": 331, "s": 53, "text": "Quantitative Aptitude or commonly called as the mathematical section of Aptitude is a crucial part in getting placement in many companies that prefer quantitative ability evaluation. Many big companies like Infosys, TCS and many others have their first round an Aptitude Test. " }, { "code": null, "e": 621, "s": 331, "text": "To correctly crack the test in time, it’s important to learn to understand how the solution to a particular type of situation or question is reached. There are many easy, shorthand tricks and various formulas for easy understanding and quick answering of the questions under this section. " }, { "code": null, "e": 688, "s": 621, "text": "There are many topics that come under quantitative aptitude like, " }, { "code": null, "e": 824, "s": 688, "text": "Time and Work Probability Boats and Streams Permutation and Combination Simple and Compound Interest Heights and Distances, etc. " }, { "code": null, "e": 840, "s": 824, "text": "Time and Work " }, { "code": null, "e": 854, "s": 840, "text": "Probability " }, { "code": null, "e": 874, "s": 854, "text": "Boats and Streams " }, { "code": null, "e": 904, "s": 874, "text": "Permutation and Combination " }, { "code": null, "e": 935, "s": 904, "text": "Simple and Compound Interest " }, { "code": null, "e": 965, "s": 935, "text": "Heights and Distances, etc. " }, { "code": null, "e": 1051, "s": 965, "text": "Here we will discuss how to solve questions based on relation between Time and Work. " }, { "code": null, "e": 1059, "s": 1051, "text": "Note: " }, { "code": null, "e": 1528, "s": 1059, "text": "If X is two times better than Y in completing the work then: Time taken by X to finish work : Time taken by Y to finish work = 1:3 Work done by A : Work done by B = 3:1 Here, ” : ” denotes ratio. How to find no. of days taken to complete given amount of work: If X’s 1 day’s work = 1/m then it will take X, m days to finish given work. How to find amount of work done from given number of days: If X can do some work in m days, then work done by X in one day = 1/m " }, { "code": null, "e": 1726, "s": 1528, "text": "If X is two times better than Y in completing the work then: Time taken by X to finish work : Time taken by Y to finish work = 1:3 Work done by A : Work done by B = 3:1 Here, ” : ” denotes ratio. " }, { "code": null, "e": 1868, "s": 1726, "text": "How to find no. of days taken to complete given amount of work: If X’s 1 day’s work = 1/m then it will take X, m days to finish given work. " }, { "code": null, "e": 1999, "s": 1868, "text": "How to find amount of work done from given number of days: If X can do some work in m days, then work done by X in one day = 1/m " }, { "code": null, "e": 2140, "s": 1999, "text": "Que-1: A and B together can do a piece of work in 8 days. If A alone can do the same work in 12 days, then B alone can do the same work in? " }, { "code": null, "e": 2205, "s": 2140, "text": "Explanation: Let B take x days to complete the work alone. So, " }, { "code": null, "e": 2262, "s": 2205, "text": "1/x + 1/12 = 1/8 \n=> 1/x = 1/8 – 1/12 = 1/24 \n=> x = 24 " }, { "code": null, "e": 2395, "s": 2262, "text": "Que-2: If 3 men or 4 women can construct a wall in 43 days, then the number of days that 7 men and 5 women take to construct it is? " }, { "code": null, "e": 2411, "s": 2395, "text": "Explanation : " }, { "code": null, "e": 2449, "s": 2411, "text": "3 men = 4 women or 1 man = 4/3 women " }, { "code": null, "e": 2461, "s": 2449, "text": "Therefore, " }, { "code": null, "e": 2500, "s": 2461, "text": "7 men + 5 women = (7 × 4/3 + 5) women " }, { "code": null, "e": 2612, "s": 2500, "text": "i.e., 43/3 women 4 women can construct the wall in 43 days Therefore, 43/3 women can construct it in = 12 days " }, { "code": null, "e": 2841, "s": 2612, "text": "Que-3: Arnold alone can do some work in 6 days and Brat alone can do the same work in 8 days. Arnold and Brat decided to do it for $3200. With the help of Carl, they completed the work in 3 days. How much is to be paid to Carl? " }, { "code": null, "e": 2877, "s": 2841, "text": "Explanation : Carl’s 1 day’s work " }, { "code": null, "e": 2918, "s": 2877, "text": "= 1/3 – (1/6 + 1/8) = 1/3 – 7/24 = 1/24 " }, { "code": null, "e": 2986, "s": 2918, "text": "Arnold’s wages : Brat’s wages : Carl’s wages can be written as -> " }, { "code": null, "e": 3012, "s": 2986, "text": "1/6 : 1/8 : 1/24 = 4:3:1 " }, { "code": null, "e": 3032, "s": 3012, "text": "So, Carl’s share, " }, { "code": null, "e": 3054, "s": 3032, "text": "= 1/8 * 3200 = $400 " }, { "code": null, "e": 3394, "s": 3054, "text": "Que-4: A tank has four inlet pipes.When first three inlet pipes are opened together, tank can be filled in 12 min and when the last three inlet pipes are opened together, tank can be filled in 15 minutes and by the first and last inlets only, tank can be filled in 24 minutes. What is the time taken by last pipe to fill half of the tank? " }, { "code": null, "e": 3473, "s": 3394, "text": "Explanation : Let the four inlet pipes be P, Q, R and S respectively. Given, " }, { "code": null, "e": 3619, "s": 3473, "text": "P + Q + R together can fill the tank in = 12 min \nQ + R + S together can fill the tank in = 15 min \nP + S together can fill the tank in = 24 min " }, { "code": null, "e": 3725, "s": 3619, "text": "So, Total capacity of the tank = 120 units (L.C.M of time taken by all 4 inlet pipes be P, Q, R, and S). " }, { "code": null, "e": 3848, "s": 3725, "text": "Now, Efficiency of inlet pipes P + Q + R = Total capacity of the tank/ Time taken by P + Q + R together to fill the tank " }, { "code": null, "e": 3876, "s": 3848, "text": "= 120/12 = 10 units/minute " }, { "code": null, "e": 4012, "s": 3876, "text": "Similarly, Efficiency of inlet pipes Q + R + S = 120/15 = 8 units/minute and Efficiency of inlet pipes P + S = 120/24 = 5 units/minute " }, { "code": null, "e": 4063, "s": 4012, "text": "On Adding all the obtained efficiencies, we get, " }, { "code": null, "e": 4099, "s": 4063, "text": "2(P + Q + R + S) = 23 units/minute " }, { "code": null, "e": 4170, "s": 4099, "text": "Efficiency of (P + Q + R + S) = (23/2) units/minute Efficiency of S, " }, { "code": null, "e": 4243, "s": 4170, "text": "= (23/2) – Efficiency of (P + Q + R) \n= (23/2) – 10 \n= 3/2 units/minute " }, { "code": null, "e": 4298, "s": 4243, "text": "Time taken by last pipe (S) to fill half of the tank " }, { "code": null, "e": 4418, "s": 4298, "text": "= (1/2) * [Total capacity of the tank/Efficiency of pipe S] \n= (1/2) * [120/(3/2)] \n= (1/2) * [(120 * 2)/3] \n= 40 mins " }, { "code": null, "e": 4579, "s": 4418, "text": "Que-5: Either 6 women or 17 men can paint a wall in 33 days. The number of days required to paint three such walls by 12 women and 32 men working at same rate? " }, { "code": null, "e": 4595, "s": 4579, "text": "Explanation : " }, { "code": null, "e": 4653, "s": 4595, "text": "6 women = 17 men \n1 women = 17/6 men \nTotal work = 17*33 " }, { "code": null, "e": 4697, "s": 4653, "text": "One day efficiency of 12 women and 32 men " }, { "code": null, "e": 4773, "s": 4697, "text": "= 12 women + 32 men \n= (12*17)/6 men + 32 men \n= 34 men + 32 men \n= 66 men " }, { "code": null, "e": 4813, "s": 4773, "text": "Days required for 12 women and 32 men " }, { "code": null, "e": 4838, "s": 4813, "text": "= (17*33)/66 = 8.5 days " }, { "code": null, "e": 4893, "s": 4838, "text": "The number of days required to paint three such walls " }, { "code": null, "e": 4914, "s": 4893, "text": "= 8.5*3 = 25.5 days " }, { "code": null, "e": 4933, "s": 4914, "text": "surindertarika1234" }, { "code": null, "e": 4957, "s": 4933, "text": "Technical Scripter 2019" }, { "code": null, "e": 4974, "s": 4957, "text": "Computer Subject" }, { "code": null, "e": 4993, "s": 4974, "text": "Technical Scripter" }, { "code": null, "e": 5091, "s": 4993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5124, "s": 5091, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 5176, "s": 5124, "text": "Difference Between Edge Computing and Fog Computing" }, { "code": null, "e": 5205, "s": 5176, "text": "Optimization of Basic Blocks" }, { "code": null, "e": 5231, "s": 5205, "text": "OSI Security Architecture" }, { "code": null, "e": 5259, "s": 5231, "text": "Token, Patterns, and Lexems" }, { "code": null, "e": 5301, "s": 5259, "text": "Compiler Design - Variants of Syntax Tree" }, { "code": null, "e": 5346, "s": 5301, "text": "Difference Between User Mode and Kernel Mode" }, { "code": null, "e": 5371, "s": 5346, "text": "Evaluation Order For SDD" }, { "code": null, "e": 5403, "s": 5371, "text": "50 Common Ports You Should Know" } ]
How to Show All Columns of a Pandas DataFrame?
19 Dec, 2021 In this article, we will discuss how to Show All Columns of a Pandas DataFrame. We will use the pandas set_option() method. This method will set the specified option’s value. Syntax : pandas.set_option(pat, value) Parameters : pat : Regexp which should match a single option. value : New value of option. Returns : None Raises : if no other option exists, the OptionError is raised To view and download the CSV file used in the below example click train.csv. Example: Without using the set_option() method: Python3 # importing packagesimport pandas as pd # importing 'train.csv'data = pd.read_csv('train.csv')data.head() Output: Example: After using the set_option() method: Here we have given ‘display.max_columns’ as an argument to view the maximum columns from our dataframe. Python3 # importing packagesimport pandas as pd # importing 'train.csv'data = pd.read_csv('train.csv') pd.set_option('display.max_columns', None)data.head() Output: We can view all columns, as we scroll to the right, unlike when we didn’t use the set_option() method. If we only want to view a certain number of columns: Syntax: pd.set_option(‘display.max_columns’, n) where, n is an integer. Example: Python3 # importing packagesimport pandas as pd # importing 'train.csv'data = pd.read_csv('train.csv')pd.set_option('display.max_columns', 4)data.head() Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Dec, 2021" }, { "code": null, "e": 108, "s": 28, "text": "In this article, we will discuss how to Show All Columns of a Pandas DataFrame." }, { "code": null, "e": 203, "s": 108, "text": "We will use the pandas set_option() method. This method will set the specified option’s value." }, { "code": null, "e": 212, "s": 203, "text": "Syntax :" }, { "code": null, "e": 243, "s": 212, "text": " pandas.set_option(pat, value)" }, { "code": null, "e": 256, "s": 243, "text": "Parameters :" }, { "code": null, "e": 305, "s": 256, "text": "pat : Regexp which should match a single option." }, { "code": null, "e": 334, "s": 305, "text": "value : New value of option." }, { "code": null, "e": 344, "s": 334, "text": "Returns :" }, { "code": null, "e": 350, "s": 344, "text": " None" }, { "code": null, "e": 360, "s": 350, "text": "Raises : " }, { "code": null, "e": 413, "s": 360, "text": "if no other option exists, the OptionError is raised" }, { "code": null, "e": 490, "s": 413, "text": "To view and download the CSV file used in the below example click train.csv." }, { "code": null, "e": 499, "s": 490, "text": "Example:" }, { "code": null, "e": 539, "s": 499, "text": "Without using the set_option() method: " }, { "code": null, "e": 547, "s": 539, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # importing 'train.csv'data = pd.read_csv('train.csv')data.head()", "e": 654, "s": 547, "text": null }, { "code": null, "e": 662, "s": 654, "text": "Output:" }, { "code": null, "e": 671, "s": 662, "text": "Example:" }, { "code": null, "e": 708, "s": 671, "text": "After using the set_option() method:" }, { "code": null, "e": 812, "s": 708, "text": "Here we have given ‘display.max_columns’ as an argument to view the maximum columns from our dataframe." }, { "code": null, "e": 820, "s": 812, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # importing 'train.csv'data = pd.read_csv('train.csv') pd.set_option('display.max_columns', None)data.head()", "e": 971, "s": 820, "text": null }, { "code": null, "e": 979, "s": 971, "text": "Output:" }, { "code": null, "e": 1135, "s": 979, "text": "We can view all columns, as we scroll to the right, unlike when we didn’t use the set_option() method. If we only want to view a certain number of columns:" }, { "code": null, "e": 1143, "s": 1135, "text": "Syntax:" }, { "code": null, "e": 1183, "s": 1143, "text": "pd.set_option(‘display.max_columns’, n)" }, { "code": null, "e": 1207, "s": 1183, "text": "where, n is an integer." }, { "code": null, "e": 1216, "s": 1207, "text": "Example:" }, { "code": null, "e": 1224, "s": 1216, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # importing 'train.csv'data = pd.read_csv('train.csv')pd.set_option('display.max_columns', 4)data.head()", "e": 1370, "s": 1224, "text": null }, { "code": null, "e": 1378, "s": 1370, "text": "Output:" }, { "code": null, "e": 1403, "s": 1378, "text": "pandas-dataframe-program" }, { "code": null, "e": 1410, "s": 1403, "text": "Picked" }, { "code": null, "e": 1434, "s": 1410, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1448, "s": 1434, "text": "Python-pandas" }, { "code": null, "e": 1455, "s": 1448, "text": "Python" } ]
VB.Net - Bit Shift Operators
Assume that the variable A holds 60 and variable B holds 13, then − Try the following example to understand all the bitwise operators available in VB.Net − Module BitwiseOp Sub Main() Dim a As Integer = 60 ' 60 = 0011 1100 Dim b As Integer = 13 ' 13 = 0000 1101 Dim c As Integer = 0 c = a And b ' 12 = 0000 1100 Console.WriteLine("Line 1 - Value of c is {0}", c) c = a Or b ' 61 = 0011 1101 Console.WriteLine("Line 2 - Value of c is {0}", c) c = a Xor b ' 49 = 0011 0001 Console.WriteLine("Line 3 - Value of c is {0}", c) c = Not a ' -61 = 1100 0011 Console.WriteLine("Line 4 - Value of c is {0}", c) c = a << 2 ' 240 = 1111 0000 Console.WriteLine("Line 5 - Value of c is {0}", c) c = a >> 2 ' 15 = 0000 1111 Console.WriteLine("Line 6 - Value of c is {0}", c) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15
[ { "code": null, "e": 2502, "s": 2434, "text": "Assume that the variable A holds 60 and variable B holds 13, then −" }, { "code": null, "e": 2590, "s": 2502, "text": "Try the following example to understand all the bitwise operators available in VB.Net −" }, { "code": null, "e": 3424, "s": 2590, "text": "Module BitwiseOp\n Sub Main()\n Dim a As Integer = 60 ' 60 = 0011 1100 \n Dim b As Integer = 13 ' 13 = 0000 1101\n Dim c As Integer = 0\n c = a And b ' 12 = 0000 1100 \n Console.WriteLine(\"Line 1 - Value of c is {0}\", c)\n c = a Or b ' 61 = 0011 1101 \n \n Console.WriteLine(\"Line 2 - Value of c is {0}\", c)\n c = a Xor b ' 49 = 0011 0001 \n \n Console.WriteLine(\"Line 3 - Value of c is {0}\", c)\n c = Not a ' -61 = 1100 0011 \n \n Console.WriteLine(\"Line 4 - Value of c is {0}\", c)\n c = a << 2 ' 240 = 1111 0000 \n \n Console.WriteLine(\"Line 5 - Value of c is {0}\", c)\n c = a >> 2 ' 15 = 0000 1111 \n \n Console.WriteLine(\"Line 6 - Value of c is {0}\", c)\n Console.ReadLine()\n End Sub\nEnd Module" }, { "code": null, "e": 3505, "s": 3424, "text": "When the above code is compiled and executed, it produces the following result −" } ]
Swift - For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. The syntax of for loop in Swift programming language is as follows − for init; condition; increment { statement(s) } The flow of control in a for loop is as follows − The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. import Cocoa var someInts:[Int] = [10, 20, 30] for var index = 0; index < 3; ++index { println( "Value of someInts[\(index)] is \(someInts[index])") } When the above code is executed, it produces the following result − Value of someInts[0] is 10 Value of someInts[1] is 20 Value of someInts[2] is 30
[ { "code": null, "e": 2526, "s": 2387, "text": "A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times." }, { "code": null, "e": 2595, "s": 2526, "text": "The syntax of for loop in Swift programming language is as follows −" }, { "code": null, "e": 2647, "s": 2595, "text": "for init; condition; increment {\n statement(s)\n}\n" }, { "code": null, "e": 2697, "s": 2647, "text": "The flow of control in a for loop is as follows −" }, { "code": null, "e": 2898, "s": 2697, "text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears." }, { "code": null, "e": 3099, "s": 2898, "text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears." }, { "code": null, "e": 3309, "s": 3099, "text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop." }, { "code": null, "e": 3519, "s": 3309, "text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop." }, { "code": null, "e": 3772, "s": 3519, "text": "After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition." }, { "code": null, "e": 4025, "s": 3772, "text": "After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition." }, { "code": null, "e": 4250, "s": 4025, "text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates." }, { "code": null, "e": 4475, "s": 4250, "text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates." }, { "code": null, "e": 4631, "s": 4475, "text": "import Cocoa\n\nvar someInts:[Int] = [10, 20, 30]\n\nfor var index = 0; index < 3; ++index {\n println( \"Value of someInts[\\(index)] is \\(someInts[index])\")\n}" }, { "code": null, "e": 4699, "s": 4631, "text": "When the above code is executed, it produces the following result −" } ]
K’th Non-repeating Character in Python using List Comprehension and OrderedDict
23 Nov, 2020 Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples: Input : str = geeksforgeeks, k = 3 Output : r First non-repeating character is f, second is o and third is r. Input : str = geeksforgeeks, k = 2 Output : o Input : str = geeksforgeeks, k = 4 Output : Less than k non-repeating characters in input. This problem has existing solution please refer link. We can solve this problem quickly in python using List Comprehension and OrderedDict. # Function to find k'th non repeating character # in string from collections import OrderedDict def kthRepeating(input,k): # OrderedDict returns a dictionary data # structure having characters of input # string as keys in the same order they # were inserted and 0 as their default value dict=OrderedDict.fromkeys(input,0) # now traverse input string to calculate # frequency of each character for ch in input: dict[ch]+=1 # now extract list of all keys whose value # is 1 from dict Ordered Dictionary nonRepeatDict = [key for (key,value) in dict.items() if value==1] # now return (k-1)th character from above list if len(nonRepeatDict) < k: return 'Less than k non-repeating characters in input.' else: return nonRepeatDict[k-1] # Driver function if __name__ == "__main__": input = "geeksforgeeks" k = 3 print (kthRepeating(input, k)) Output: r This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python dictionary-programs Python list-programs python-dict python-list Python Strings python-dict python-list Strings 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 Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Nov, 2020" }, { "code": null, "e": 293, "s": 52, "text": "Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string?" }, { "code": null, "e": 303, "s": 293, "text": "Examples:" }, { "code": null, "e": 562, "s": 303, "text": "Input : str = geeksforgeeks, k = 3\nOutput : r\nFirst non-repeating character is f,\nsecond is o and third is r.\n\nInput : str = geeksforgeeks, k = 2\nOutput : o\n\nInput : str = geeksforgeeks, k = 4\nOutput : Less than k non-repeating\n characters in input.\n" }, { "code": null, "e": 702, "s": 562, "text": "This problem has existing solution please refer link. We can solve this problem quickly in python using List Comprehension and OrderedDict." }, { "code": "# Function to find k'th non repeating character # in string from collections import OrderedDict def kthRepeating(input,k): # OrderedDict returns a dictionary data # structure having characters of input # string as keys in the same order they # were inserted and 0 as their default value dict=OrderedDict.fromkeys(input,0) # now traverse input string to calculate # frequency of each character for ch in input: dict[ch]+=1 # now extract list of all keys whose value # is 1 from dict Ordered Dictionary nonRepeatDict = [key for (key,value) in dict.items() if value==1] # now return (k-1)th character from above list if len(nonRepeatDict) < k: return 'Less than k non-repeating characters in input.' else: return nonRepeatDict[k-1] # Driver function if __name__ == \"__main__\": input = \"geeksforgeeks\" k = 3 print (kthRepeating(input, k)) ", "e": 1659, "s": 702, "text": null }, { "code": null, "e": 1667, "s": 1659, "text": "Output:" }, { "code": null, "e": 1670, "s": 1667, "text": "r\n" }, { "code": null, "e": 1981, "s": 1670, "text": "This article is contributed by Shashank Mishra (Gullu). 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": 2106, "s": 1981, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2133, "s": 2106, "text": "Python dictionary-programs" }, { "code": null, "e": 2154, "s": 2133, "text": "Python list-programs" }, { "code": null, "e": 2166, "s": 2154, "text": "python-dict" }, { "code": null, "e": 2178, "s": 2166, "text": "python-list" }, { "code": null, "e": 2185, "s": 2178, "text": "Python" }, { "code": null, "e": 2193, "s": 2185, "text": "Strings" }, { "code": null, "e": 2205, "s": 2193, "text": "python-dict" }, { "code": null, "e": 2217, "s": 2205, "text": "python-list" }, { "code": null, "e": 2225, "s": 2217, "text": "Strings" }, { "code": null, "e": 2323, "s": 2225, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2355, "s": 2323, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2382, "s": 2355, "text": "Python Classes and Objects" }, { "code": null, "e": 2403, "s": 2382, "text": "Python OOPs Concepts" }, { "code": null, "e": 2426, "s": 2403, "text": "Introduction To PYTHON" }, { "code": null, "e": 2482, "s": 2426, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2528, "s": 2482, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 2553, "s": 2528, "text": "Reverse a string in Java" }, { "code": null, "e": 2613, "s": 2553, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 2628, "s": 2613, "text": "C++ Data Types" } ]
Oracle Certified Java Associate (OCA) Exam Preparation
12 Nov, 2018 Friends! I recently appeared for OCA exam and scored 95%. Here i am sharing few techniques and exam question patterns which must be helping you while appearing for OCA test. This exam guarantee to ask question on the below topics or we can say statements.Exam code: 1Z0-808 1. Must practice the differences between str1 == str2 and str1.equals(str2).Example-1.1: class Test { public static void main(String[] args) { String s = new String("hello"); String s2 = "hello"; if (s == s2) { System.out.println("=="); } if (s.equals(s2)) { System.out.println("equals"); } }} equals Reason: Because String class equals method compare objects, but == operator only compares references. If both the references are pointing to the same object then only == operator returns true. Example-1.2: class Test { public static void main(String[] args) { String s = new String("hello"); String s2 = s; if (s == s2) { System.out.println("=="); } if (s.equals(s2)) { System.out.println("equals"); } }} == equals Reason: Because both the references are pointing to the same object so “==” printed and If both the reference are pointing to the same object so by default they the equal so “equals” printed. 2. Study ternary operator and its compile time errors. Example-2.1: class Test { public static void main(String[] args) { int marks = 90; String result = marks > 35 ? "Pass" : "Fail"; System.out.println(result); }} Pass Example-2.2: class Test { public static void main(String[] args) { int marks = 90; String result = marks > 60 ? "Pass with 1st div." : marks < 50 ? "Pass with 2nd div." : marks < 40 ? "Pass with 3nd div."; System.out.println(result); }} OUTPUT: Compile Time ErrorReason: marks < 40 ? "Pass with 3nd div." is not completed.Correction: marks < 40 ? "Pass with 3nd div.":”Fail” . 3. Study the rule “String objects are Immutable” .Example-3.1: class Test { public static void main(String[] args) { String ta = "A "; ta = ta.concat("B "); String tb = "C "; ta = ta.concat(tb); ta.replace('C', 'D'); ta = ta.concat(tb); System.out.println(ta); }} A B C C 4. Lambda expression and its simplified forms. Java Lambda Expression Syntax:(argument-list) -> {body}4.1 Lambda Expression Example: No Parameter // This a java methodvoid printHello(){ System.out.println("Hello World ");} Or // As lambda the above method can be written as below() -> { System.out.println("Hello World "); }; Or // {} is optional for single line statement() -> System.out.println("Hello World "); 4.2 Lambda Expression Example: Single Parameter // This a java methodvoid sayHello(String name){ System.out.println("Hello " + name);} Or (name) -> { System.out.println("Hello " + name); }; Or // {} optional(name) -> System.out.println("Hello " + name); Or// () optional for single input parameter.name -> System.out.println("Hello " + name); 4.3 Lambda Expression Example:Multiple Parameter // This a java methodint add(int num1, int num2){ return num1 + num2;} Or (int num1, int num2) -> { return num1 + num2; }; Or (int num1, int num2) -> num1 + num2; Or // () mandatory for more than one input parameter.(num1, num2) -> num1 + num2; 5. Study the difference between &(Bitwise AND) and &&(Logical AND) Operator.Example-5.1: class Test { public static void main(String[] args) { int a = 10; int b = 20; if (++a <= 10 && --b < 20) {} System.out.println("Output of && operator: " + "a = " + a + " b = " + b); System.out.println("-------------"); a = 10; b = 20; if (++a <= 10 & --b < 20) {} System.out.println("Output of & operator: " + "a = " + a + " b = " + b); }} Output of && operator: a = 11 b = 20 ------------- Output of & operator: a = 11 b = 19 Reason: Because ‘&&’ operator doesn’t check second operand if value for the first operand is ‘false’. But ‘&’ must check both the operands. Note: These concept definitely covers 10 – 12 questions in OCA Exam. atishaysharma640 Java-Output java-puzzle Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Stack Class in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Nov, 2018" }, { "code": null, "e": 328, "s": 54, "text": "Friends! I recently appeared for OCA exam and scored 95%. Here i am sharing few techniques and exam question patterns which must be helping you while appearing for OCA test. This exam guarantee to ask question on the below topics or we can say statements.Exam code: 1Z0-808" }, { "code": null, "e": 417, "s": 328, "text": "1. Must practice the differences between str1 == str2 and str1.equals(str2).Example-1.1:" }, { "code": "class Test { public static void main(String[] args) { String s = new String(\"hello\"); String s2 = \"hello\"; if (s == s2) { System.out.println(\"==\"); } if (s.equals(s2)) { System.out.println(\"equals\"); } }}", "e": 699, "s": 417, "text": null }, { "code": null, "e": 707, "s": 699, "text": "equals\n" }, { "code": null, "e": 900, "s": 707, "text": "Reason: Because String class equals method compare objects, but == operator only compares references. If both the references are pointing to the same object then only == operator returns true." }, { "code": null, "e": 913, "s": 900, "text": "Example-1.2:" }, { "code": "class Test { public static void main(String[] args) { String s = new String(\"hello\"); String s2 = s; if (s == s2) { System.out.println(\"==\"); } if (s.equals(s2)) { System.out.println(\"equals\"); } }}", "e": 1189, "s": 913, "text": null }, { "code": null, "e": 1200, "s": 1189, "text": "==\nequals\n" }, { "code": null, "e": 1392, "s": 1200, "text": "Reason: Because both the references are pointing to the same object so “==” printed and If both the reference are pointing to the same object so by default they the equal so “equals” printed." }, { "code": null, "e": 1447, "s": 1392, "text": "2. Study ternary operator and its compile time errors." }, { "code": null, "e": 1460, "s": 1447, "text": "Example-2.1:" }, { "code": "class Test { public static void main(String[] args) { int marks = 90; String result = marks > 35 ? \"Pass\" : \"Fail\"; System.out.println(result); }}", "e": 1637, "s": 1460, "text": null }, { "code": null, "e": 1643, "s": 1637, "text": "Pass\n" }, { "code": null, "e": 1656, "s": 1643, "text": "Example-2.2:" }, { "code": "class Test { public static void main(String[] args) { int marks = 90; String result = marks > 60 ? \"Pass with 1st div.\" : marks < 50 ? \"Pass with 2nd div.\" : marks < 40 ? \"Pass with 3nd div.\"; System.out.println(result); }}", "e": 1959, "s": 1656, "text": null }, { "code": null, "e": 2099, "s": 1959, "text": "OUTPUT: Compile Time ErrorReason: marks < 40 ? \"Pass with 3nd div.\" is not completed.Correction: marks < 40 ? \"Pass with 3nd div.\":”Fail” ." }, { "code": null, "e": 2162, "s": 2099, "text": "3. Study the rule “String objects are Immutable” .Example-3.1:" }, { "code": "class Test { public static void main(String[] args) { String ta = \"A \"; ta = ta.concat(\"B \"); String tb = \"C \"; ta = ta.concat(tb); ta.replace('C', 'D'); ta = ta.concat(tb); System.out.println(ta); }}", "e": 2421, "s": 2162, "text": null }, { "code": null, "e": 2430, "s": 2421, "text": "A B C C\n" }, { "code": null, "e": 2477, "s": 2430, "text": "4. Lambda expression and its simplified forms." }, { "code": null, "e": 2576, "s": 2477, "text": "Java Lambda Expression Syntax:(argument-list) -> {body}4.1 Lambda Expression Example: No Parameter" }, { "code": "// This a java methodvoid printHello(){ System.out.println(\"Hello World \");} Or // As lambda the above method can be written as below() -> { System.out.println(\"Hello World \"); }; Or // {} is optional for single line statement() -> System.out.println(\"Hello World \");", "e": 2850, "s": 2576, "text": null }, { "code": null, "e": 2898, "s": 2850, "text": "4.2 Lambda Expression Example: Single Parameter" }, { "code": "// This a java methodvoid sayHello(String name){ System.out.println(\"Hello \" + name);} Or (name) -> { System.out.println(\"Hello \" + name); }; Or // {} optional(name) -> System.out.println(\"Hello \" + name); Or// () optional for single input parameter.name -> System.out.println(\"Hello \" + name); ", "e": 3202, "s": 2898, "text": null }, { "code": null, "e": 3251, "s": 3202, "text": "4.3 Lambda Expression Example:Multiple Parameter" }, { "code": "// This a java methodint add(int num1, int num2){ return num1 + num2;} Or (int num1, int num2) -> { return num1 + num2; }; Or (int num1, int num2) -> num1 + num2; Or // () mandatory for more than one input parameter.(num1, num2) -> num1 + num2;", "e": 3506, "s": 3251, "text": null }, { "code": null, "e": 3595, "s": 3506, "text": "5. Study the difference between &(Bitwise AND) and &&(Logical AND) Operator.Example-5.1:" }, { "code": "class Test { public static void main(String[] args) { int a = 10; int b = 20; if (++a <= 10 && --b < 20) {} System.out.println(\"Output of && operator: \" + \"a = \" + a + \" b = \" + b); System.out.println(\"-------------\"); a = 10; b = 20; if (++a <= 10 & --b < 20) {} System.out.println(\"Output of & operator: \" + \"a = \" + a + \" b = \" + b); }}", "e": 4066, "s": 3595, "text": null }, { "code": null, "e": 4154, "s": 4066, "text": "Output of && operator: a = 11 b = 20\n-------------\nOutput of & operator: a = 11 b = 19\n" }, { "code": null, "e": 4294, "s": 4154, "text": "Reason: Because ‘&&’ operator doesn’t check second operand if value for the first operand is ‘false’. But ‘&’ must check both the operands." }, { "code": null, "e": 4363, "s": 4294, "text": "Note: These concept definitely covers 10 – 12 questions in OCA Exam." }, { "code": null, "e": 4380, "s": 4363, "text": "atishaysharma640" }, { "code": null, "e": 4392, "s": 4380, "text": "Java-Output" }, { "code": null, "e": 4404, "s": 4392, "text": "java-puzzle" }, { "code": null, "e": 4409, "s": 4404, "text": "Java" }, { "code": null, "e": 4414, "s": 4409, "text": "Java" }, { "code": null, "e": 4512, "s": 4414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4563, "s": 4512, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4594, "s": 4563, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4613, "s": 4594, "text": "Interfaces in Java" }, { "code": null, "e": 4643, "s": 4613, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4661, "s": 4643, "text": "ArrayList in Java" }, { "code": null, "e": 4676, "s": 4661, "text": "Stream In Java" }, { "code": null, "e": 4696, "s": 4676, "text": "Collections in Java" }, { "code": null, "e": 4720, "s": 4696, "text": "Singleton Class in Java" }, { "code": null, "e": 4752, "s": 4720, "text": "Multidimensional Arrays in Java" } ]
How to use TypeScript on backend ?
04 Jul, 2021 TypeScript was developed by Microsoft to simplify the JavaScript code, making it easier to read and debug. Its type checking prevents many horrendous bugs during runtime. In this article, we will see how to set up typescript in the backend with NodeJS and express. Prerequisites Basics of NodeJS Basics of Express Basics of JavaScript Project Setup and Module Installation: Step 1: Run the following command in command prompt/bash/console to create a node project npm init -y Step 2: Adding the required dependencies using the following command. npm i express npm i typescript ts-node @types/node @types/express --save-dev npm i -D @types/express Notice the devDependency for typescript. Typescript is only required through the development process, In the end, It will be compiled to VanillaJS for runtime. Learn more about types of dependencies. Project Structure: It will look like this Step 3: Configure Typescript using the following command. npx tsc --init It will generate tsconfig.json where you can define parameters for typescript like which ECMAScript version to use (like ES3 (default), ES5, ES2015), enable strict type checking or not. Learn more about typescript configuration. Step 4: Creating an express server, here we have named it server.ts server.ts // Importing moduleimport express from 'express'; const app = express();const PORT:Number=3000; // Handling GET / Requestapp.get('/', (req, res) => { res.send('Welcome to typescript backend!');}) // Server setupapp.listen(PORT,() => { console.log('The application is listening ' + 'on port http://localhost:'+PORT);}) Step 6: Configure package.json Add the following line of code in package.json file, tsc command compiles typescript code to Vanilla JavaScript, while node server.js will take the generated Vanilla JavaScript file and start the server. "scripts": { "build": "tsc", "start": " node server.js" } Step 7: Run the server using the following command. npm run build npm start Output: Now open the http://localhost:3000 in any browser to see the server running. JavaScript-Questions Picked TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2021" }, { "code": null, "e": 317, "s": 52, "text": "TypeScript was developed by Microsoft to simplify the JavaScript code, making it easier to read and debug. Its type checking prevents many horrendous bugs during runtime. In this article, we will see how to set up typescript in the backend with NodeJS and express." }, { "code": null, "e": 331, "s": 317, "text": "Prerequisites" }, { "code": null, "e": 348, "s": 331, "text": "Basics of NodeJS" }, { "code": null, "e": 366, "s": 348, "text": "Basics of Express" }, { "code": null, "e": 387, "s": 366, "text": "Basics of JavaScript" }, { "code": null, "e": 426, "s": 387, "text": "Project Setup and Module Installation:" }, { "code": null, "e": 516, "s": 426, "text": "Step 1: Run the following command in command prompt/bash/console to create a node project" }, { "code": null, "e": 528, "s": 516, "text": "npm init -y" }, { "code": null, "e": 600, "s": 530, "text": "Step 2: Adding the required dependencies using the following command." }, { "code": null, "e": 702, "s": 600, "text": "npm i express \nnpm i typescript ts-node @types/node @types/express --save-dev\nnpm i -D @types/express" }, { "code": null, "e": 902, "s": 702, "text": "Notice the devDependency for typescript. Typescript is only required through the development process, In the end, It will be compiled to VanillaJS for runtime. Learn more about types of dependencies." }, { "code": null, "e": 944, "s": 902, "text": "Project Structure: It will look like this" }, { "code": null, "e": 1002, "s": 944, "text": "Step 3: Configure Typescript using the following command." }, { "code": null, "e": 1017, "s": 1002, "text": "npx tsc --init" }, { "code": null, "e": 1246, "s": 1017, "text": "It will generate tsconfig.json where you can define parameters for typescript like which ECMAScript version to use (like ES3 (default), ES5, ES2015), enable strict type checking or not. Learn more about typescript configuration." }, { "code": null, "e": 1314, "s": 1246, "text": "Step 4: Creating an express server, here we have named it server.ts" }, { "code": null, "e": 1324, "s": 1314, "text": "server.ts" }, { "code": "// Importing moduleimport express from 'express'; const app = express();const PORT:Number=3000; // Handling GET / Requestapp.get('/', (req, res) => { res.send('Welcome to typescript backend!');}) // Server setupapp.listen(PORT,() => { console.log('The application is listening ' + 'on port http://localhost:'+PORT);})", "e": 1660, "s": 1324, "text": null }, { "code": null, "e": 1691, "s": 1660, "text": "Step 6: Configure package.json" }, { "code": null, "e": 1895, "s": 1691, "text": "Add the following line of code in package.json file, tsc command compiles typescript code to Vanilla JavaScript, while node server.js will take the generated Vanilla JavaScript file and start the server." }, { "code": null, "e": 1955, "s": 1895, "text": "\"scripts\": {\n \"build\": \"tsc\",\n \"start\": \" node server.js\"\n}" }, { "code": null, "e": 2007, "s": 1955, "text": "Step 7: Run the server using the following command." }, { "code": null, "e": 2031, "s": 2007, "text": "npm run build\nnpm start" }, { "code": null, "e": 2116, "s": 2031, "text": "Output: Now open the http://localhost:3000 in any browser to see the server running." }, { "code": null, "e": 2137, "s": 2116, "text": "JavaScript-Questions" }, { "code": null, "e": 2144, "s": 2137, "text": "Picked" }, { "code": null, "e": 2155, "s": 2144, "text": "TypeScript" }, { "code": null, "e": 2166, "s": 2155, "text": "JavaScript" }, { "code": null, "e": 2183, "s": 2166, "text": "Web Technologies" } ]
Monkey Patching in Python (Dynamic Behavior)
04 Dec, 2020 In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time. # monk.pyclass A: def func(self): print ("func() is being called") We use above module (monk) in below code and change behavior of func() at run-time by assigning different value. import monkdef monkey_f(self): print ("monkey_f() is being called") # replacing address of "func" with "monkey_f"monk.A.func = monkey_fobj = monk.A() # calling function "func" whose address got replaced# with function "monkey_f()"obj.func() Examples: Output :monkey_f() is being called Python-Functions python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Dec, 2020" }, { "code": null, "e": 221, "s": 52, "text": "In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time." }, { "code": "# monk.pyclass A: def func(self): print (\"func() is being called\")", "e": 301, "s": 221, "text": null }, { "code": null, "e": 414, "s": 301, "text": "We use above module (monk) in below code and change behavior of func() at run-time by assigning different value." }, { "code": "import monkdef monkey_f(self): print (\"monkey_f() is being called\") # replacing address of \"func\" with \"monkey_f\"monk.A.func = monkey_fobj = monk.A() # calling function \"func\" whose address got replaced# with function \"monkey_f()\"obj.func()", "e": 662, "s": 414, "text": null }, { "code": null, "e": 672, "s": 662, "text": "Examples:" }, { "code": null, "e": 708, "s": 672, "text": "Output :monkey_f() is being called\n" }, { "code": null, "e": 725, "s": 708, "text": "Python-Functions" }, { "code": null, "e": 740, "s": 725, "text": "python-modules" }, { "code": null, "e": 747, "s": 740, "text": "Python" }, { "code": null, "e": 845, "s": 747, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 863, "s": 845, "text": "Python Dictionary" }, { "code": null, "e": 905, "s": 863, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 927, "s": 905, "text": "Enumerate() in Python" }, { "code": null, "e": 953, "s": 927, "text": "Python String | replace()" }, { "code": null, "e": 985, "s": 953, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1014, "s": 985, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1041, "s": 1014, "text": "Python Classes and Objects" }, { "code": null, "e": 1062, "s": 1041, "text": "Python OOPs Concepts" }, { "code": null, "e": 1098, "s": 1062, "text": "Convert integer to string in Python" } ]
Java - Serialization
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform. Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object. The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out − public final void writeObject(Object x) throws IOException The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object − public final Object readObject() throws IOException, ClassNotFoundException This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type. To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface − public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); } } Notice that for a class to be serialized successfully, two conditions must be met − The class must implement the java.io.Serializable interface. The class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient. If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not. The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file. When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing. Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser extension. import java.io.*; public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Reyan Ali"; e.address = "Phokka Kuan, Ambehta Peer"; e.SSN = 11122333; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in /tmp/employee.ser"); } catch (IOException i) { i.printStackTrace(); } } } The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output − import java.io.*; public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream("/tmp/employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Employee..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("SSN: " + e.SSN); System.out.println("Number: " + e.number); } } This will produce the following result − Deserialized Employee... Name: Reyan Ali Address:Phokka Kuan, Ambehta Peer SSN: 0 Number:101 Here are following important points to be noted − The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException. The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException. Notice that the return value of readObject() is cast to an Employee reference. Notice that the return value of readObject() is cast to an Employee reference. The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0. The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.
[ { "code": null, "e": 2747, "s": 2511, "text": "Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object." }, { "code": null, "e": 2974, "s": 2747, "text": "After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory." }, { "code": null, "e": 3141, "s": 2974, "text": "Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform." }, { "code": null, "e": 3283, "s": 3141, "text": "Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object." }, { "code": null, "e": 3414, "s": 3283, "text": "The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out −" }, { "code": null, "e": 3474, "s": 3414, "text": "public final void writeObject(Object x) throws IOException\n" }, { "code": null, "e": 3646, "s": 3474, "text": "The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object −" }, { "code": null, "e": 3723, "s": 3646, "text": "public final Object readObject() throws IOException, ClassNotFoundException\n" }, { "code": null, "e": 3886, "s": 3723, "text": "This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type." }, { "code": null, "e": 4108, "s": 3886, "text": "To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface −" }, { "code": null, "e": 4376, "s": 4108, "text": "public class Employee implements java.io.Serializable {\n public String name;\n public String address;\n public transient int SSN;\n public int number;\n \n public void mailCheck() {\n System.out.println(\"Mailing a check to \" + name + \" \" + address);\n }\n}" }, { "code": null, "e": 4460, "s": 4376, "text": "Notice that for a class to be serialized successfully, two conditions must be met −" }, { "code": null, "e": 4521, "s": 4460, "text": "The class must implement the java.io.Serializable interface." }, { "code": null, "e": 4582, "s": 4521, "text": "The class must implement the java.io.Serializable interface." }, { "code": null, "e": 4696, "s": 4582, "text": "All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient." }, { "code": null, "e": 4810, "s": 4696, "text": "All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient." }, { "code": null, "e": 5037, "s": 4810, "text": "If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not." }, { "code": null, "e": 5195, "s": 5037, "text": "The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file." }, { "code": null, "e": 5378, "s": 5195, "text": "When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing." }, { "code": null, "e": 5493, "s": 5378, "text": "Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser extension." }, { "code": null, "e": 6147, "s": 5493, "text": "import java.io.*;\npublic class SerializeDemo {\n\n public static void main(String [] args) {\n Employee e = new Employee();\n e.name = \"Reyan Ali\";\n e.address = \"Phokka Kuan, Ambehta Peer\";\n e.SSN = 11122333;\n e.number = 101;\n \n try {\n FileOutputStream fileOut =\n new FileOutputStream(\"/tmp/employee.ser\");\n ObjectOutputStream out = new ObjectOutputStream(fileOut);\n out.writeObject(e);\n out.close();\n fileOut.close();\n System.out.printf(\"Serialized data is saved in /tmp/employee.ser\");\n } catch (IOException i) {\n i.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 6308, "s": 6147, "text": "The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output −" }, { "code": null, "e": 7156, "s": 6308, "text": "import java.io.*;\npublic class DeserializeDemo {\n\n public static void main(String [] args) {\n Employee e = null;\n try {\n FileInputStream fileIn = new FileInputStream(\"/tmp/employee.ser\");\n ObjectInputStream in = new ObjectInputStream(fileIn);\n e = (Employee) in.readObject();\n in.close();\n fileIn.close();\n } catch (IOException i) {\n i.printStackTrace();\n return;\n } catch (ClassNotFoundException c) {\n System.out.println(\"Employee class not found\");\n c.printStackTrace();\n return;\n }\n \n System.out.println(\"Deserialized Employee...\");\n System.out.println(\"Name: \" + e.name);\n System.out.println(\"Address: \" + e.address);\n System.out.println(\"SSN: \" + e.SSN);\n System.out.println(\"Number: \" + e.number);\n }\n}" }, { "code": null, "e": 7197, "s": 7156, "text": "This will produce the following result −" }, { "code": null, "e": 7291, "s": 7197, "text": "Deserialized Employee...\nName: Reyan Ali\nAddress:Phokka Kuan, Ambehta Peer\nSSN: 0\nNumber:101\n" }, { "code": null, "e": 7341, "s": 7291, "text": "Here are following important points to be noted −" }, { "code": null, "e": 7654, "s": 7341, "text": "The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException." }, { "code": null, "e": 7967, "s": 7654, "text": "The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException." }, { "code": null, "e": 8046, "s": 7967, "text": "Notice that the return value of readObject() is cast to an Employee reference." }, { "code": null, "e": 8125, "s": 8046, "text": "Notice that the return value of readObject() is cast to an Employee reference." }, { "code": null, "e": 8335, "s": 8125, "text": "The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0." } ]
iscntrl() in C++ and its application to find control characters
18 Apr, 2019 In C++, iscntrl() is a predefined function used for string and character handling. cstring is the header file required for string functions and cctype is the header file required for character functions. A control character is one which is not a printable character i.e, it does not occupy a printing position on a display. This function is used to check if the argument contains any control characters. There are many types of control characters in C++ such as: Horizontal tab – ‘\t’ Line feed – ‘\n’ Backspace – ‘\b’ Carriage return – ‘\r’ Form feed – ‘\f’ Escape Syntax int iscntrl ( int c ); Applications Given a string, we need to find the number of control characters in the string.Algorithm1. Traverse the given string character by character up to its length, check if the character is a control character.2. If it is a control character, increment the counter by 1, else traverse to the next character.3. Print the value of the counter.Examples:Input : string='My name \n is \n Ayush' Output :2 Input :string= 'This is written above \n This is written below' Output :1 Recommended: Please try your approach on {IDE} first, before moving on to the solution.// CPP program to count control characters in a string#include <iostream>#include <cstring>#include <cctype>using namespace std; // function to calculate control charactersvoid space(string& str){ int count = 0; int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (iscntrl(c)) count++; } cout << count;} // Driver Codeint main(){ string str = "My name \n is \n Ayush"; space(str); return 0;} Output:2 Given a string, we need to print the string till a control character is found in the string.Algorithm1. Traverse the given string character by character and write the characters to the standard output using putchar().2. Break the loop when a control character is found in the string.3. Print the final string from the standard output.Examples:Input : string='My name is \n Ayush' Output :My name is Input :string= 'This is written above \n This is written below' Output :This is written above // CPP program to print a string until a control character#include <iostream>#include <cstring>#include <cctype>#include<cstdio>using namespace std; // function to print string until a control characterint space(string& str){ int i=0; while (!iscntrl(str[i])) { putchar (str[i]); i++; } return 0;} // Driver Codeint main(){ string str = "My name is \n Ayush"; space(str); return 0;}Output:My name is Given a string, we need to find the number of control characters in the string.Algorithm1. Traverse the given string character by character up to its length, check if the character is a control character.2. If it is a control character, increment the counter by 1, else traverse to the next character.3. Print the value of the counter.Examples:Input : string='My name \n is \n Ayush' Output :2 Input :string= 'This is written above \n This is written below' Output :1 Recommended: Please try your approach on {IDE} first, before moving on to the solution.// CPP program to count control characters in a string#include <iostream>#include <cstring>#include <cctype>using namespace std; // function to calculate control charactersvoid space(string& str){ int count = 0; int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (iscntrl(c)) count++; } cout << count;} // Driver Codeint main(){ string str = "My name \n is \n Ayush"; space(str); return 0;} Output:2 Algorithm1. Traverse the given string character by character up to its length, check if the character is a control character.2. If it is a control character, increment the counter by 1, else traverse to the next character.3. Print the value of the counter. Examples: Input : string='My name \n is \n Ayush' Output :2 Input :string= 'This is written above \n This is written below' Output :1 // CPP program to count control characters in a string#include <iostream>#include <cstring>#include <cctype>using namespace std; // function to calculate control charactersvoid space(string& str){ int count = 0; int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (iscntrl(c)) count++; } cout << count;} // Driver Codeint main(){ string str = "My name \n is \n Ayush"; space(str); return 0;} Output: 2 Given a string, we need to print the string till a control character is found in the string.Algorithm1. Traverse the given string character by character and write the characters to the standard output using putchar().2. Break the loop when a control character is found in the string.3. Print the final string from the standard output.Examples:Input : string='My name is \n Ayush' Output :My name is Input :string= 'This is written above \n This is written below' Output :This is written above // CPP program to print a string until a control character#include <iostream>#include <cstring>#include <cctype>#include<cstdio>using namespace std; // function to print string until a control characterint space(string& str){ int i=0; while (!iscntrl(str[i])) { putchar (str[i]); i++; } return 0;} // Driver Codeint main(){ string str = "My name is \n Ayush"; space(str); return 0;}Output:My name is Input : string='My name is \n Ayush' Output :My name is Input :string= 'This is written above \n This is written below' Output :This is written above // CPP program to print a string until a control character#include <iostream>#include <cstring>#include <cctype>#include<cstdio>using namespace std; // function to print string until a control characterint space(string& str){ int i=0; while (!iscntrl(str[i])) { putchar (str[i]); i++; } return 0;} // Driver Codeint main(){ string str = "My name is \n Ayush"; space(str); return 0;} Output: My name is This article is contributed by Ayush Saxena. 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-Library C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Priority Queue in C++ Standard Template Library (STL) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Substring in C++ Inheritance in C++ Object Oriented Programming in C++ C++ Classes and Objects Sorting a vector in C++ C++ Data Types
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Apr, 2019" }, { "code": null, "e": 352, "s": 28, "text": "In C++, iscntrl() is a predefined function used for string and character handling. cstring is the header file required for string functions and cctype is the header file required for character functions. A control character is one which is not a printable character i.e, it does not occupy a printing position on a display." }, { "code": null, "e": 491, "s": 352, "text": "This function is used to check if the argument contains any control characters. There are many types of control characters in C++ such as:" }, { "code": null, "e": 513, "s": 491, "text": "Horizontal tab – ‘\\t’" }, { "code": null, "e": 530, "s": 513, "text": "Line feed – ‘\\n’" }, { "code": null, "e": 547, "s": 530, "text": "Backspace – ‘\\b’" }, { "code": null, "e": 570, "s": 547, "text": "Carriage return – ‘\\r’" }, { "code": null, "e": 587, "s": 570, "text": "Form feed – ‘\\f’" }, { "code": null, "e": 594, "s": 587, "text": "Escape" }, { "code": null, "e": 601, "s": 594, "text": "Syntax" }, { "code": null, "e": 626, "s": 601, "text": "int iscntrl ( int c ); \n" }, { "code": null, "e": 639, "s": 626, "text": "Applications" }, { "code": null, "e": 2598, "s": 639, "text": "Given a string, we need to find the number of control characters in the string.Algorithm1. Traverse the given string character by character up to its length, check if the character is a control character.2. If it is a control character, increment the counter by 1, else traverse to the next character.3. Print the value of the counter.Examples:Input : string='My name \\n is \\n Ayush'\nOutput :2\n\nInput :string= 'This is written above \\n This is written below'\nOutput :1\nRecommended: Please try your approach on {IDE} first, before moving on to the solution.// CPP program to count control characters in a string#include <iostream>#include <cstring>#include <cctype>using namespace std; // function to calculate control charactersvoid space(string& str){ int count = 0; int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (iscntrl(c)) count++; } cout << count;} // Driver Codeint main(){ string str = \"My name \\n is \\n Ayush\"; space(str); return 0;} Output:2\nGiven a string, we need to print the string till a control character is found in the string.Algorithm1. Traverse the given string character by character and write the characters to the standard output using putchar().2. Break the loop when a control character is found in the string.3. Print the final string from the standard output.Examples:Input : string='My name is \\n Ayush'\nOutput :My name is\n\nInput :string= 'This is written above \\n This is written below'\nOutput :This is written above\n// CPP program to print a string until a control character#include <iostream>#include <cstring>#include <cctype>#include<cstdio>using namespace std; // function to print string until a control characterint space(string& str){ int i=0; while (!iscntrl(str[i])) { putchar (str[i]); i++; } return 0;} // Driver Codeint main(){ string str = \"My name is \\n Ayush\"; space(str); return 0;}Output:My name is\n" }, { "code": null, "e": 3638, "s": 2598, "text": "Given a string, we need to find the number of control characters in the string.Algorithm1. Traverse the given string character by character up to its length, check if the character is a control character.2. If it is a control character, increment the counter by 1, else traverse to the next character.3. Print the value of the counter.Examples:Input : string='My name \\n is \\n Ayush'\nOutput :2\n\nInput :string= 'This is written above \\n This is written below'\nOutput :1\nRecommended: Please try your approach on {IDE} first, before moving on to the solution.// CPP program to count control characters in a string#include <iostream>#include <cstring>#include <cctype>using namespace std; // function to calculate control charactersvoid space(string& str){ int count = 0; int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (iscntrl(c)) count++; } cout << count;} // Driver Codeint main(){ string str = \"My name \\n is \\n Ayush\"; space(str); return 0;} Output:2\n" }, { "code": null, "e": 3895, "s": 3638, "text": "Algorithm1. Traverse the given string character by character up to its length, check if the character is a control character.2. If it is a control character, increment the counter by 1, else traverse to the next character.3. Print the value of the counter." }, { "code": null, "e": 3905, "s": 3895, "text": "Examples:" }, { "code": null, "e": 4031, "s": 3905, "text": "Input : string='My name \\n is \\n Ayush'\nOutput :2\n\nInput :string= 'This is written above \\n This is written below'\nOutput :1\n" }, { "code": "// CPP program to count control characters in a string#include <iostream>#include <cstring>#include <cctype>using namespace std; // function to calculate control charactersvoid space(string& str){ int count = 0; int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (iscntrl(c)) count++; } cout << count;} // Driver Codeint main(){ string str = \"My name \\n is \\n Ayush\"; space(str); return 0;} ", "e": 4506, "s": 4031, "text": null }, { "code": null, "e": 4514, "s": 4506, "text": "Output:" }, { "code": null, "e": 4517, "s": 4514, "text": "2\n" }, { "code": null, "e": 5437, "s": 4517, "text": "Given a string, we need to print the string till a control character is found in the string.Algorithm1. Traverse the given string character by character and write the characters to the standard output using putchar().2. Break the loop when a control character is found in the string.3. Print the final string from the standard output.Examples:Input : string='My name is \\n Ayush'\nOutput :My name is\n\nInput :string= 'This is written above \\n This is written below'\nOutput :This is written above\n// CPP program to print a string until a control character#include <iostream>#include <cstring>#include <cctype>#include<cstdio>using namespace std; // function to print string until a control characterint space(string& str){ int i=0; while (!iscntrl(str[i])) { putchar (str[i]); i++; } return 0;} // Driver Codeint main(){ string str = \"My name is \\n Ayush\"; space(str); return 0;}Output:My name is\n" }, { "code": null, "e": 5589, "s": 5437, "text": "Input : string='My name is \\n Ayush'\nOutput :My name is\n\nInput :string= 'This is written above \\n This is written below'\nOutput :This is written above\n" }, { "code": "// CPP program to print a string until a control character#include <iostream>#include <cstring>#include <cctype>#include<cstdio>using namespace std; // function to print string until a control characterint space(string& str){ int i=0; while (!iscntrl(str[i])) { putchar (str[i]); i++; } return 0;} // Driver Codeint main(){ string str = \"My name is \\n Ayush\"; space(str); return 0;}", "e": 5997, "s": 5589, "text": null }, { "code": null, "e": 6005, "s": 5997, "text": "Output:" }, { "code": null, "e": 6017, "s": 6005, "text": "My name is\n" }, { "code": null, "e": 6317, "s": 6017, "text": "This article is contributed by Ayush Saxena. 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": 6442, "s": 6317, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6455, "s": 6442, "text": "Akanksha_Rai" }, { "code": null, "e": 6467, "s": 6455, "text": "CPP-Library" }, { "code": null, "e": 6471, "s": 6467, "text": "C++" }, { "code": null, "e": 6475, "s": 6471, "text": "CPP" }, { "code": null, "e": 6573, "s": 6475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6627, "s": 6573, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 6670, "s": 6627, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6704, "s": 6670, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 6729, "s": 6704, "text": "unordered_map in C++ STL" }, { "code": null, "e": 6746, "s": 6729, "text": "Substring in C++" }, { "code": null, "e": 6765, "s": 6746, "text": "Inheritance in C++" }, { "code": null, "e": 6800, "s": 6765, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 6824, "s": 6800, "text": "C++ Classes and Objects" }, { "code": null, "e": 6848, "s": 6824, "text": "Sorting a vector in C++" } ]
Python – Weibull Minimum Distribution in Statistics
10 Jan, 2020 scipy.stats.weibull_min() is a Weibull minimum continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : Weibull minimum continuous random variable Code #1 : Creating Weibull minimum continuous random variable # importing library from scipy.stats import weibull_min numargs = weibull_min .numargs a, b = 0.2, 0.8rv = weibull_min (a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9DA00E108 Code #2 : Weibull minimum continuous variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = weibull_min .rvs(a, b, size = 10) print ("Random Variates : \n", R) # PDF x = np.linspace(weibull_min.ppf(0.01, a, b), weibull_min.ppf(0.99, a, b), 10)R = weibull_min.pdf(x, 1, 3)print ("\nProbability Distribution : \n", R) Output : Random Variates : [12.76832063 0.80471316 0.80000281 0.80001071 0.80000427 2.1282417 1.9774416 27.87159473 0.80431529 0.80000885] Probability Distribution : [0.00000000e+000 1.01939341e-099 1.15142533e-199 1.30055804e-299 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) Output : Distribution : [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735 1.95918367 2. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = weibull_min.pdf(x, a, b) y2 = weibull_min.pdf(x, a, b) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2020" }, { "code": null, "e": 271, "s": 28, "text": "scipy.stats.weibull_min() is a Weibull minimum continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution." }, { "code": null, "e": 284, "s": 271, "text": "Parameters :" }, { "code": null, "e": 630, "s": 284, "text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 683, "s": 630, "text": "Results : Weibull minimum continuous random variable" }, { "code": null, "e": 745, "s": 683, "text": "Code #1 : Creating Weibull minimum continuous random variable" }, { "code": "# importing library from scipy.stats import weibull_min numargs = weibull_min .numargs a, b = 0.2, 0.8rv = weibull_min (a, b) print (\"RV : \\n\", rv) ", "e": 904, "s": 745, "text": null }, { "code": null, "e": 913, "s": 904, "text": "Output :" }, { "code": null, "e": 994, "s": 913, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9DA00E108\n" }, { "code": null, "e": 1069, "s": 994, "text": "Code #2 : Weibull minimum continuous variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = weibull_min .rvs(a, b, size = 10) print (\"Random Variates : \\n\", R) # PDF x = np.linspace(weibull_min.ppf(0.01, a, b), weibull_min.ppf(0.99, a, b), 10)R = weibull_min.pdf(x, 1, 3)print (\"\\nProbability Distribution : \\n\", R) ", "e": 1390, "s": 1069, "text": null }, { "code": null, "e": 1399, "s": 1390, "text": "Output :" }, { "code": null, "e": 1736, "s": 1399, "text": "Random Variates : \n [12.76832063 0.80471316 0.80000281 0.80001071 0.80000427 2.1282417\n 1.9774416 27.87159473 0.80431529 0.80000885]\n\nProbability Distribution : \n [0.00000000e+000 1.01939341e-099 1.15142533e-199 1.30055804e-299\n 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000\n 0.00000000e+000 0.00000000e+000]\n" }, { "code": null, "e": 1772, "s": 1736, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) ", "e": 1983, "s": 1772, "text": null }, { "code": null, "e": 1992, "s": 1983, "text": "Output :" }, { "code": null, "e": 2572, "s": 1992, "text": "Distribution : \n [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163\n 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959\n 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755\n 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551\n 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347\n 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143\n 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939\n 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735\n 1.95918367 2. ]\n " }, { "code": null, "e": 2611, "s": 2572, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = weibull_min.pdf(x, a, b) y2 = weibull_min.pdf(x, a, b) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 2823, "s": 2611, "text": null }, { "code": null, "e": 2832, "s": 2823, "text": "Output :" }, { "code": null, "e": 2861, "s": 2832, "text": "Python scipy-stats-functions" }, { "code": null, "e": 2868, "s": 2861, "text": "Python" }, { "code": null, "e": 2966, "s": 2868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2984, "s": 2966, "text": "Python Dictionary" }, { "code": null, "e": 3026, "s": 2984, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3048, "s": 3026, "text": "Enumerate() in Python" }, { "code": null, "e": 3083, "s": 3048, "text": "Read a file line by line in Python" }, { "code": null, "e": 3109, "s": 3083, "text": "Python String | replace()" }, { "code": null, "e": 3141, "s": 3109, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3170, "s": 3141, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3197, "s": 3170, "text": "Python Classes and Objects" }, { "code": null, "e": 3227, "s": 3197, "text": "Iterate over a list in Python" } ]
Python – API.home_timeline() in Tweepy
08 Jun, 2020 Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication. The home_timeline() method of the API class in Tweepy module is used to get the 20 most recent statuses, including retweets, posted by the authenticating user and that user’s friends. This is the equivalent of /timeline/home on the Web. Syntax : API.home_timeline(parameters) Parameters : since_ids : Fetch only the statuses newer than the specified ID. max_ids : Fetch only the statuses older than or equal to the specified ID. count : The number of statuses to be fetched, the default value is 20. Returns : a list of objects of the class Status Example 1 :Using the home_timeline() method without any parameters. # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # fetching the statusesstatuses = api.home_timeline() # printing the screen names of each statusfor status in statuses: print(status.user.screen_name) Output : republic AapGhumaKeLeLo_ vijaita ABPNews 1911_1913_BakUp BBCPolitics SwarajyaMag WIONews YourAnonNews thehill AP TimesNow krystalball People4Bernie Holbornlolz RealSaavedra BenjaminPDixon BJP4Haryana BuzzFeed MixedRaita Example 2: Using the home_timeline() method with the count parameter to fetch only a specified number of statuses. # number of statuses to be fetchedcount = 5 # fetching the statusesstatuses = api.home_timeline(count = count) # printing the screen names of each statusfor status in statuses: print(status.user.screen_name) Output : ANI alexkotch chrislongview CNN CGTNOfficial Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2020" }, { "code": null, "e": 428, "s": 28, "text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication." }, { "code": null, "e": 665, "s": 428, "text": "The home_timeline() method of the API class in Tweepy module is used to get the 20 most recent statuses, including retweets, posted by the authenticating user and that user’s friends. This is the equivalent of /timeline/home on the Web." }, { "code": null, "e": 704, "s": 665, "text": "Syntax : API.home_timeline(parameters)" }, { "code": null, "e": 717, "s": 704, "text": "Parameters :" }, { "code": null, "e": 782, "s": 717, "text": "since_ids : Fetch only the statuses newer than the specified ID." }, { "code": null, "e": 857, "s": 782, "text": "max_ids : Fetch only the statuses older than or equal to the specified ID." }, { "code": null, "e": 928, "s": 857, "text": "count : The number of statuses to be fetched, the default value is 20." }, { "code": null, "e": 976, "s": 928, "text": "Returns : a list of objects of the class Status" }, { "code": null, "e": 1044, "s": 976, "text": "Example 1 :Using the home_timeline() method without any parameters." }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # fetching the statusesstatuses = api.home_timeline() # printing the screen names of each statusfor status in statuses: print(status.user.screen_name)", "e": 1606, "s": 1044, "text": null }, { "code": null, "e": 1615, "s": 1606, "text": "Output :" }, { "code": null, "e": 1836, "s": 1615, "text": "republic\nAapGhumaKeLeLo_\nvijaita\nABPNews\n1911_1913_BakUp\nBBCPolitics\nSwarajyaMag\nWIONews\nYourAnonNews\nthehill\nAP\nTimesNow\nkrystalball\nPeople4Bernie\nHolbornlolz\nRealSaavedra\nBenjaminPDixon\nBJP4Haryana\nBuzzFeed\nMixedRaita\n" }, { "code": null, "e": 1951, "s": 1836, "text": "Example 2: Using the home_timeline() method with the count parameter to fetch only a specified number of statuses." }, { "code": "# number of statuses to be fetchedcount = 5 # fetching the statusesstatuses = api.home_timeline(count = count) # printing the screen names of each statusfor status in statuses: print(status.user.screen_name)", "e": 2164, "s": 1951, "text": null }, { "code": null, "e": 2173, "s": 2164, "text": "Output :" }, { "code": null, "e": 2219, "s": 2173, "text": "ANI\nalexkotch\nchrislongview\nCNN\nCGTNOfficial\n" }, { "code": null, "e": 2233, "s": 2219, "text": "Python-Tweepy" }, { "code": null, "e": 2240, "s": 2233, "text": "Python" }, { "code": null, "e": 2338, "s": 2240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2356, "s": 2338, "text": "Python Dictionary" }, { "code": null, "e": 2398, "s": 2356, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2420, "s": 2398, "text": "Enumerate() in Python" }, { "code": null, "e": 2446, "s": 2420, "text": "Python String | replace()" }, { "code": null, "e": 2478, "s": 2446, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2507, "s": 2478, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2534, "s": 2507, "text": "Python Classes and Objects" }, { "code": null, "e": 2555, "s": 2534, "text": "Python OOPs Concepts" }, { "code": null, "e": 2591, "s": 2555, "text": "Convert integer to string in Python" } ]
Getting Familiar With BioJulia: BioInformatics for Julia | by Emmett Boudreau | Towards Data Science
Julia is a great programming language that is typically associated with its strong statistical analysis and machine-learning capabilities. However, many people might know that Julia actually has a fairly mature and established group of packages for other applied sciences. Some notable examples include Yao.jl for quantum simulations, JuliaAstro.jl for astronomy (I really want to check this one out, as well) quantitative economics with QuantEcon.jl, and even quantum physics with QuantumBFS.jl and QuantumOptics.jl. With this rich ecosystem for scientific computing with Julia, it’s easy to see why many scientists are Julians either by hobby or work. This package ecosystem has piqued my interest, so I have decided to dive in to one of them with all of the free time I have had lately due to the virus. It is a great time to do something productive like learn a new applied science with my favorite programming language, after-all; as I see that as being rather productive. Also maybe this is the most optimal of times to learn more about biology and genome sequencing. To be clear, I do not have any domain knowledge in the field of Bioinformatics, but I am seeking to get a foothold in it that I can improve over time with practice and research. I am also interested to see how I might be able to apply machine learning and statistics to Biology with Julia, and cross two applied sciences that I am very interested in. In order to use BioJulia’s packages, we of course will need to add them. For my selection, I pretty much went to BioJulia’s Github and picked some repositories that sounded interesting. What I didn’t realize in my approach is that BioJulia actually has its own package registry. Rather than adding the packages individually through the Pkg REPL and Github, I decided that the registry is certainly the way to go. From the Pkg REPL, we can add the BioJulia registry with this command: registry add https://github.com/BioJulia/BioJuliaRegistry.git Then I was able to add my packages exactly how I normally would. These are the packages that piqued my interest: BioSequences.jl GenomeGraphs.jl BioSymbols.jl However, this experience ended up being a little less like me adding packages I know nothing about, and a little more like a kid in a candy shop... I also decided to pick up XAM.jl and BigBed.jl. We will also need BioCore.jl, and I went ahead and picked up BioGenerics.jl (not sure if I needed it or not.) By the end of it, I had a pretty large group of Github pages opened up. Fortunately, I have the experimental tab-grouping enabled on my Google Chrome. I love that feature. pkg> add BioCorepkg> add BioSymbolspkg> add GenomeGraphspkg> add BioGenericspkg> add BigBedpkg> add BioSequencespkg> add XAM Surprisingly, my list of packages still doesn’t look too bad! Of course, for now I’m going to just be performing more research than a human being should be capable of, and picking one of the several packages I just added... But I’m all in! I stumbled across this video, if you desire to check it out: It was really helpful in getting a good idea of where I could start learning in order to have a solid knowledge-base approaching these packages. I actually didn’t realize initially how much my machine-learning, programming, and statistics domain knowledge were going to be applying here, and I was very delighted to know that her first checkbox was entirely filled for me. To summarize she says are the five things to do when getting started with BioInformatics: Apt abilities in a statistical programming language. (Python, R, Julia) ✔ Be familiar with Bash. ✔ Be able to read data into your programming language of choice. ✔ Be able to perform basic statistical tests (e.g. T-test, chi2 test, F-test) ✔ Find some interesting data and read it into your choice of programming language. Visualize the data with a plotting library. Here is the website she suggested for obtaining data: genome.ucsc.edu The importance of understanding the data collected was stressed. She also suggested machine-learning — I am a happy young man on this day. I don’t think I realized how much BioInformatics and machine-learning go together. (I kind of already did this, I like safaris) Find the industry standard tools associated with what you want to do prior to doing it. Once you get more experience, branch out and even try creating your own tools. So after watching this quick introduction, I decided my next best move would be to start my first project. For my first BioInformatics project, I decided to browse that UCSC site mentioned earlier for data. Not only does the site have a lot of data, but also a lot of great ways to view said data! Today I will just be getting the data read in, but in the future I will be exploring it, visualizing and testing with it, and maybe I can even find some machine-learning uses for it that are practical. I was able to wget some Pangolin data I thought looked cool off of this website. To do so was a little strange, as you’re brought to an html page with no styling with 30 minutes of talking about how to get a file with wget... It was certainly weird, and made finding the ftp:// or http:// link really difficult. Here is the one that I ended up using: wget --timestamping 'ftp://hgdownload.cse.ucsc.edu/goldenPath/manPen1/bigZips/*' Funny story, my 512GB NVME drive is very low on storage because I am a data-hoarder, so I was pretty scared that I might top off the rest of my SSD with this data and need to go around cleaning. You know what I really need? NAS. Here are the files I collected from the repository with wget: Now I’m going to create a notebook server in this directory. cd ~/Projects/bioprojectjupyter-notebook This is an overwhelming amount of data, so the first one that I decided to go about trying to get into Julia is manPen1.2bit. This is because while I don’t know exactly how to read this data into Julia, I know I have a package that can do so. There is a 2bit reader inside of BioSequences.jl, and you can find the documentation here: biojulia.net BioSequences.jl has a type stored in a sub-module called TwoBit. However, I ran into an issue when I tried to import it... “ TwoBit is not defined” With this in mind, I decided to check what version of BioSequences.jl I had: On the left-hand side of that documentation page, I changed the version to the proper version that is actually on my computer, then searched for TwoBit. This revealed that the package was no longer a sub-module, but has become its own package, so I’ll have to add it: pkg> add TwoBit Now we can import it into Julia and create our reader: using TwoBitreader = TwoBit.Reader(open("manPen1.2bit", "r")) Now we can view the genome sequences we just read in using the seqnames() method on our reader: sequences = TwoBit.seqnames(reader) And now we have BioData! That was rather fun! I am incredibly excited to see all of the genomics I will be able to experiment with in Julia. Though I certainly have a long way to go, I think that some practice and reiteration will get me to the point where I can start machine-learning with nucleotides and DNA. Though this is certainly not my domain of knowledge or area of skill, I really think I am going to enjoy genomics as I am rather fond of biology to begin with. My next step is to try visualizing the data and drawing conclusions from it. Going into this I really didn’t realize how similar this was going to be to what I do every day. I am thankful that it is, and also incredibly excited to learn more. I ordered some books on Amazon that might help me to learn some of this overwhelming amount of information, but for now, I would just like to get familiar with the tools and data formats associated with genomics.
[ { "code": null, "e": 826, "s": 172, "text": "Julia is a great programming language that is typically associated with its strong statistical analysis and machine-learning capabilities. However, many people might know that Julia actually has a fairly mature and established group of packages for other applied sciences. Some notable examples include Yao.jl for quantum simulations, JuliaAstro.jl for astronomy (I really want to check this one out, as well) quantitative economics with QuantEcon.jl, and even quantum physics with QuantumBFS.jl and QuantumOptics.jl. With this rich ecosystem for scientific computing with Julia, it’s easy to see why many scientists are Julians either by hobby or work." }, { "code": null, "e": 1597, "s": 826, "text": "This package ecosystem has piqued my interest, so I have decided to dive in to one of them with all of the free time I have had lately due to the virus. It is a great time to do something productive like learn a new applied science with my favorite programming language, after-all; as I see that as being rather productive. Also maybe this is the most optimal of times to learn more about biology and genome sequencing. To be clear, I do not have any domain knowledge in the field of Bioinformatics, but I am seeking to get a foothold in it that I can improve over time with practice and research. I am also interested to see how I might be able to apply machine learning and statistics to Biology with Julia, and cross two applied sciences that I am very interested in." }, { "code": null, "e": 2081, "s": 1597, "text": "In order to use BioJulia’s packages, we of course will need to add them. For my selection, I pretty much went to BioJulia’s Github and picked some repositories that sounded interesting. What I didn’t realize in my approach is that BioJulia actually has its own package registry. Rather than adding the packages individually through the Pkg REPL and Github, I decided that the registry is certainly the way to go. From the Pkg REPL, we can add the BioJulia registry with this command:" }, { "code": null, "e": 2143, "s": 2081, "text": "registry add https://github.com/BioJulia/BioJuliaRegistry.git" }, { "code": null, "e": 2256, "s": 2143, "text": "Then I was able to add my packages exactly how I normally would. These are the packages that piqued my interest:" }, { "code": null, "e": 2272, "s": 2256, "text": "BioSequences.jl" }, { "code": null, "e": 2288, "s": 2272, "text": "GenomeGraphs.jl" }, { "code": null, "e": 2302, "s": 2288, "text": "BioSymbols.jl" }, { "code": null, "e": 2759, "s": 2302, "text": "However, this experience ended up being a little less like me adding packages I know nothing about, and a little more like a kid in a candy shop... I also decided to pick up XAM.jl and BigBed.jl. We will also need BioCore.jl, and I went ahead and picked up BioGenerics.jl (not sure if I needed it or not.) By the end of it, I had a pretty large group of Github pages opened up. Fortunately, I have the experimental tab-grouping enabled on my Google Chrome." }, { "code": null, "e": 2780, "s": 2759, "text": "I love that feature." }, { "code": null, "e": 2905, "s": 2780, "text": "pkg> add BioCorepkg> add BioSymbolspkg> add GenomeGraphspkg> add BioGenericspkg> add BigBedpkg> add BioSequencespkg> add XAM" }, { "code": null, "e": 2967, "s": 2905, "text": "Surprisingly, my list of packages still doesn’t look too bad!" }, { "code": null, "e": 3129, "s": 2967, "text": "Of course, for now I’m going to just be performing more research than a human being should be capable of, and picking one of the several packages I just added..." }, { "code": null, "e": 3145, "s": 3129, "text": "But I’m all in!" }, { "code": null, "e": 3206, "s": 3145, "text": "I stumbled across this video, if you desire to check it out:" }, { "code": null, "e": 3669, "s": 3206, "text": "It was really helpful in getting a good idea of where I could start learning in order to have a solid knowledge-base approaching these packages. I actually didn’t realize initially how much my machine-learning, programming, and statistics domain knowledge were going to be applying here, and I was very delighted to know that her first checkbox was entirely filled for me. To summarize she says are the five things to do when getting started with BioInformatics:" }, { "code": null, "e": 3743, "s": 3669, "text": "Apt abilities in a statistical programming language. (Python, R, Julia) ✔" }, { "code": null, "e": 3768, "s": 3743, "text": "Be familiar with Bash. ✔" }, { "code": null, "e": 3833, "s": 3768, "text": "Be able to read data into your programming language of choice. ✔" }, { "code": null, "e": 3911, "s": 3833, "text": "Be able to perform basic statistical tests (e.g. T-test, chi2 test, F-test) ✔" }, { "code": null, "e": 3992, "s": 3911, "text": "Find some interesting data and read it into your choice of programming language." }, { "code": null, "e": 4036, "s": 3992, "text": "Visualize the data with a plotting library." }, { "code": null, "e": 4090, "s": 4036, "text": "Here is the website she suggested for obtaining data:" }, { "code": null, "e": 4106, "s": 4090, "text": "genome.ucsc.edu" }, { "code": null, "e": 4171, "s": 4106, "text": "The importance of understanding the data collected was stressed." }, { "code": null, "e": 4328, "s": 4171, "text": "She also suggested machine-learning — I am a happy young man on this day. I don’t think I realized how much BioInformatics and machine-learning go together." }, { "code": null, "e": 4373, "s": 4328, "text": "(I kind of already did this, I like safaris)" }, { "code": null, "e": 4461, "s": 4373, "text": "Find the industry standard tools associated with what you want to do prior to doing it." }, { "code": null, "e": 4540, "s": 4461, "text": "Once you get more experience, branch out and even try creating your own tools." }, { "code": null, "e": 4647, "s": 4540, "text": "So after watching this quick introduction, I decided my next best move would be to start my first project." }, { "code": null, "e": 5040, "s": 4647, "text": "For my first BioInformatics project, I decided to browse that UCSC site mentioned earlier for data. Not only does the site have a lot of data, but also a lot of great ways to view said data! Today I will just be getting the data read in, but in the future I will be exploring it, visualizing and testing with it, and maybe I can even find some machine-learning uses for it that are practical." }, { "code": null, "e": 5391, "s": 5040, "text": "I was able to wget some Pangolin data I thought looked cool off of this website. To do so was a little strange, as you’re brought to an html page with no styling with 30 minutes of talking about how to get a file with wget... It was certainly weird, and made finding the ftp:// or http:// link really difficult. Here is the one that I ended up using:" }, { "code": null, "e": 5480, "s": 5391, "text": "wget --timestamping 'ftp://hgdownload.cse.ucsc.edu/goldenPath/manPen1/bigZips/*'" }, { "code": null, "e": 5704, "s": 5480, "text": "Funny story, my 512GB NVME drive is very low on storage because I am a data-hoarder, so I was pretty scared that I might top off the rest of my SSD with this data and need to go around cleaning. You know what I really need?" }, { "code": null, "e": 5709, "s": 5704, "text": "NAS." }, { "code": null, "e": 5771, "s": 5709, "text": "Here are the files I collected from the repository with wget:" }, { "code": null, "e": 5832, "s": 5771, "text": "Now I’m going to create a notebook server in this directory." }, { "code": null, "e": 5873, "s": 5832, "text": "cd ~/Projects/bioprojectjupyter-notebook" }, { "code": null, "e": 6207, "s": 5873, "text": "This is an overwhelming amount of data, so the first one that I decided to go about trying to get into Julia is manPen1.2bit. This is because while I don’t know exactly how to read this data into Julia, I know I have a package that can do so. There is a 2bit reader inside of BioSequences.jl, and you can find the documentation here:" }, { "code": null, "e": 6220, "s": 6207, "text": "biojulia.net" }, { "code": null, "e": 6343, "s": 6220, "text": "BioSequences.jl has a type stored in a sub-module called TwoBit. However, I ran into an issue when I tried to import it..." }, { "code": null, "e": 6368, "s": 6343, "text": "“ TwoBit is not defined”" }, { "code": null, "e": 6445, "s": 6368, "text": "With this in mind, I decided to check what version of BioSequences.jl I had:" }, { "code": null, "e": 6713, "s": 6445, "text": "On the left-hand side of that documentation page, I changed the version to the proper version that is actually on my computer, then searched for TwoBit. This revealed that the package was no longer a sub-module, but has become its own package, so I’ll have to add it:" }, { "code": null, "e": 6729, "s": 6713, "text": "pkg> add TwoBit" }, { "code": null, "e": 6784, "s": 6729, "text": "Now we can import it into Julia and create our reader:" }, { "code": null, "e": 6846, "s": 6784, "text": "using TwoBitreader = TwoBit.Reader(open(\"manPen1.2bit\", \"r\"))" }, { "code": null, "e": 6942, "s": 6846, "text": "Now we can view the genome sequences we just read in using the seqnames() method on our reader:" }, { "code": null, "e": 6978, "s": 6942, "text": "sequences = TwoBit.seqnames(reader)" }, { "code": null, "e": 7003, "s": 6978, "text": "And now we have BioData!" }, { "code": null, "e": 7450, "s": 7003, "text": "That was rather fun! I am incredibly excited to see all of the genomics I will be able to experiment with in Julia. Though I certainly have a long way to go, I think that some practice and reiteration will get me to the point where I can start machine-learning with nucleotides and DNA. Though this is certainly not my domain of knowledge or area of skill, I really think I am going to enjoy genomics as I am rather fond of biology to begin with." } ]
HTML - <menuitem> tag
The HTML <menuitem> tag is used for defining a menu item for a menu. <!Doctype html> <html> <head> <title>HTML menuitem Tag</title> </head> <body> <div style = "border:1px solid #000; padding:20px;" contextmenu = "clickmenu"> <p>Right click inside here....</p> <menu type = "context" id = "clickmenu"> <menuitem label = "Tutorialspoint" onclick = ""></menuitem> </menu> </div> </body> </html> This will produce the following result in Firefox browser only − Right click inside here.... This tag supports all the global attributes described in − HTML Attribute Reference The HTML <menuitem> tag also supports the following additional attributes − checkbox command radio This tag supports all the event attributes described in − HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2443, "s": 2374, "text": "The HTML <menuitem> tag is used for defining a menu item for a menu." }, { "code": null, "e": 2852, "s": 2443, "text": "<!Doctype html>\n<html>\n\n <head>\n <title>HTML menuitem Tag</title>\n </head>\n\n <body>\n\n <div style = \"border:1px solid #000; padding:20px;\" contextmenu = \"clickmenu\">\n <p>Right click inside here....</p>\n\n <menu type = \"context\" id = \"clickmenu\">\n <menuitem label = \"Tutorialspoint\" onclick = \"\"></menuitem>\n </menu>\n \n </div>\n </body>\n\n</html>" }, { "code": null, "e": 2917, "s": 2852, "text": "This will produce the following result in Firefox browser only −" }, { "code": null, "e": 2946, "s": 2917, "text": "Right click inside here...." }, { "code": null, "e": 3030, "s": 2946, "text": "This tag supports all the global attributes described in − HTML Attribute Reference" }, { "code": null, "e": 3107, "s": 3030, "text": "The HTML <menuitem> tag also supports the following additional attributes −" }, { "code": null, "e": 3116, "s": 3107, "text": "checkbox" }, { "code": null, "e": 3124, "s": 3116, "text": "command" }, { "code": null, "e": 3130, "s": 3124, "text": "radio" }, { "code": null, "e": 3210, "s": 3130, "text": "This tag supports all the event attributes described in − HTML Events Reference" }, { "code": null, "e": 3243, "s": 3210, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3257, "s": 3243, "text": " Anadi Sharma" }, { "code": null, "e": 3292, "s": 3257, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3306, "s": 3292, "text": " Anadi Sharma" }, { "code": null, "e": 3341, "s": 3306, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3358, "s": 3341, "text": " Frahaan Hussain" }, { "code": null, "e": 3393, "s": 3358, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3424, "s": 3393, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3457, "s": 3424, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3488, "s": 3457, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3523, "s": 3488, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3554, "s": 3523, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3561, "s": 3554, "text": " Print" }, { "code": null, "e": 3572, "s": 3561, "text": " Add Notes" } ]
Add custom borders to matrix in Python - GeeksforGeeks
05 Apr, 2021 Given a Matrix, the task is to write a python program to print each row having custom borders. Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord = "|" Output : | 4 5 6 | | 1 4 5 | | 6 9 1 | | 0 3 1 | Explanation : Matrix is ended using | border as required. Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord = "!" Output : ! 4 5 6 ! ! 1 4 5 ! ! 6 9 1 ! ! 0 3 1 ! Explanation : Matrix is ended using ! border as required. Method #1 : Using loop In this, we perform task of printing the row elements using inner loop, separated by space. The main step of adding custom borders is concatenated using + operator. Python3 # Python3 code to demonstrate working of# Custom Matrix Borders# Using loop # initializing listtest_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]] # printing original listprint("The original list is : " + str(test_list)) # initializing borderbord = "|" for sub in test_list: temp = bord + " " # inner row for ele in sub: temp = temp + str(ele) + " " # adding border temp = temp + bord print(temp) Output: The original list is : [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]] | 4 5 6 | | 1 4 5 | | 6 9 1 | | 0 3 1 | Method #2 : Using * operator + loop In this, the task of joining inner characters is performed using * operator. Python3 # Python3 code to demonstrate working of# Custom Matrix Borders# Using * operator + loop # initializing listtest_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]] # printing original listprint("The original list is : " + str(test_list)) # initializing borderbord = "|" for sub in test_list: # * operator performs task of joining print(bord, *sub, bord) Output: The original list is : [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]] | 4 5 6 | | 1 4 5 | | 6 9 1 | | 0 3 1 | Python list-programs Python Python Programs 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() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not Python | Convert a list to dictionary
[ { "code": null, "e": 23901, "s": 23873, "text": "\n05 Apr, 2021" }, { "code": null, "e": 23996, "s": 23901, "text": "Given a Matrix, the task is to write a python program to print each row having custom borders." }, { "code": null, "e": 24419, "s": 23996, "text": "Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord = \"|\"\nOutput : | 4 5 6 |\n | 1 4 5 |\n | 6 9 1 |\n | 0 3 1 |\nExplanation : Matrix is ended using | border as required.\n\nInput : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord = \"!\"\nOutput : ! 4 5 6 !\n ! 1 4 5 !\n ! 6 9 1 !\n ! 0 3 1 !\nExplanation : Matrix is ended using ! border as required." }, { "code": null, "e": 24442, "s": 24419, "text": "Method #1 : Using loop" }, { "code": null, "e": 24607, "s": 24442, "text": "In this, we perform task of printing the row elements using inner loop, separated by space. The main step of adding custom borders is concatenated using + operator." }, { "code": null, "e": 24615, "s": 24607, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Custom Matrix Borders# Using loop # initializing listtest_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing borderbord = \"|\" for sub in test_list: temp = bord + \" \" # inner row for ele in sub: temp = temp + str(ele) + \" \" # adding border temp = temp + bord print(temp)", "e": 25063, "s": 24615, "text": null }, { "code": null, "e": 25071, "s": 25063, "text": "Output:" }, { "code": null, "e": 25179, "s": 25071, "text": "The original list is : [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]]\n| 4 5 6 |\n| 1 4 5 |\n| 6 9 1 |\n| 0 3 1 |" }, { "code": null, "e": 25215, "s": 25179, "text": "Method #2 : Using * operator + loop" }, { "code": null, "e": 25293, "s": 25215, "text": "In this, the task of joining inner characters is performed using * operator. " }, { "code": null, "e": 25301, "s": 25293, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Custom Matrix Borders# Using * operator + loop # initializing listtest_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing borderbord = \"|\" for sub in test_list: # * operator performs task of joining print(bord, *sub, bord)", "e": 25681, "s": 25301, "text": null }, { "code": null, "e": 25689, "s": 25681, "text": "Output:" }, { "code": null, "e": 25797, "s": 25689, "text": "The original list is : [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3, 1]]\n| 4 5 6 |\n| 1 4 5 |\n| 6 9 1 |\n| 0 3 1 |" }, { "code": null, "e": 25818, "s": 25797, "text": "Python list-programs" }, { "code": null, "e": 25825, "s": 25818, "text": "Python" }, { "code": null, "e": 25841, "s": 25825, "text": "Python Programs" }, { "code": null, "e": 25939, "s": 25841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25948, "s": 25939, "text": "Comments" }, { "code": null, "e": 25961, "s": 25948, "text": "Old Comments" }, { "code": null, "e": 25993, "s": 25961, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26049, "s": 25993, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26091, "s": 26049, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26133, "s": 26091, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26169, "s": 26133, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26191, "s": 26169, "text": "Defaultdict in Python" }, { "code": null, "e": 26230, "s": 26191, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26276, "s": 26230, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26333, "s": 26276, "text": "Python program to check whether a number is Prime or not" } ]
Last index of One | Practice | GeeksforGeeks
Given a string S consisting only '0's and '1's, find the last index of the '1' present in it. Example 1: Input: S = 00001 Output: 4 Explanation: Last index of 1 in given string is 4. Example 2: Input: 0 Output: -1 Explanation: Since, 1 is not present, so output is -1. Your Task: You don't need to read input or print anything. Your task is to complete the function lastIndex() which takes the string S as inputs and returns the last index of '1'. If '1' is not present, return "-1" (without quotes). Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 <= |S| <= 106 S = {0,1} 0 akashmarkad22101 day ago JAVA Solution public int lastIndex( String s) { for(int i=s.length()-1;i>=0;i--) { if(s.charAt(i)== '1') { return i; } } return -1; } 0 harshscode4 days ago for(int i=s.length()-1;i>=0;i--) if(s[i]=='1') return i; return -1; 0 sumitk074 days ago char c[s.length()]; for(int i = 0;i<sizeof(c);i++){ c[i] = s[i]; } for(int i = s.length()-1;i>=0;i--){ if(c[i] == '1') return i; } return -1; 0 ninthale6 days ago int lastIndex(string s) { for(int i=s.length()-1;i>=0;i--) { if(s[i]=='1') { return i; } } return -1; }}; 0 swapniltayal4223 weeks ago class Solution: def lastIndex(self, s): # code here for i in range(len(s)-1, -1, -1): if s[i] == "1": return i; return -1 0 divakar16693 weeks ago // JAVA SOLUTION O(1)class Solution { public int lastIndex( String s) { if( s.contains("1") ) { int x=s.lastIndexOf("1"); return x; } else { return -1; } }} 0 atif836141 month ago JAVA SOLUTION : class Solution { public int lastIndex( String s) { if (s.length() == 0) { return -1; } int res = 0; int flag = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '1') { res = i; flag = 1; } } if (flag == 1) { return res; } return -1; } } 0 coderh1 month ago class Solution: def lastIndex(self, s): c=len(s)-1 for i in range(len(s)-1,-1,-1): if s[i]=="1": return c c-=1 return -1 0 adityagagtiwari1 month ago This is a basic trivial solution. Using a boolean marker. class Solution { public int lastIndex( String s) { int idx = 0; if(s.length()==1 && s.charAt(0)=='1') return 0; boolean visited = false; for(int i=0;i<s.length();i++) { char ch = s.charAt(i); if(ch=='1') { visited = true; idx = i; } } if(idx>=0 && visited) { return idx; } else { return -1; } }} 0 kashyapabhishek221 month ago def lastIndex(self, s): # code here if '1' not in s: return -1 s = s[::-1] res = len(s)-s.index('1') -1 return res We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 334, "s": 238, "text": "Given a string S consisting only '0's and '1's, find the last index of the '1' present in it. " }, { "code": null, "e": 347, "s": 336, "text": "Example 1:" }, { "code": null, "e": 427, "s": 347, "text": "Input:\nS = 00001\nOutput:\n4\nExplanation:\nLast index of 1 in given string is 4.\n" }, { "code": null, "e": 440, "s": 429, "text": "Example 2:" }, { "code": null, "e": 515, "s": 440, "text": "Input:\n0\nOutput:\n-1\nExplanation:\nSince, 1 is not present, so output is -1." }, { "code": null, "e": 752, "s": 517, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function lastIndex() which takes the string S as inputs and returns the last index of '1'. If '1' is not present, return \"-1\" (without quotes)." }, { "code": null, "e": 816, "s": 754, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 858, "s": 818, "text": "Constraints: \n1 <= |S| <= 106\nS = {0,1}" }, { "code": null, "e": 869, "s": 867, "text": "0" }, { "code": null, "e": 894, "s": 869, "text": "akashmarkad22101 day ago" }, { "code": null, "e": 908, "s": 894, "text": "JAVA Solution" }, { "code": null, "e": 1126, "s": 910, "text": "public int lastIndex( String s) { for(int i=s.length()-1;i>=0;i--) { if(s.charAt(i)== '1') { return i; } } return -1; }" }, { "code": null, "e": 1128, "s": 1126, "text": "0" }, { "code": null, "e": 1149, "s": 1128, "text": "harshscode4 days ago" }, { "code": null, "e": 1248, "s": 1149, "text": " for(int i=s.length()-1;i>=0;i--) if(s[i]=='1') return i; return -1;" }, { "code": null, "e": 1250, "s": 1248, "text": "0" }, { "code": null, "e": 1269, "s": 1250, "text": "sumitk074 days ago" }, { "code": null, "e": 1487, "s": 1269, "text": "char c[s.length()];\n for(int i = 0;i<sizeof(c);i++){\n c[i] = s[i];\n }\n for(int i = s.length()-1;i>=0;i--){\n if(c[i] == '1')\n return i;\n }\n return -1;" }, { "code": null, "e": 1489, "s": 1487, "text": "0" }, { "code": null, "e": 1508, "s": 1489, "text": "ninthale6 days ago" }, { "code": null, "e": 1697, "s": 1508, "text": " int lastIndex(string s) { for(int i=s.length()-1;i>=0;i--) { if(s[i]=='1') { return i; } } return -1; }};" }, { "code": null, "e": 1699, "s": 1697, "text": "0" }, { "code": null, "e": 1726, "s": 1699, "text": "swapniltayal4223 weeks ago" }, { "code": null, "e": 1892, "s": 1726, "text": "class Solution: def lastIndex(self, s): # code here for i in range(len(s)-1, -1, -1): if s[i] == \"1\": return i; return -1" }, { "code": null, "e": 1894, "s": 1892, "text": "0" }, { "code": null, "e": 1917, "s": 1894, "text": "divakar16693 weeks ago" }, { "code": null, "e": 2149, "s": 1917, "text": "// JAVA SOLUTION O(1)class Solution { public int lastIndex( String s) { if( s.contains(\"1\") ) { int x=s.lastIndexOf(\"1\"); return x; } else { return -1; } }}" }, { "code": null, "e": 2151, "s": 2149, "text": "0" }, { "code": null, "e": 2172, "s": 2151, "text": "atif836141 month ago" }, { "code": null, "e": 2188, "s": 2172, "text": "JAVA SOLUTION :" }, { "code": null, "e": 2495, "s": 2188, "text": "class Solution {\n public int lastIndex( String s) {\n if (s.length() == 0) {\n\t\t\treturn -1;\n\t\t}\n\t\tint res = 0;\n\t\tint flag = 0;\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tif (s.charAt(i) == '1') {\n\t\t\t\tres = i;\n\t\t\t\tflag = 1;\n\t\t\t}\n\n\t\t}\n\t\tif (flag == 1) {\n\t\t\treturn res;\n\t\t}\n\t\treturn -1;\n\t}\n \n }" }, { "code": null, "e": 2497, "s": 2495, "text": "0" }, { "code": null, "e": 2515, "s": 2497, "text": "coderh1 month ago" }, { "code": null, "e": 2704, "s": 2515, "text": "class Solution:\n def lastIndex(self, s):\n c=len(s)-1\n for i in range(len(s)-1,-1,-1):\n if s[i]==\"1\":\n return c\n c-=1\n return -1" }, { "code": null, "e": 2706, "s": 2704, "text": "0" }, { "code": null, "e": 2733, "s": 2706, "text": "adityagagtiwari1 month ago" }, { "code": null, "e": 2791, "s": 2733, "text": "This is a basic trivial solution. Using a boolean marker." }, { "code": null, "e": 3264, "s": 2791, "text": "class Solution { public int lastIndex( String s) { int idx = 0; if(s.length()==1 && s.charAt(0)=='1') return 0; boolean visited = false; for(int i=0;i<s.length();i++) { char ch = s.charAt(i); if(ch=='1') { visited = true; idx = i; } } if(idx>=0 && visited) { return idx; } else { return -1; } }}" }, { "code": null, "e": 3266, "s": 3264, "text": "0" }, { "code": null, "e": 3295, "s": 3266, "text": "kashyapabhishek221 month ago" }, { "code": null, "e": 3451, "s": 3295, "text": "def lastIndex(self, s): # code here if '1' not in s: return -1 s = s[::-1] res = len(s)-s.index('1') -1 return res" }, { "code": null, "e": 3597, "s": 3451, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3633, "s": 3597, "text": " Login to access your submissions. " }, { "code": null, "e": 3643, "s": 3633, "text": "\nProblem\n" }, { "code": null, "e": 3653, "s": 3643, "text": "\nContest\n" }, { "code": null, "e": 3716, "s": 3653, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3864, "s": 3716, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4072, "s": 3864, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4178, "s": 4072, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How do you round up a float number in Python?
Python has an in-built function round() for this purpose. The function takes two arguments, the number to be rounded and the places upto which it is to be rounded. If the number is to be rounded to nearest integer, the second argument is not given. >>> round(1.7456) 2 >>> round(1.4756) 1 If however, it is to be rounded up, 0.5 is added to it before rounding >>> round(1.7456+0.5) 2 >>> round(1.4756+0.5) 2
[ { "code": null, "e": 1311, "s": 1062, "text": "Python has an in-built function round() for this purpose. The function takes two arguments, the number to be rounded and the places upto which it is to be rounded. If the number is to be rounded to nearest integer, the second argument is not given." }, { "code": null, "e": 1351, "s": 1311, "text": ">>> round(1.7456)\n2\n>>> round(1.4756)\n1" }, { "code": null, "e": 1422, "s": 1351, "text": "If however, it is to be rounded up, 0.5 is added to it before rounding" }, { "code": null, "e": 1470, "s": 1422, "text": ">>> round(1.7456+0.5)\n2\n>>> round(1.4756+0.5)\n2" } ]
ES6 - for in loop
The for...in loop is used to loop through an object's properties. Following is the syntax of ‘for...in’ loop. for (variablename in object) { statement or block to execute } In each iteration, one property from the object is assigned to the variable name and this loop continues till all the properties of the object are exhausted. var obj = {a:1, b:2, c:3}; for (var prop in obj) { console.log(obj[prop]); } The above example illustrates iterating an object using the for... in loop. The following output is displayed on successful execution of the code. 1 2 3 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2343, "s": 2277, "text": "The for...in loop is used to loop through an object's properties." }, { "code": null, "e": 2387, "s": 2343, "text": "Following is the syntax of ‘for...in’ loop." }, { "code": null, "e": 2454, "s": 2387, "text": "for (variablename in object) {\n statement or block to execute\n}\n" }, { "code": null, "e": 2612, "s": 2454, "text": "In each iteration, one property from the object is assigned to the variable name and this loop continues till all the properties of the object are exhausted." }, { "code": null, "e": 2693, "s": 2612, "text": "var obj = {a:1, b:2, c:3};\n\nfor (var prop in obj) {\n console.log(obj[prop]);\n}" }, { "code": null, "e": 2840, "s": 2693, "text": "The above example illustrates iterating an object using the for... in loop. The following output is displayed on successful execution of the code." }, { "code": null, "e": 2847, "s": 2840, "text": "1\n2\n3\n" }, { "code": null, "e": 2882, "s": 2847, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2896, "s": 2882, "text": " Sharad Kumar" }, { "code": null, "e": 2929, "s": 2896, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 2947, "s": 2929, "text": " Richa Maheshwari" }, { "code": null, "e": 2980, "s": 2947, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2994, "s": 2980, "text": " Anadi Sharma" }, { "code": null, "e": 3029, "s": 2994, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3046, "s": 3029, "text": " Gowthami Swarna" }, { "code": null, "e": 3079, "s": 3046, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 3095, "s": 3079, "text": " Deepti Trivedi" }, { "code": null, "e": 3130, "s": 3095, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3138, "s": 3130, "text": " Shweta" }, { "code": null, "e": 3145, "s": 3138, "text": " Print" }, { "code": null, "e": 3156, "s": 3145, "text": " Add Notes" } ]
What does double underscore prefix do in Python variables?
In Python, we use double underscore i.e., __ before the attribute's name and those attributes will not be directly accessible/visible outside. Double underscore mangles the attribute's name. However, that variable can still be accessed using some tricky syntax but it's generally not a good idea to do so. Double underscores are used for fully private variables. According to Python documentation − If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name. The code below shows use of double underscore. class MyClass: __hiddenVar = 0 def add(self, increment): self.__hiddenVar += increment print (self.__hiddenVar) myObject = MyClass() myObject.add(3) myObject.add (8) print (myObject.__hiddenVar) 3 Traceback (most recent call last): 11 File "C:/Users/TutorialsPoint1/.PyCharmCE2017.2/config/scratches/scratch_1.py", line 12, in <module> print (myObject.__hiddenVar) AttributeError: MyClass instance has no attribute '__hiddenVar' In the above program, we tried to access hidden variable outside the class using object and it threw an exception.
[ { "code": null, "e": 1425, "s": 1062, "text": "In Python, we use double underscore i.e., __ before the attribute's name and those attributes will not be directly accessible/visible outside. Double underscore mangles the attribute's name. However, that variable can still be accessed using some tricky syntax but it's generally not a good idea to do so. Double underscores are used for fully private variables." }, { "code": null, "e": 1461, "s": 1425, "text": "According to Python documentation −" }, { "code": null, "e": 1877, "s": 1461, "text": "If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name. " }, { "code": null, "e": 1924, "s": 1877, "text": "The code below shows use of double underscore." }, { "code": null, "e": 2141, "s": 1924, "text": "class MyClass:\n __hiddenVar = 0\n def add(self, increment):\n self.__hiddenVar += increment\n print (self.__hiddenVar)\nmyObject = MyClass()\nmyObject.add(3)\nmyObject.add (8)\nprint (myObject.__hiddenVar)" }, { "code": null, "e": 2381, "s": 2141, "text": "3\nTraceback (most recent call last):\n11\n File \"C:/Users/TutorialsPoint1/.PyCharmCE2017.2/config/scratches/scratch_1.py\", line 12, in <module>\n print (myObject.__hiddenVar)\nAttributeError: MyClass instance has no attribute '__hiddenVar'" }, { "code": null, "e": 2496, "s": 2381, "text": "In the above program, we tried to access hidden variable outside the class using object and it threw an exception." } ]
Sort a String | Practice | GeeksforGeeks
Given a string consisting of lowercase letters, arrange all its letters in ascending order. Example 1: Input: S = "edcab" Output: "abcde" Explanation: characters are in ascending order in "abcde". Example 2: Input: S = "xzy" Output: "xyz" Explanation: characters are in ascending order in "xyz". Your Task: You don't need to read input or print anything. Your task is to complete the function sort() which takes the string as inputs and returns the modified string. Expected Time Complexity: O(|S| * log |S|) Expected Auxiliary Space: O(1) Constraints: 1 ≤ |S| ≤ 105 S contains only lowercase alphabets. +1 rb0011 week ago My Java Solution : char tempArray[] = inputString.toCharArray(); // Sorting temp array using Arrays.sort(tempArray); // Returning new sorted string return new String(tempArray); 0 ten000perhr3 weeks ago C++ One line answer string sort(string s){ //complete the function here sort(s.begin(), s.end()); return s;} 0 mayank180919994 weeks ago string sort(string s){ //complete the function here sort(s.begin(),s.end()); return s; } -1 atif836142 months ago JAVA SOLUTION: class Solution { String sort(String s) { char[] arr=s.toCharArray(); Arrays.sort(arr); return String.valueOf(arr); } } -1 priyaranjandash2 months ago class Solution { String sort(String s) { char ch[] = s.toCharArray(); Arrays.sort(ch); return String.valueOf(ch); }} +1 imohdalam2 months ago Java | O(n) class Solution { String sort(String s) { char[] charArray = s.toCharArray(); Arrays.sort(charArray); StringBuilder ans = new StringBuilder(); for(char x: charArray) ans.append(x); return ans.toString(); } } +1 shubhamkhavare2 months ago Simple Java Soln: char[] c = s.toCharArray(); Arrays.sort(c); String str = new String(); for(int i = 0 ; i < c.length ; i++) { str += c[i]; } return str; +1 imsonishivam2 months ago without any predefine function Time complexity - O(n) n - string size; space complexity - O(1) string sort(string s){ //complete the function here int count[26] = {0}; for(int i=0;i<s.size();i++){ count[s[i] - 'a']++; } s = "\0"; for(int i=0;i<26;i++){ if(count[i] > 0){ while(count[i] != 0){ s.push_back(i+ 'a'); count[i]--; } } } return s;} +1 imabheek3 months ago // JAVA char [] arr = s.toCharArray(); Arrays.sort(arr); return new String(arr); 0 anshraj7 This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 331, "s": 238, "text": "Given a string consisting of lowercase letters, arrange all its letters in ascending order. " }, { "code": null, "e": 342, "s": 331, "text": "Example 1:" }, { "code": null, "e": 437, "s": 342, "text": "Input:\nS = \"edcab\"\nOutput: \"abcde\"\nExplanation: characters are in ascending\norder in \"abcde\".\n" }, { "code": null, "e": 448, "s": 437, "text": "Example 2:" }, { "code": null, "e": 537, "s": 448, "text": "Input:\nS = \"xzy\"\nOutput: \"xyz\"\nExplanation: characters are in ascending\norder in \"xyz\".\n" }, { "code": null, "e": 851, "s": 537, "text": "\n\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function sort() which takes the string as inputs and returns the modified string.\n\nExpected Time Complexity: O(|S| * log |S|)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 ≤ |S| ≤ 105\nS contains only lowercase alphabets." }, { "code": null, "e": 854, "s": 851, "text": "+1" }, { "code": null, "e": 870, "s": 854, "text": "rb0011 week ago" }, { "code": null, "e": 889, "s": 870, "text": "My Java Solution :" }, { "code": null, "e": 936, "s": 889, "text": " char tempArray[] = inputString.toCharArray();" }, { "code": null, "e": 972, "s": 936, "text": " // Sorting temp array using" }, { "code": null, "e": 1004, "s": 972, "text": " Arrays.sort(tempArray);" }, { "code": null, "e": 1043, "s": 1004, "text": " // Returning new sorted string" }, { "code": null, "e": 1081, "s": 1043, "text": " return new String(tempArray);" }, { "code": null, "e": 1083, "s": 1081, "text": "0" }, { "code": null, "e": 1106, "s": 1083, "text": "ten000perhr3 weeks ago" }, { "code": null, "e": 1126, "s": 1106, "text": "C++ One line answer" }, { "code": null, "e": 1223, "s": 1128, "text": "string sort(string s){ //complete the function here sort(s.begin(), s.end()); return s;}" }, { "code": null, "e": 1225, "s": 1223, "text": "0" }, { "code": null, "e": 1251, "s": 1225, "text": "mayank180919994 weeks ago" }, { "code": null, "e": 1352, "s": 1251, "text": "string sort(string s){\n //complete the function here\n sort(s.begin(),s.end());\n return s;\n}" }, { "code": null, "e": 1355, "s": 1352, "text": "-1" }, { "code": null, "e": 1377, "s": 1355, "text": "atif836142 months ago" }, { "code": null, "e": 1392, "s": 1377, "text": "JAVA SOLUTION:" }, { "code": null, "e": 1551, "s": 1392, "text": "class Solution \n{ \n String sort(String s) \n {\n char[] arr=s.toCharArray();\n Arrays.sort(arr);\n return String.valueOf(arr);\n }\n} " }, { "code": null, "e": 1554, "s": 1551, "text": "-1" }, { "code": null, "e": 1582, "s": 1554, "text": "priyaranjandash2 months ago" }, { "code": null, "e": 1733, "s": 1582, "text": "class Solution { String sort(String s) { char ch[] = s.toCharArray(); Arrays.sort(ch); return String.valueOf(ch); }} " }, { "code": null, "e": 1736, "s": 1733, "text": "+1" }, { "code": null, "e": 1758, "s": 1736, "text": "imohdalam2 months ago" }, { "code": null, "e": 1770, "s": 1758, "text": "Java | O(n)" }, { "code": null, "e": 2079, "s": 1770, "text": "class Solution \n{ \n String sort(String s) \n {\n char[] charArray = s.toCharArray();\n \n Arrays.sort(charArray);\n \n StringBuilder ans = new StringBuilder();\n \n for(char x: charArray)\n ans.append(x);\n \n return ans.toString();\n }\n}" }, { "code": null, "e": 2082, "s": 2079, "text": "+1" }, { "code": null, "e": 2109, "s": 2082, "text": "shubhamkhavare2 months ago" }, { "code": null, "e": 2127, "s": 2109, "text": "Simple Java Soln:" }, { "code": null, "e": 2315, "s": 2127, "text": " char[] c = s.toCharArray(); Arrays.sort(c); String str = new String(); for(int i = 0 ; i < c.length ; i++) { str += c[i]; } return str;" }, { "code": null, "e": 2318, "s": 2315, "text": "+1" }, { "code": null, "e": 2343, "s": 2318, "text": "imsonishivam2 months ago" }, { "code": null, "e": 2374, "s": 2343, "text": "without any predefine function" }, { "code": null, "e": 2397, "s": 2374, "text": "Time complexity - O(n)" }, { "code": null, "e": 2414, "s": 2397, "text": "n - string size;" }, { "code": null, "e": 2438, "s": 2414, "text": "space complexity - O(1)" }, { "code": null, "e": 2776, "s": 2440, "text": "string sort(string s){ //complete the function here int count[26] = {0}; for(int i=0;i<s.size();i++){ count[s[i] - 'a']++; } s = \"\\0\"; for(int i=0;i<26;i++){ if(count[i] > 0){ while(count[i] != 0){ s.push_back(i+ 'a'); count[i]--; } } } return s;}" }, { "code": null, "e": 2779, "s": 2776, "text": "+1" }, { "code": null, "e": 2800, "s": 2779, "text": "imabheek3 months ago" }, { "code": null, "e": 2808, "s": 2800, "text": "// JAVA" }, { "code": null, "e": 2893, "s": 2808, "text": "char [] arr = s.toCharArray(); Arrays.sort(arr); return new String(arr);" }, { "code": null, "e": 2895, "s": 2893, "text": "0" }, { "code": null, "e": 2904, "s": 2895, "text": "anshraj7" }, { "code": null, "e": 2930, "s": 2904, "text": "This comment was deleted." }, { "code": null, "e": 3076, "s": 2930, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3112, "s": 3076, "text": " Login to access your submissions. " }, { "code": null, "e": 3122, "s": 3112, "text": "\nProblem\n" }, { "code": null, "e": 3132, "s": 3122, "text": "\nContest\n" }, { "code": null, "e": 3195, "s": 3132, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3343, "s": 3195, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3551, "s": 3343, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3657, "s": 3551, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
ReactJS Reactstrap Modal Component - GeeksforGeeks
29 Jul, 2021 Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Modal component provides a solid foundation for creating dialogs, lightboxes, popovers, etc. We can use the following approach in ReactJS to use the ReactJS Reactstrap Modal Component. Modal Props: isOpen: The modal will show itself when this is set to true. autoFocus: The Modal is opened and is automatically focused on its own when this is set to true. centered: It is used to make the Centered Modal. size: It is used to set the Modal size toggle: It is a callback function that is triggered when the component toggles. role: It is used to denote the role attribute, its default value is “dialog”. labelledBy: It is used to reference the ID of the title element in the modal. keyboard: It is used to indicate whether to support press ESC to close or not. backdrop: The Modal will display the background in its opened state when this is set to true. scrollable: It is used to allow the modal to be scrollable when content is long. external: It is used to allows for a node or a component to exist next to the modal. onEnter: It is a callback function that is called on componentDidMount event. onExit: It is a callback function that is called on componentWillUnmount event. onOpened: It is a callback function that is called when transitioning in is done. onClosed: It is a callback function that is called when transitioning out is done. className: It is used to denote the class name for styling. wrapClassName: It is used to pass the class name of the container of the modal dialog. modalClassName: It is used to add an optional extra class name for the modal class. backdropClassName: It is used to add an optional extra class name to .modal-backdrop. contentClassName: It is used to add an optional extra class name to .modal-content fade: It is used to indicate whether the fade transition occurs or not. cssModule: It is used to denote the CSS module for styling. zIndex: It is used to denote the z-index of the Modal. backdropTransition: It is used for the backdrop Transition as it controls backdrop transition. modalTransition: It is used for the modal Transition as it controls modal transition. innerRef: It is used to denote the inner ref element for this component. unmountOnClose: It is used to unmount from DOM after closing the modal. returnFocusAfterClose: It is used to return the focus back to the element which opens the modal after the modal closes. container: It is the container attribute, and it is of type any. trapFocus: It is used to manage the focus for its descendants. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command: npm install reactstrap bootstrap Project Structure: It will look like the following. Project Structure Example 1: Now write down the following code in the App.js file. Here we have shown the Modal with a delay of 2 seconds and we have shown Modal without ModalHeader and ModalFooter. Javascript import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Button, Modal, ModalFooter, ModalHeader, ModalBody} from "reactstrap" function App() { // Modal open state const [modal, setModal] = React.useState(false); // Toggle for Modal const toggle = () => setModal(!modal); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Modal Component</h4> <Button color="primary" onClick={toggle}>Open Modal</Button> <Modal isOpen={modal} toggle={toggle} modalTransition={{ timeout: 2000 }}> <ModalBody> Simple Modal with just ModalBody... </ModalBody> </Modal> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: Now write down the following code in the App.js file. Here we have shown the Modal without any delay and we have shown Modal with ModalHeader and ModalFooter. Javascript import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Button, Modal, ModalFooter, ModalHeader, ModalBody} from "reactstrap" function App() { // Modal open state const [modal, setModal] = React.useState(false); // Toggle for Modal const toggle = () => setModal(!modal); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Modal Component</h4> <Button color="danger" onClick={toggle}>Click me to open Modal</Button> <Modal isOpen={modal} toggle={toggle}> <ModalHeader toggle={toggle}>Sample Modal Title</ModalHeader> <ModalBody> Sample Modal Body Text to display... </ModalBody> <ModalFooter> <Button color="primary" onClick={toggle}>Okay</Button> </ModalFooter> </Modal> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://reactstrap.github.io/components/modals/ Reactstrap JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 27108, "s": 27080, "text": "\n29 Jul, 2021" }, { "code": null, "e": 27459, "s": 27108, "text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Modal component provides a solid foundation for creating dialogs, lightboxes, popovers, etc. We can use the following approach in ReactJS to use the ReactJS Reactstrap Modal Component." }, { "code": null, "e": 27472, "s": 27459, "text": "Modal Props:" }, { "code": null, "e": 27533, "s": 27472, "text": "isOpen: The modal will show itself when this is set to true." }, { "code": null, "e": 27630, "s": 27533, "text": "autoFocus: The Modal is opened and is automatically focused on its own when this is set to true." }, { "code": null, "e": 27679, "s": 27630, "text": "centered: It is used to make the Centered Modal." }, { "code": null, "e": 27718, "s": 27679, "text": "size: It is used to set the Modal size" }, { "code": null, "e": 27799, "s": 27718, "text": "toggle: It is a callback function that is triggered when the component toggles." }, { "code": null, "e": 27878, "s": 27799, "text": "role: It is used to denote the role attribute, its default value is “dialog”." }, { "code": null, "e": 27956, "s": 27878, "text": "labelledBy: It is used to reference the ID of the title element in the modal." }, { "code": null, "e": 28035, "s": 27956, "text": "keyboard: It is used to indicate whether to support press ESC to close or not." }, { "code": null, "e": 28129, "s": 28035, "text": "backdrop: The Modal will display the background in its opened state when this is set to true." }, { "code": null, "e": 28210, "s": 28129, "text": "scrollable: It is used to allow the modal to be scrollable when content is long." }, { "code": null, "e": 28295, "s": 28210, "text": "external: It is used to allows for a node or a component to exist next to the modal." }, { "code": null, "e": 28373, "s": 28295, "text": "onEnter: It is a callback function that is called on componentDidMount event." }, { "code": null, "e": 28453, "s": 28373, "text": "onExit: It is a callback function that is called on componentWillUnmount event." }, { "code": null, "e": 28535, "s": 28453, "text": "onOpened: It is a callback function that is called when transitioning in is done." }, { "code": null, "e": 28618, "s": 28535, "text": "onClosed: It is a callback function that is called when transitioning out is done." }, { "code": null, "e": 28678, "s": 28618, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 28766, "s": 28678, "text": "wrapClassName: It is used to pass the class name of the container of the modal dialog. " }, { "code": null, "e": 28850, "s": 28766, "text": "modalClassName: It is used to add an optional extra class name for the modal class." }, { "code": null, "e": 28936, "s": 28850, "text": "backdropClassName: It is used to add an optional extra class name to .modal-backdrop." }, { "code": null, "e": 29021, "s": 28936, "text": "contentClassName: It is used to add an optional extra class name to .modal-content " }, { "code": null, "e": 29093, "s": 29021, "text": "fade: It is used to indicate whether the fade transition occurs or not." }, { "code": null, "e": 29153, "s": 29093, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 29208, "s": 29153, "text": "zIndex: It is used to denote the z-index of the Modal." }, { "code": null, "e": 29303, "s": 29208, "text": "backdropTransition: It is used for the backdrop Transition as it controls backdrop transition." }, { "code": null, "e": 29389, "s": 29303, "text": "modalTransition: It is used for the modal Transition as it controls modal transition." }, { "code": null, "e": 29462, "s": 29389, "text": "innerRef: It is used to denote the inner ref element for this component." }, { "code": null, "e": 29534, "s": 29462, "text": "unmountOnClose: It is used to unmount from DOM after closing the modal." }, { "code": null, "e": 29654, "s": 29534, "text": "returnFocusAfterClose: It is used to return the focus back to the element which opens the modal after the modal closes." }, { "code": null, "e": 29719, "s": 29654, "text": "container: It is the container attribute, and it is of type any." }, { "code": null, "e": 29782, "s": 29719, "text": "trapFocus: It is used to manage the focus for its descendants." }, { "code": null, "e": 29832, "s": 29782, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 29896, "s": 29832, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 29928, "s": 29896, "text": "npx create-react-app foldername" }, { "code": null, "e": 30030, "s": 29930, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 30044, "s": 30030, "text": "cd foldername" }, { "code": null, "e": 30149, "s": 30044, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 30182, "s": 30149, "text": "npm install reactstrap bootstrap" }, { "code": null, "e": 30234, "s": 30182, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 30252, "s": 30234, "text": "Project Structure" }, { "code": null, "e": 30433, "s": 30252, "text": "Example 1: Now write down the following code in the App.js file. Here we have shown the Modal with a delay of 2 seconds and we have shown Modal without ModalHeader and ModalFooter." }, { "code": null, "e": 30444, "s": 30433, "text": "Javascript" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Button, Modal, ModalFooter, ModalHeader, ModalBody} from \"reactstrap\" function App() { // Modal open state const [modal, setModal] = React.useState(false); // Toggle for Modal const toggle = () => setModal(!modal); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Modal Component</h4> <Button color=\"primary\" onClick={toggle}>Open Modal</Button> <Modal isOpen={modal} toggle={toggle} modalTransition={{ timeout: 2000 }}> <ModalBody> Simple Modal with just ModalBody... </ModalBody> </Modal> </div > );} export default App;", "e": 31292, "s": 30444, "text": null }, { "code": null, "e": 31405, "s": 31292, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 31415, "s": 31405, "text": "npm start" }, { "code": null, "e": 31514, "s": 31415, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 31684, "s": 31514, "text": "Example 2: Now write down the following code in the App.js file. Here we have shown the Modal without any delay and we have shown Modal with ModalHeader and ModalFooter." }, { "code": null, "e": 31695, "s": 31684, "text": "Javascript" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Button, Modal, ModalFooter, ModalHeader, ModalBody} from \"reactstrap\" function App() { // Modal open state const [modal, setModal] = React.useState(false); // Toggle for Modal const toggle = () => setModal(!modal); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Modal Component</h4> <Button color=\"danger\" onClick={toggle}>Click me to open Modal</Button> <Modal isOpen={modal} toggle={toggle}> <ModalHeader toggle={toggle}>Sample Modal Title</ModalHeader> <ModalBody> Sample Modal Body Text to display... </ModalBody> <ModalFooter> <Button color=\"primary\" onClick={toggle}>Okay</Button> </ModalFooter> </Modal> </div > );} export default App;", "e": 32718, "s": 31695, "text": null }, { "code": null, "e": 32831, "s": 32718, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 32841, "s": 32831, "text": "npm start" }, { "code": null, "e": 32940, "s": 32841, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 32999, "s": 32940, "text": "Reference: https://reactstrap.github.io/components/modals/" }, { "code": null, "e": 33010, "s": 32999, "text": "Reactstrap" }, { "code": null, "e": 33021, "s": 33010, "text": "JavaScript" }, { "code": null, "e": 33029, "s": 33021, "text": "ReactJS" }, { "code": null, "e": 33046, "s": 33029, "text": "Web Technologies" }, { "code": null, "e": 33144, "s": 33046, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33184, "s": 33144, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33245, "s": 33184, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33286, "s": 33245, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 33308, "s": 33286, "text": "JavaScript | Promises" }, { "code": null, "e": 33362, "s": 33308, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 33405, "s": 33362, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33450, "s": 33405, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 33515, "s": 33450, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 33583, "s": 33515, "text": "How to pass data from one component to other component in ReactJS ?" } ]
How to Round Numbers in Python? - GeeksforGeeks
20 Aug, 2020 Rounding a number means making the number simpler by keeping its value intact but closer to the next number. Example: If we want to round off a number, say 3.5. It will be rounded to the nearest whole number which is 4. However, the number 3.74 will be rounded to one decimal place to give 3.7. Method 1: Using Built-in round() Function.In Python there is a built-in round() function which rounds off a number to the given number of digits. The function round() accepts two numeric arguments, n and n digits and then returns the number n after rounding it to n digits. If the number of digits are not provided for rounding off, the function rounds off the given number n to the nearest integer. Syntax: round(number, number of digits) Parameters: number: The number to be rounded number of digits (Optional): The number of digits up to which the given number is to be rounded Example: python3 # For integersprint(round(11)) # For floating pointprint(round(22.7)) # if the second parameter is present # when the (ndigit+1)th digit is =5 print(round(4.465, 2)) # when the (ndigit+1)th digit is >=5 print(round(4.476, 2)) # when the (ndigit+1)th digit is <5 print(round(4.473, 2)) Output: 11 23 4.46 4.48 4.47 Method 2: Using Truncation concept.Truncation is one of the simplest methods to round a number which involves truncating a number to a given number of digits. In this function, each digit after a given position is replaced with 0. truncate() function can be used with positive as well as negative numbers. Truncation function can be implemented in following way: Multiplying the number by 10^p (10 raised to the pth power) to shift the decimal point p places to the right. Taking the integer part of that new number using int(). Shifting the decimal place p places back to the left by dividing by 10^p. Implementation of the Truncation concept using truncate() user-defined function: python3 # defining truncate function# second argument defaults to 0# so that if no argument is passed # it returns the integer part of number def truncate(n, decimals = 0): multiplier = 10 ** decimals return int(n * multiplier) / multiplier print(truncate(16.5))print(truncate(-3.853, 1))print(truncate(3.815, 2)) # we can truncate digits towards the left of the decimal point# by passing a negative number.print(truncate(346.8, -1))print(truncate(-2947.48, -3)) Output: 16.0 -3.8 3.81 340.0 -2000.0 Method 3: Using Math.ceil() and Math.floor() functions.Math.ceil(): This function returns the nearest integer that is greater than or equal to a given number. Math.floor(): This function returns the nearest integer less than or equal to a given number. Example: python3 # import math libraryimport math # ceil value for positive# decimal numberprint(math.ceil(4.2)) # ceil value for negative# decimal numberprint(math.ceil(-0.5)) # floor value for decimal # and negative numberprint(math.floor(2.2))print(math.floor(-0.5)) Output: 5 0 2 -1 Method 3: Using Rounding Up concept.In Rounding Up a number is rounded up to a specified number of digits. Rounding up function can be implemented in following way: First the decimal point in n is shifted the correct number of places to the right by multiplying n by 10 ** decimals. The new value is rounded up to the nearest integer using math.ceil() Finally, the decimal point is shifted back to the left by dividing by 10 ** decimals. Implementation of the rounding up concept using round_up() user-defined function: python3 # import math libraryimport math # define a function for # round_updef round_up(n, decimals = 0): multiplier = 10 ** decimals return math.ceil(n * multiplier) / multiplier # passing positive valuesprint(round_up(2.1))print(round_up(2.23, 1))print(round_up(2.543, 2)) # passing negative valuesprint(round_up(22.45, -1))print(round_up(2352, -2)) Output: 3.0 2.3 2.55 30.0 2400.0 We can follow the diagram below to understand round up and round down. Round up to the right and down to the left. Rounding up always rounds a number to the right on the number line and rounding down always rounds a number to the left on the number line. Method 5: Using Rounding Down concept. In Rounding Down a number is rounded down to a specified number of digits. Rounding down function can be implemented in following way: First the decimal point in n is shifted the correct number of places to the right by multiplying n by 10 ** decimals. The new value is rounded up to the nearest integer using math.floor(). Finally, the decimal point is shifted back to the left by dividing by 10 ** decimals. Implementation of the rounding down concept using round_down() user-defined function: python3 import math # defining a function for# round down.def round_down(n, decimals=0): multiplier = 10 ** decimals return math.floor(n * multiplier) / multiplier # passing different values to functionprint(round_down(2.5))print(round_down(2.48, 1))print(round_down(-0.5)) Output: 2.0 2.4 -1.0 Method 5: Using Rounding Bias concept.The concept of symmetry introduces the notion of rounding bias, that describes how rounding affects numeric data in a dataset. The rounding up strategy has a round towards positive infinity bias, as the value is always rounded up in the direction of positive infinity. Similarly, the rounding down strategy has a round towards negative infinity bias. The truncation strategy has a round towards negative infinity bias on positive values and a round towards positive infinity for negative values. Rounding functions with this behaviour are said to have a round towards zero bias, in general. a) Rounding Half Up concept.The rounding half up rounds every number to the nearest number with the specified precision and breaks ties by rounding up. Rounding half up strategy is implemented by shifting the decimal point to the right by the desired number of places. In this case we will have to determine whether the digit after the shifted decimal point is less than or greater than equal to 5. We can add 0.5 to the value which is shifted and then round it down with the math.floor() function. Implementation of round_half_up() function: python3 import math # defining round_half_up def round_half_up(n, decimals=0): multiplier = 10 ** decimals return math.floor(n * multiplier + 0.5) / multiplier # passing different values to the function print(round_half_up(1.28, 1))print(round_half_up(-1.5))print(round_half_up(-1.225, 2)) Output: 1.3 -1.0 -1.23 b) Rounding Half Down concept.This rounds to the nearest number similarly like rounding half up method, the difference is that it breaks ties by rounding to the lesser of the two numbers. Rounding half down strategy is implemented by replacing math.floor() in the round_half_up() function with math.ceil() and then by subtracting 0.5 instead of adding. Implementation of round_half_down() function: python3 # import math libraryimport math # defining a function# for round_half_downdef round_half_down(n, decimals=0): multiplier = 10 ** decimals return math.ceil(n * multiplier - 0.5) / multiplier # passing different values to the functionprint(round_half_down(2.5))print(round_half_down(-2.5))print(round_half_down(2.25, 1)) Output: 2.0 -3.0 2.2 Method 6: Rounding Half Away From Zero.In Rounding Half Away From Zero we need to do is to start as usual by shifting the decimal point to the right a given number of places and then notice the digit(d) immediately to the right of the decimal place in the new number. There are four cases to consider: If n is positive and d >= 5, round up If n is positive and d = 5, round down If n is negative and d >= 5, round down If n is negative and d < 5, round up After rounding as per the rules mentioned above, we can shift the decimal place back to the left. Rounding Half To Even: There is a way to mitigate rounding bias while we are rounding values in a dataset. We can simply round ties to the nearest even number at the desired precision. The rounding half to even strategy is the strategy used by Python’s built-in round(). The decimal class provides support for fast correctly-rounded decimal floating-point arithmetic. This offers several advantages over the float datatype. The default rounding strategy in the decimal module is ROUND_HALF_EVEN. Example: python3 # import Decimal function from # decimal libraryfrom decimal import Decimalprint(Decimal("0.1"))print(Decimal(0.1)) # Rounding a Decimal number is# done with the .quantize() function# "1.0" in .quantize() determines the# number of decimal places to round the numberprint(Decimal("1.65").quantize(Decimal("1.0")))print(Decimal("1.675").quantize(Decimal("1.00"))) Output: 0.1 0.1000000000000000055511151231257827021181583404541015625 1.6 1.68 python-basics Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25415, "s": 25387, "text": "\n20 Aug, 2020" }, { "code": null, "e": 25711, "s": 25415, "text": "Rounding a number means making the number simpler by keeping its value intact but closer to the next number. Example: If we want to round off a number, say 3.5. It will be rounded to the nearest whole number which is 4. However, the number 3.74 will be rounded to one decimal place to give 3.7. " }, { "code": null, "e": 26112, "s": 25711, "text": "Method 1: Using Built-in round() Function.In Python there is a built-in round() function which rounds off a number to the given number of digits. The function round() accepts two numeric arguments, n and n digits and then returns the number n after rounding it to n digits. If the number of digits are not provided for rounding off, the function rounds off the given number n to the nearest integer. " }, { "code": null, "e": 26152, "s": 26112, "text": "Syntax: round(number, number of digits)" }, { "code": null, "e": 26165, "s": 26152, "text": "Parameters: " }, { "code": null, "e": 26198, "s": 26165, "text": "number: The number to be rounded" }, { "code": null, "e": 26294, "s": 26198, "text": "number of digits (Optional): The number of digits up to which the given number is to be rounded" }, { "code": null, "e": 26304, "s": 26294, "text": "Example: " }, { "code": null, "e": 26312, "s": 26304, "text": "python3" }, { "code": "# For integersprint(round(11)) # For floating pointprint(round(22.7)) # if the second parameter is present # when the (ndigit+1)th digit is =5 print(round(4.465, 2)) # when the (ndigit+1)th digit is >=5 print(round(4.476, 2)) # when the (ndigit+1)th digit is <5 print(round(4.473, 2))", "e": 26612, "s": 26312, "text": null }, { "code": null, "e": 26621, "s": 26612, "text": "Output: " }, { "code": null, "e": 26643, "s": 26621, "text": "11\n23\n4.46\n4.48\n4.47\n" }, { "code": null, "e": 26950, "s": 26643, "text": "Method 2: Using Truncation concept.Truncation is one of the simplest methods to round a number which involves truncating a number to a given number of digits. In this function, each digit after a given position is replaced with 0. truncate() function can be used with positive as well as negative numbers. " }, { "code": null, "e": 27007, "s": 26950, "text": "Truncation function can be implemented in following way:" }, { "code": null, "e": 27117, "s": 27007, "text": "Multiplying the number by 10^p (10 raised to the pth power) to shift the decimal point p places to the right." }, { "code": null, "e": 27173, "s": 27117, "text": "Taking the integer part of that new number using int()." }, { "code": null, "e": 27247, "s": 27173, "text": "Shifting the decimal place p places back to the left by dividing by 10^p." }, { "code": null, "e": 27329, "s": 27247, "text": "Implementation of the Truncation concept using truncate() user-defined function: " }, { "code": null, "e": 27337, "s": 27329, "text": "python3" }, { "code": "# defining truncate function# second argument defaults to 0# so that if no argument is passed # it returns the integer part of number def truncate(n, decimals = 0): multiplier = 10 ** decimals return int(n * multiplier) / multiplier print(truncate(16.5))print(truncate(-3.853, 1))print(truncate(3.815, 2)) # we can truncate digits towards the left of the decimal point# by passing a negative number.print(truncate(346.8, -1))print(truncate(-2947.48, -3))", "e": 27801, "s": 27337, "text": null }, { "code": null, "e": 27810, "s": 27801, "text": "Output: " }, { "code": null, "e": 27840, "s": 27810, "text": "16.0\n-3.8\n3.81\n340.0\n-2000.0\n" }, { "code": null, "e": 28102, "s": 27840, "text": "Method 3: Using Math.ceil() and Math.floor() functions.Math.ceil(): This function returns the nearest integer that is greater than or equal to a given number. Math.floor(): This function returns the nearest integer less than or equal to a given number. Example:" }, { "code": null, "e": 28110, "s": 28102, "text": "python3" }, { "code": "# import math libraryimport math # ceil value for positive# decimal numberprint(math.ceil(4.2)) # ceil value for negative# decimal numberprint(math.ceil(-0.5)) # floor value for decimal # and negative numberprint(math.floor(2.2))print(math.floor(-0.5))", "e": 28366, "s": 28110, "text": null }, { "code": null, "e": 28375, "s": 28366, "text": "Output: " }, { "code": null, "e": 28385, "s": 28375, "text": "5\n0\n2\n-1\n" }, { "code": null, "e": 28494, "s": 28385, "text": "Method 3: Using Rounding Up concept.In Rounding Up a number is rounded up to a specified number of digits. " }, { "code": null, "e": 28553, "s": 28494, "text": "Rounding up function can be implemented in following way: " }, { "code": null, "e": 28671, "s": 28553, "text": "First the decimal point in n is shifted the correct number of places to the right by multiplying n by 10 ** decimals." }, { "code": null, "e": 28740, "s": 28671, "text": "The new value is rounded up to the nearest integer using math.ceil()" }, { "code": null, "e": 28826, "s": 28740, "text": "Finally, the decimal point is shifted back to the left by dividing by 10 ** decimals." }, { "code": null, "e": 28908, "s": 28826, "text": "Implementation of the rounding up concept using round_up() user-defined function:" }, { "code": null, "e": 28916, "s": 28908, "text": "python3" }, { "code": "# import math libraryimport math # define a function for # round_updef round_up(n, decimals = 0): multiplier = 10 ** decimals return math.ceil(n * multiplier) / multiplier # passing positive valuesprint(round_up(2.1))print(round_up(2.23, 1))print(round_up(2.543, 2)) # passing negative valuesprint(round_up(22.45, -1))print(round_up(2352, -2))", "e": 29271, "s": 28916, "text": null }, { "code": null, "e": 29280, "s": 29271, "text": "Output: " }, { "code": null, "e": 29306, "s": 29280, "text": "3.0\n2.3\n2.55\n30.0\n2400.0\n" }, { "code": null, "e": 29423, "s": 29306, "text": "We can follow the diagram below to understand round up and round down. Round up to the right and down to the left. " }, { "code": null, "e": 29602, "s": 29423, "text": "Rounding up always rounds a number to the right on the number line and rounding down always rounds a number to the left on the number line. Method 5: Using Rounding Down concept." }, { "code": null, "e": 29678, "s": 29602, "text": "In Rounding Down a number is rounded down to a specified number of digits. " }, { "code": null, "e": 29739, "s": 29678, "text": "Rounding down function can be implemented in following way: " }, { "code": null, "e": 29857, "s": 29739, "text": "First the decimal point in n is shifted the correct number of places to the right by multiplying n by 10 ** decimals." }, { "code": null, "e": 29928, "s": 29857, "text": "The new value is rounded up to the nearest integer using math.floor()." }, { "code": null, "e": 30014, "s": 29928, "text": "Finally, the decimal point is shifted back to the left by dividing by 10 ** decimals." }, { "code": null, "e": 30100, "s": 30014, "text": "Implementation of the rounding down concept using round_down() user-defined function:" }, { "code": null, "e": 30108, "s": 30100, "text": "python3" }, { "code": "import math # defining a function for# round down.def round_down(n, decimals=0): multiplier = 10 ** decimals return math.floor(n * multiplier) / multiplier # passing different values to functionprint(round_down(2.5))print(round_down(2.48, 1))print(round_down(-0.5))", "e": 30382, "s": 30108, "text": null }, { "code": null, "e": 30391, "s": 30382, "text": "Output: " }, { "code": null, "e": 30405, "s": 30391, "text": "2.0\n2.4\n-1.0\n" }, { "code": null, "e": 31035, "s": 30405, "text": "Method 5: Using Rounding Bias concept.The concept of symmetry introduces the notion of rounding bias, that describes how rounding affects numeric data in a dataset. The rounding up strategy has a round towards positive infinity bias, as the value is always rounded up in the direction of positive infinity. Similarly, the rounding down strategy has a round towards negative infinity bias. The truncation strategy has a round towards negative infinity bias on positive values and a round towards positive infinity for negative values. Rounding functions with this behaviour are said to have a round towards zero bias, in general. " }, { "code": null, "e": 31535, "s": 31035, "text": "a) Rounding Half Up concept.The rounding half up rounds every number to the nearest number with the specified precision and breaks ties by rounding up. Rounding half up strategy is implemented by shifting the decimal point to the right by the desired number of places. In this case we will have to determine whether the digit after the shifted decimal point is less than or greater than equal to 5. We can add 0.5 to the value which is shifted and then round it down with the math.floor() function. " }, { "code": null, "e": 31580, "s": 31535, "text": "Implementation of round_half_up() function: " }, { "code": null, "e": 31588, "s": 31580, "text": "python3" }, { "code": "import math # defining round_half_up def round_half_up(n, decimals=0): multiplier = 10 ** decimals return math.floor(n * multiplier + 0.5) / multiplier # passing different values to the function print(round_half_up(1.28, 1))print(round_half_up(-1.5))print(round_half_up(-1.225, 2))", "e": 31880, "s": 31588, "text": null }, { "code": null, "e": 31889, "s": 31880, "text": "Output: " }, { "code": null, "e": 31906, "s": 31889, "text": "1.3\n-1.0\n-1.23\n\n" }, { "code": null, "e": 32260, "s": 31906, "text": "b) Rounding Half Down concept.This rounds to the nearest number similarly like rounding half up method, the difference is that it breaks ties by rounding to the lesser of the two numbers. Rounding half down strategy is implemented by replacing math.floor() in the round_half_up() function with math.ceil() and then by subtracting 0.5 instead of adding. " }, { "code": null, "e": 32307, "s": 32260, "text": "Implementation of round_half_down() function: " }, { "code": null, "e": 32315, "s": 32307, "text": "python3" }, { "code": "# import math libraryimport math # defining a function# for round_half_downdef round_half_down(n, decimals=0): multiplier = 10 ** decimals return math.ceil(n * multiplier - 0.5) / multiplier # passing different values to the functionprint(round_half_down(2.5))print(round_half_down(-2.5))print(round_half_down(2.25, 1))", "e": 32643, "s": 32315, "text": null }, { "code": null, "e": 32652, "s": 32643, "text": "Output: " }, { "code": null, "e": 32666, "s": 32652, "text": "2.0\n-3.0\n2.2\n" }, { "code": null, "e": 32968, "s": 32666, "text": "Method 6: Rounding Half Away From Zero.In Rounding Half Away From Zero we need to do is to start as usual by shifting the decimal point to the right a given number of places and then notice the digit(d) immediately to the right of the decimal place in the new number. There are four cases to consider:" }, { "code": null, "e": 33006, "s": 32968, "text": "If n is positive and d >= 5, round up" }, { "code": null, "e": 33045, "s": 33006, "text": "If n is positive and d = 5, round down" }, { "code": null, "e": 33085, "s": 33045, "text": "If n is negative and d >= 5, round down" }, { "code": null, "e": 33122, "s": 33085, "text": "If n is negative and d < 5, round up" }, { "code": null, "e": 33221, "s": 33122, "text": "After rounding as per the rules mentioned above, we can shift the decimal place back to the left. " }, { "code": null, "e": 33717, "s": 33221, "text": "Rounding Half To Even: There is a way to mitigate rounding bias while we are rounding values in a dataset. We can simply round ties to the nearest even number at the desired precision. The rounding half to even strategy is the strategy used by Python’s built-in round(). The decimal class provides support for fast correctly-rounded decimal floating-point arithmetic. This offers several advantages over the float datatype. The default rounding strategy in the decimal module is ROUND_HALF_EVEN." }, { "code": null, "e": 33727, "s": 33717, "text": "Example: " }, { "code": null, "e": 33735, "s": 33727, "text": "python3" }, { "code": "# import Decimal function from # decimal libraryfrom decimal import Decimalprint(Decimal(\"0.1\"))print(Decimal(0.1)) # Rounding a Decimal number is# done with the .quantize() function# \"1.0\" in .quantize() determines the# number of decimal places to round the numberprint(Decimal(\"1.65\").quantize(Decimal(\"1.0\")))print(Decimal(\"1.675\").quantize(Decimal(\"1.00\")))", "e": 34098, "s": 33735, "text": null }, { "code": null, "e": 34107, "s": 34098, "text": "Output: " }, { "code": null, "e": 34179, "s": 34107, "text": "0.1\n0.1000000000000000055511151231257827021181583404541015625\n1.6\n1.68\n" }, { "code": null, "e": 34193, "s": 34179, "text": "python-basics" }, { "code": null, "e": 34219, "s": 34193, "text": "Python-Built-in-functions" }, { "code": null, "e": 34226, "s": 34219, "text": "Python" }, { "code": null, "e": 34324, "s": 34226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34342, "s": 34324, "text": "Python Dictionary" }, { "code": null, "e": 34377, "s": 34342, "text": "Read a file line by line in Python" }, { "code": null, "e": 34409, "s": 34377, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34431, "s": 34409, "text": "Enumerate() in Python" }, { "code": null, "e": 34473, "s": 34431, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 34503, "s": 34473, "text": "Iterate over a list in Python" }, { "code": null, "e": 34529, "s": 34503, "text": "Python String | replace()" }, { "code": null, "e": 34573, "s": 34529, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 34602, "s": 34573, "text": "*args and **kwargs in Python" } ]
Check if a given string is a valid number in C++
It should be validated if a given string is numeric. Input − str = "12.5" Output − true Input − str = "def" Output − false Input − str = "2e5" Output − true Input − 10e4.4 Output − false We have to handle the following cases in the code. We have to ignore the leading and trailing white spaces. We have to ignore the leading and trailing white spaces. We have to ignore the ‘+’, ‘-‘ and’.’ at the start. We have to ignore the ‘+’, ‘-‘ and’.’ at the start. We have to ensure that the characters in the string belong to {+, -, ., e, [0-9]} We have to ensure that the characters in the string belong to {+, -, ., e, [0-9]} We have to ensure that no ‘.’ comes after ‘e’. We have to ensure that no ‘.’ comes after ‘e’. A digit should follow a dot character ‘.’. A digit should follow a dot character ‘.’. We have to ensure that the character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit. We have to ensure that the character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit. Live Demo // C++ program to check if input number // is a valid number #include <bits/stdc++.h> #include <iostream> using namespace std; int valid_number1(string str1){ int i = 0, j = str1.length() - 1; while (i < str1.length() && str1[i] == ' ') i++; while (j >= 0 && str1[j] == ' ') j--; if (i > j) return 0; if (i == j && !(str1[i] >= '0' && str1[i] <= '9')) return 0; if (str1[i] != '.' && str1[i] != '+' && str1[i] != '-' && !(str1[i] >= '0' && str1[i] <= '9')) return 0; bool flagDotOrE = false; for (i; i <= j; i++) { // If any of the char does not belong to // {digit, +, -, ., e} if (str1[i] != 'e' && str1[i] != '.' && str1[i] != '+' && str1[i] != '-' && !(str1[i] >= '0' && str1[i] <= '9')) return 0; if (str1[i] == '.') { if (flagDotOrE == true) return 0; if (i + 1 > str1.length()) return 0; if (!(str1[i + 1] >= '0' && str1[i + 1] <= '9')) return 0; } else if (str1[i] == 'e') { flagDotOrE = true; if (!(str1[i - 1] >= '0' && str1[i - 1] <= '9')) return 0; if (i + 1 > str1.length()) return 0; if (str1[i + 1] != '+' && str1[i + 1] != '-' && (str1[i + 1] >= '0' && str1[i] <= '9')) return 0; } } return 1; } // Driver code int main(){ char str1[] = "0.1e10"; if (valid_number1(str1)) cout << "true"; else cout << "false"; return 0; } true
[ { "code": null, "e": 1115, "s": 1062, "text": "It should be validated if a given string is numeric." }, { "code": null, "e": 1136, "s": 1115, "text": "Input − str = \"12.5\"" }, { "code": null, "e": 1150, "s": 1136, "text": "Output − true" }, { "code": null, "e": 1170, "s": 1150, "text": "Input − str = \"def\"" }, { "code": null, "e": 1185, "s": 1170, "text": "Output − false" }, { "code": null, "e": 1205, "s": 1185, "text": "Input − str = \"2e5\"" }, { "code": null, "e": 1219, "s": 1205, "text": "Output − true" }, { "code": null, "e": 1234, "s": 1219, "text": "Input − 10e4.4" }, { "code": null, "e": 1249, "s": 1234, "text": "Output − false" }, { "code": null, "e": 1300, "s": 1249, "text": "We have to handle the following cases in the code." }, { "code": null, "e": 1357, "s": 1300, "text": "We have to ignore the leading and trailing white spaces." }, { "code": null, "e": 1414, "s": 1357, "text": "We have to ignore the leading and trailing white spaces." }, { "code": null, "e": 1466, "s": 1414, "text": "We have to ignore the ‘+’, ‘-‘ and’.’ at the start." }, { "code": null, "e": 1518, "s": 1466, "text": "We have to ignore the ‘+’, ‘-‘ and’.’ at the start." }, { "code": null, "e": 1600, "s": 1518, "text": "We have to ensure that the characters in the string belong to {+, -, ., e, [0-9]}" }, { "code": null, "e": 1682, "s": 1600, "text": "We have to ensure that the characters in the string belong to {+, -, ., e, [0-9]}" }, { "code": null, "e": 1729, "s": 1682, "text": "We have to ensure that no ‘.’ comes after ‘e’." }, { "code": null, "e": 1776, "s": 1729, "text": "We have to ensure that no ‘.’ comes after ‘e’." }, { "code": null, "e": 1819, "s": 1776, "text": "A digit should follow a dot character ‘.’." }, { "code": null, "e": 1862, "s": 1819, "text": "A digit should follow a dot character ‘.’." }, { "code": null, "e": 1954, "s": 1862, "text": "We have to ensure that the character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit." }, { "code": null, "e": 2046, "s": 1954, "text": "We have to ensure that the character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit." }, { "code": null, "e": 2057, "s": 2046, "text": " Live Demo" }, { "code": null, "e": 3583, "s": 2057, "text": "// C++ program to check if input number\n// is a valid number\n#include <bits/stdc++.h>\n#include <iostream>\nusing namespace std;\nint valid_number1(string str1){\n int i = 0, j = str1.length() - 1;\n while (i < str1.length() && str1[i] == ' ')\n i++;\n while (j >= 0 && str1[j] == ' ')\n j--;\n if (i > j)\n return 0;\n if (i == j && !(str1[i] >= '0' && str1[i] <= '9'))\n return 0;\n if (str1[i] != '.' && str1[i] != '+' && str1[i] != '-' && !(str1[i] >= '0' && str1[i] <= '9'))\n return 0;\n bool flagDotOrE = false;\n for (i; i <= j; i++) {\n // If any of the char does not belong to\n // {digit, +, -, ., e}\n if (str1[i] != 'e' && str1[i] != '.'\n && str1[i] != '+' && str1[i] != '-'\n && !(str1[i] >= '0' && str1[i] <= '9'))\n return 0;\n if (str1[i] == '.') {\n if (flagDotOrE == true)\n return 0;\n if (i + 1 > str1.length())\n return 0;\n if (!(str1[i + 1] >= '0' && str1[i + 1] <= '9'))\n return 0;\n }\n else if (str1[i] == 'e') {\n flagDotOrE = true;\n if (!(str1[i - 1] >= '0' && str1[i - 1] <= '9'))\n return 0;\n if (i + 1 > str1.length())\n return 0;\n if (str1[i + 1] != '+' && str1[i + 1] != '-'\n && (str1[i + 1] >= '0' && str1[i] <= '9'))\n return 0;\n }\n }\n return 1;\n}\n// Driver code\nint main(){\n char str1[] = \"0.1e10\";\n if (valid_number1(str1))\n cout << \"true\";\n else\n cout << \"false\";\n return 0;\n}" }, { "code": null, "e": 3588, "s": 3583, "text": "true" } ]
Angular PrimeNG Inplace Component - GeeksforGeeks
24 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Inplace component in Angular PrimeNG. We will also learn about the properties, events, methods & styling along with their syntaxes that will be used in the code. Inplace component: It is used to edit & display the content inplace of others at the same time & render the actual output while clicking the button to display. Properties: active: It is used to specify whether the content is displayed or not. It is of boolean datatype & the default value is false. disabled: It specifies that the element should be disabled. It is of the boolean data type, the default value is false. closable: It Displays a button to switch back to display mode. It is of the boolean data type, the default value is false. preventClick: It specifies whether the component can be controlled full programmatic with activate() and deactivate() functions. It is of the boolean data type, the default value is false. style: It sets an inline style of the component. It is of string data type, the default value is null. styleClass: It is the style class of the component. It is of string data type, the default value is null. closeIcon: It is the close icon, It is of string data type, the default value is pi pi-times. Events: onActivate: It is a callback that is fired when content is activated. onDeactivate: It is a callback that is fired when content is deactivated Methods: activate: It is used to activates the content. deactivate: It is used to deactivates the content. Styling: p-inplace: It is the Container element p-inplace-display: It is the Display container p-inplace-content: It is the Content container Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that illustrates how to implement the closable property in the Inplace Component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Inplace Component</h5><p-inplace closable="closable"> <ng-template pTemplate="display"> Click to Edit </ng-template> <ng-template pTemplate="content"> <input type="text" value="GeeksforGeeks" pInputText /> </ng-template></p-inplace> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { HttpClientModule } from "@angular/common/http";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { InplaceModule } from "primeng/inplace";import { TableModule } from "primeng/table";import { InputTextModule } from "primeng/inputtext"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, InplaceModule, InputTextModule, TableModule, HttpClientModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we are making a button inside the Inplace Component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Inplace Component</h5><p-inplace> <ng-template pTemplate="display"> Click Here </ng-template> <ng-template pTemplate="content"> <p-button>GfG</p-button> </ng-template></p-inplace> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { HttpClientModule } from "@angular/common/http";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { InplaceModule } from "primeng/inplace";import { TableModule } from "primeng/table";import { InputTextModule } from "primeng/inputtext"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, InplaceModule, InputTextModule, TableModule, HttpClientModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/inplace Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n24 Sep, 2021" }, { "code": null, "e": 26762, "s": 26354, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Inplace component in Angular PrimeNG. We will also learn about the properties, events, methods & styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 26922, "s": 26762, "text": "Inplace component: It is used to edit & display the content inplace of others at the same time & render the actual output while clicking the button to display." }, { "code": null, "e": 26934, "s": 26922, "text": "Properties:" }, { "code": null, "e": 27061, "s": 26934, "text": "active: It is used to specify whether the content is displayed or not. It is of boolean datatype & the default value is false." }, { "code": null, "e": 27181, "s": 27061, "text": "disabled: It specifies that the element should be disabled. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27304, "s": 27181, "text": "closable: It Displays a button to switch back to display mode. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27493, "s": 27304, "text": "preventClick: It specifies whether the component can be controlled full programmatic with activate() and deactivate() functions. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27596, "s": 27493, "text": "style: It sets an inline style of the component. It is of string data type, the default value is null." }, { "code": null, "e": 27702, "s": 27596, "text": "styleClass: It is the style class of the component. It is of string data type, the default value is null." }, { "code": null, "e": 27796, "s": 27702, "text": "closeIcon: It is the close icon, It is of string data type, the default value is pi pi-times." }, { "code": null, "e": 27804, "s": 27796, "text": "Events:" }, { "code": null, "e": 27874, "s": 27804, "text": "onActivate: It is a callback that is fired when content is activated." }, { "code": null, "e": 27947, "s": 27874, "text": "onDeactivate: It is a callback that is fired when content is deactivated" }, { "code": null, "e": 27958, "s": 27949, "text": "Methods:" }, { "code": null, "e": 28005, "s": 27958, "text": "activate: It is used to activates the content." }, { "code": null, "e": 28056, "s": 28005, "text": "deactivate: It is used to deactivates the content." }, { "code": null, "e": 28065, "s": 28056, "text": "Styling:" }, { "code": null, "e": 28104, "s": 28065, "text": "p-inplace: It is the Container element" }, { "code": null, "e": 28151, "s": 28104, "text": "p-inplace-display: It is the Display container" }, { "code": null, "e": 28198, "s": 28151, "text": "p-inplace-content: It is the Content container" }, { "code": null, "e": 28250, "s": 28198, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 28317, "s": 28250, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 28332, "s": 28317, "text": "ng new appname" }, { "code": null, "e": 28429, "s": 28332, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28440, "s": 28429, "text": "cd appname" }, { "code": null, "e": 28489, "s": 28440, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28546, "s": 28489, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28598, "s": 28546, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 28717, "s": 28598, "text": "Example 1: This is the basic example that illustrates how to implement the closable property in the Inplace Component." }, { "code": null, "e": 28736, "s": 28717, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Inplace Component</h5><p-inplace closable=\"closable\"> <ng-template pTemplate=\"display\"> Click to Edit </ng-template> <ng-template pTemplate=\"content\"> <input type=\"text\" value=\"GeeksforGeeks\" pInputText /> </ng-template></p-inplace>", "e": 29009, "s": 28736, "text": null }, { "code": null, "e": 29026, "s": 29009, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 29209, "s": 29026, "text": null }, { "code": null, "e": 29223, "s": 29209, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { HttpClientModule } from \"@angular/common/http\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { InplaceModule } from \"primeng/inplace\";import { TableModule } from \"primeng/table\";import { InputTextModule } from \"primeng/inputtext\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, InplaceModule, InputTextModule, TableModule, HttpClientModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 29936, "s": 29223, "text": null }, { "code": null, "e": 29944, "s": 29936, "text": "Output:" }, { "code": null, "e": 30025, "s": 29944, "text": "Example 2: In this example, we are making a button inside the Inplace Component." }, { "code": null, "e": 30044, "s": 30025, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Inplace Component</h5><p-inplace> <ng-template pTemplate=\"display\"> Click Here </ng-template> <ng-template pTemplate=\"content\"> <p-button>GfG</p-button> </ng-template></p-inplace>", "e": 30270, "s": 30044, "text": null }, { "code": null, "e": 30287, "s": 30270, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 30470, "s": 30287, "text": null }, { "code": null, "e": 30484, "s": 30470, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { HttpClientModule } from \"@angular/common/http\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { InplaceModule } from \"primeng/inplace\";import { TableModule } from \"primeng/table\";import { InputTextModule } from \"primeng/inputtext\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, InplaceModule, InputTextModule, TableModule, HttpClientModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 31197, "s": 30484, "text": null }, { "code": null, "e": 31205, "s": 31197, "text": "Output:" }, { "code": null, "e": 31266, "s": 31205, "text": "Reference: https://primefaces.org/primeng/showcase/#/inplace" }, { "code": null, "e": 31282, "s": 31266, "text": "Angular-PrimeNG" }, { "code": null, "e": 31292, "s": 31282, "text": "AngularJS" }, { "code": null, "e": 31309, "s": 31292, "text": "Web Technologies" }, { "code": null, "e": 31407, "s": 31309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31442, "s": 31407, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31477, "s": 31442, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31501, "s": 31477, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31536, "s": 31501, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31589, "s": 31536, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31629, "s": 31589, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31662, "s": 31629, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31707, "s": 31662, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31750, "s": 31707, "text": "How to fetch data from an API in ReactJS ?" } ]
How to write tidy SQL queries in R | by Keith McNulty | Towards Data Science
Most of us have to interact with databases nowadays, and SQL is by far the most common language used. However, working with SQL in R can be messy. If your queries are complex, you have to code them up as text strings which can be error prone, and suffer from formatting challenges. Also, when you want to build your SQL queries to have variables inside them, then you are forced to do substitution or pasting, which is a little bit hacky. Ideally you want to be able to work with your database using tidy principles, taking advantage of the wonders of the tidyverse, and preferably without downloading the entire database into your session first. This is where the magic of dbplyr comes in. dbplyr acts as a SQL translator and allows you to play with databases using tidyverse. So now you can pipe to your hearts content. If you haven’t been using this yet, I would get onto it now. Writing tidy database queries has many advantages. You can understand your work more easily when you come back to it after a while, you can comment more clearly, and it also forces you to think about the most efficient structure for your queries. To work in dbplyr, you set up your database connection in the same way as you normally would in your R session, let’s call it myconn. You will set up database objects in your R session using dbplyr::in_schema(). This takes two arguments: first, the schema you want to access in your database connection, and second, that table you are interested in within that schema. Here’s an example of how to set one up: catdata <- dplyr::tbl( myconn, dbplyr::in_schema("ANIMAL_ANALYSTS", "CAT_TABLE")) Now catdata is a database object. The command above connects to the database and downloads a bare minimum of information on fields, data types, etc. — enough to allow manipulation of the object without physical download of the data. You can now manipulate catdata in the same way as you would manipulate other tables in R. For example: weight_by_age <- catdata %>% dplyr::group_by(AGE) %>% dplyr::summarise(AVG_WT = mean(WT, na.rm = TRUE)) All these manipulations occur without physical download of the data, by translating your code into SQL in the background. Since data download is often the most time consuming step, this allows you to think about how much work you want to get done on the server before you pull the data. When you are ready to pull the data, you just use dplyr::collect(). This will send the background compiled SQL query to the database and execute it. For example: weight_by_age %>% dplyr::rename(`Age of Cat` = AGE, `Average Weight` = AVG_WT) %>% dplyr::collect() dbplyr is highly flexible and I have yet to find a SQL query that I could not rewrite tidy using dbplyr. Joins work by using dplyr ‘s join functions on database objects, for example: fullcatdata <- dplyr::left_join( catregistrationdetails, catdata, by = "SERIAL_NO") %>% dplyr::left_join( cathealthrecord, by = "SERIAL_NO") New columns can be added to the data using dplyr::mutate(), and can even be used for more complex joins. For example, if your cat serial number has a “CAT-” at the beginning in one table but not another: fullcatdata <- catregistrationdetails %>% dplyr::mutate(SERIAL_NO = paste0("CAT-", SERIAL_NO)) %>% dplyr::left_join(catdata, by = "SERIAL_NO") dbplyr cleverly translates R functions into SQL equivalents. You can see what it does using the dbplyr::translate_sql() function. For example: dbplyr::translate_sql(substr(NAME, -3, -1))<SQL> substr("NAME", -3, 3) I find dbplyr also allows me to code more easily in reactive environments. If you were to build a Shiny app that calculates average weight of cats according to an input input$age: weight <- reactive({ catdata %>% dplyr::filter(AGE == input$age) %>% dplyr::select(WT) %>% mean(na.rm = TRUE) %>% dplyr::collect()}) These are just some of the many ways that dbplyr helps you work more tidy in SQL. I highly recommend it. For more information on dbplyr go here. Originally I was a Pure Mathematician, then I became a Psychometrician and a Data Scientist. I am passionate about applying the rigor of all those disciplines to complex people questions. I’m also a coding geek and a massive fan of Japanese RPGs. Find me on LinkedIn or on Twitter.
[ { "code": null, "e": 610, "s": 171, "text": "Most of us have to interact with databases nowadays, and SQL is by far the most common language used. However, working with SQL in R can be messy. If your queries are complex, you have to code them up as text strings which can be error prone, and suffer from formatting challenges. Also, when you want to build your SQL queries to have variables inside them, then you are forced to do substitution or pasting, which is a little bit hacky." }, { "code": null, "e": 862, "s": 610, "text": "Ideally you want to be able to work with your database using tidy principles, taking advantage of the wonders of the tidyverse, and preferably without downloading the entire database into your session first. This is where the magic of dbplyr comes in." }, { "code": null, "e": 1301, "s": 862, "text": "dbplyr acts as a SQL translator and allows you to play with databases using tidyverse. So now you can pipe to your hearts content. If you haven’t been using this yet, I would get onto it now. Writing tidy database queries has many advantages. You can understand your work more easily when you come back to it after a while, you can comment more clearly, and it also forces you to think about the most efficient structure for your queries." }, { "code": null, "e": 1710, "s": 1301, "text": "To work in dbplyr, you set up your database connection in the same way as you normally would in your R session, let’s call it myconn. You will set up database objects in your R session using dbplyr::in_schema(). This takes two arguments: first, the schema you want to access in your database connection, and second, that table you are interested in within that schema. Here’s an example of how to set one up:" }, { "code": null, "e": 1794, "s": 1710, "text": "catdata <- dplyr::tbl( myconn, dbplyr::in_schema(\"ANIMAL_ANALYSTS\", \"CAT_TABLE\"))" }, { "code": null, "e": 2027, "s": 1794, "text": "Now catdata is a database object. The command above connects to the database and downloads a bare minimum of information on fields, data types, etc. — enough to allow manipulation of the object without physical download of the data." }, { "code": null, "e": 2130, "s": 2027, "text": "You can now manipulate catdata in the same way as you would manipulate other tables in R. For example:" }, { "code": null, "e": 2236, "s": 2130, "text": "weight_by_age <- catdata %>% dplyr::group_by(AGE) %>% dplyr::summarise(AVG_WT = mean(WT, na.rm = TRUE))" }, { "code": null, "e": 2523, "s": 2236, "text": "All these manipulations occur without physical download of the data, by translating your code into SQL in the background. Since data download is often the most time consuming step, this allows you to think about how much work you want to get done on the server before you pull the data." }, { "code": null, "e": 2685, "s": 2523, "text": "When you are ready to pull the data, you just use dplyr::collect(). This will send the background compiled SQL query to the database and execute it. For example:" }, { "code": null, "e": 2803, "s": 2685, "text": "weight_by_age %>% dplyr::rename(`Age of Cat` = AGE, `Average Weight` = AVG_WT) %>% dplyr::collect() " }, { "code": null, "e": 2908, "s": 2803, "text": "dbplyr is highly flexible and I have yet to find a SQL query that I could not rewrite tidy using dbplyr." }, { "code": null, "e": 2986, "s": 2908, "text": "Joins work by using dplyr ‘s join functions on database objects, for example:" }, { "code": null, "e": 3140, "s": 2986, "text": "fullcatdata <- dplyr::left_join( catregistrationdetails, catdata, by = \"SERIAL_NO\") %>% dplyr::left_join( cathealthrecord, by = \"SERIAL_NO\")" }, { "code": null, "e": 3344, "s": 3140, "text": "New columns can be added to the data using dplyr::mutate(), and can even be used for more complex joins. For example, if your cat serial number has a “CAT-” at the beginning in one table but not another:" }, { "code": null, "e": 3490, "s": 3344, "text": " fullcatdata <- catregistrationdetails %>% dplyr::mutate(SERIAL_NO = paste0(\"CAT-\", SERIAL_NO)) %>% dplyr::left_join(catdata, by = \"SERIAL_NO\")" }, { "code": null, "e": 3633, "s": 3490, "text": "dbplyr cleverly translates R functions into SQL equivalents. You can see what it does using the dbplyr::translate_sql() function. For example:" }, { "code": null, "e": 3704, "s": 3633, "text": "dbplyr::translate_sql(substr(NAME, -3, -1))<SQL> substr(\"NAME\", -3, 3)" }, { "code": null, "e": 3884, "s": 3704, "text": "I find dbplyr also allows me to code more easily in reactive environments. If you were to build a Shiny app that calculates average weight of cats according to an input input$age:" }, { "code": null, "e": 4022, "s": 3884, "text": "weight <- reactive({ catdata %>% dplyr::filter(AGE == input$age) %>% dplyr::select(WT) %>% mean(na.rm = TRUE) %>% dplyr::collect()})" }, { "code": null, "e": 4127, "s": 4022, "text": "These are just some of the many ways that dbplyr helps you work more tidy in SQL. I highly recommend it." }, { "code": null, "e": 4167, "s": 4127, "text": "For more information on dbplyr go here." } ]
Object detection with neural networks — a simple tutorial using keras | by Johannes Rieke | Towards Data Science
TLDR: A very lightweight tutorial to object detection in images. We will bootstrap simple images and apply increasingly complex neural networks to them. In the end, the algorithm will be able to detect multiple objects of varying shapes and colors (image below). You should have a basic understanding of neural networks to follow along. Image analysis is one of the most prominent fields in deep learning. Images are easy to generate and handle, and they are exactly the right type of data for machine learning: easy to understand for human beings, but difficult for computers. Not surprisingly, image analysis played a key role in the history of deep neural networks. In this blog post, we’ll look at object detection — finding out which objects are in an image. For example, imagine a self-driving car that needs to detect other cars on the road. There are lots of complicated algorithms for object detection. They often require huge datasets, very deep convolutional networks and long training times. To make this tutorial easy to follow along, we’ll apply two simplifications: 1) We don’t use real photographs, but images with abstract geometric shapes. This allows us to bootstrap the image data and use simpler neural networks. 2) We predict a fixed number of objects in each image. This makes the entire algorithm a lot, lot easier (it’s actually surprisingly simple besides a few tricks). At the end of the post, I will outline how one can expand on this approach to detect many more objects in an image. I tried to make this tutorial as simple as possible: I will go step by step, starting with detection of a single object. For each step, there’s a Jupyter notebook with the complete code in this github repo. You don’t need to download any additional dataset. The code is in Python plus keras, so the networks should be easy to understand even for beginners. Also, the networks I use are (mostly) very simple feedforward networks, so you can train them within minutes. Detecting a single object Let’s start simple: We will predict the bounding box of a single rectangle. To construct the “images”, I created a bunch of 8x8 numpy arrays, set the background to 0, and a random rectangle within the array to 1. Here are a few examples (white is 0, black is 1): The neural network is a very simple feedforward network with one hidden layer (no convolutions, nothing fancy). It takes the flattened image (i.e. 8 x 8 = 64 values) as input, and predicts the parameters of the bounding box (i.e. the coordinates x and y of the lower left corner, the width w and the height h). During training, we simply do a regression of the predicted to the expected bounding boxes via mean squared error (MSE). I used adadelta as an optimizer here — it’s basically standard stochastic gradient descent, but with an adaptive learning rate. It’s a really great choice for experimentation, because you don’t need to spend a lot of time on hyperparameter optimization. Here’s how the network is implemented in keras: model = Sequential([ Dense(200, input_dim=64), Activation('relu'), Dropout(0.2), Dense(4) ])model.compile('adadelta', 'mse') I trained this network with 40k random images for 50 epochs (~1 minute on my laptop’s CPU) and got almost perfect results. Here are the predicted bounding boxes on the images above (they were held out during training): Quite good, isn’t it? You can see that I also plotted the IOU values above each bounding box: This index is called Intersection Over Union and measures the overlap between the predicted and the real bounding box. It’s calculated by dividing the area of intersection (red in the image below) by the area of union (blue). The IOU is between 0 (no overlap) and 1 (perfect overlap). In the experiment above, I got an almost perfect IOU of 0.9 on average (on held-out test data). The code for this section is in this Jupyter notebook. Detecting multiple objects Predicting a single object isn’t that much fun, so let’s add another rectangle. Basically, we use the same approach as above: Bootstrap the images with 8x8 numpy arrays and train a feedforward neural network to predict two bounding boxes (i.e. a vector x1, y1, w1, h1, x2, y2, w2, h2). However, if we just go ahead and do this, we get the following (quite disappointing) result: Both bounding boxes seem to be in the middle of the rectangles. What happened? Imagine the following situation: We train our network on the leftmost image in the plot above. Let’s say that the expected bounding box of the left rectangle is at position 1 in the target vector (x1, y1, w1, h1), and the expected bounding box of the right rectangle is at position 2 in the vector (x2, y2, w2, h2). Apparently, our optimizer will change the parameters of the network so that the first predictor moves to the left, and the second predictor moves to the right. Imagine now that a bit later we come across a similar image, but this time the positions in the target vector are swapped (i.e. left rectangle at position 2, right rectangle at position 1). Now, our optimizer will pull predictor 1 to the right and predictor 2 to the left — exactly the opposite of the previous update step! In effect, the predicted bounding boxes stay in the center. And as we have a huge dataset (40k images), there will be quite a lot of such “duplicates”. The solution is to “assign” each predicted bounding box to a rectangle during training. Then, the predictors can learn to specialize on certain locations and/or shapes of rectangles. In order to do this, we process the target vectors after every epoch: For each training image, we calculate the mean squared error between the prediction and the target A) for the current order of bounding boxes in the target vector (i.e. x1, y1, w1, h1, x2, y2, w2, h2) and B) if the bounding boxes in the target vector are flipped (i.e. x2, y2, w2, h2, x1, y1, w1, h1). If the MSE of A is lower than B, we leave the target vector as is; if the MSE of B is lower than A, we flip the vector. I’ve implemented this algorithm here. Below is a visualization of the flipping process: Each row in the plot above is a sample from the training set. From left to right are the epochs of the training process. Black means that the target vector was flipped after this epoch, white means no flip. You can see nicely that most flips occur at the beginning of training, when the predictors haven’t specialized yet. If we train our network with flipping enabled, we get the following results (again on held-out test images): Overall, the network achieves a mean IOU of 0.5 on the training data (I haven’t calculated the one for the test dataset, but it should be pretty similar). Not as perfect as for a single rectangle, but pretty good (especially considering that it’s such a simple network). Note that the leftmost image is the same as in the plot before (the one without flipping) — you can clearly see that the predictors have learned to specialize on the rectangles. Finally, two more notes on the flipping algorithm: Firstly, the approach presented above is of course only valid for two rectangles. However, you can easily extend it to multiple rectangles by looking at all possible combinations of predictors and rectangles (I will explain this in some more detail below). Secondly, you don’t necessarily have to use the mean squared error to decide whether the target should be flipped or not — you can as well use the IOU or even the distance between the bounding boxes. In my experiments, all three metrics led to pretty similar results, so I decided to stick to the MSE as most people should be familiar with it. Classifying objects Detecting objects works pretty well by now, but of course we also want to say what an object is. Therefore, we’ll add triangles and classify whether an object is a rectangle or a triangle. The cool thing is that we don’t need any extra algorithm or workflow for this. We’ll use the exact same network as above and just add one value per bounding box to the target vector: 0 if the object is a rectangle, and 1 if it’s a triangle (i.e. binary classification; code is here). Here are the results (I increased the image size to 16x16 so that small triangles are easier to recognize): A red bounding box means the network predicted a rectangle, and yellow means it predicted a triangle. The samples already indicate that classification works pretty well, and indeed we get an almost perfect classification accuracy. Putting it all together: Shapes, Colors, and Convolutional Neural Networks Alright, everything works, so let’s have some fun now: We’ll apply the method to some more “realistic” scenes — that means: different colors, more shapes, and multiple objects at once. To bootstrap the images, I used the pycairo library, which can write RGB images and simple shapes to numpy arrays. I also made some modifications to the network itself, but let’s first have a look at the results: As you can see, the bounding boxes aren’t perfect, but most of the time they are kind of in the right place. The mean IOU on the test dataset is around 0.4, which is not bad for recognizing three objects at once. The predicted shapes and colors (written above the bounding boxes) are pretty much perfect (test accuracy of 95 %). Apparently, the network has really learned to assign the predictors to different objects (as we aimed for with the flipping trick introduced above). In comparison to the simple experiments above, I made three modifications: 1) I used a convolutional neural network (CNN) instead of a feedforward network. CNNs scan the image with learnable “filters” and extract more and more abstract features at each layer. Filters in early layers may for example detect edges or color gradients, while later layers may register complex shapes. I won’t go into the technical details here, but you can find excellent introductions in the lectures from Stanford’s CS231n class or this chapter from Michael Nielsen’s book. For the results shown above, I trained a network with four convolutional and two pooling layers for about 30–40 minutes. A deeper/more optimized/longer trained network might probably get better results. 2) I didn’t use a single (binary) value for classification, but one-hot vectors (0 everywhere, 1 at the index of the class). Specifically, I used one vector per object to classify shape (rectangle, triangle or circle) and one vector to classify color (red, green or blue). Note that I added some random variation to the colors in the input images to see if the network can handle this. All in all, the target vector for an image consists of 10 values for each object (4 for the bounding box, 3 for the shape classification, and 3 for the color classification). 3) I adapted the flipping algorithm to work with multiple bounding boxes (as mentioned above). After each epoch, the algorithm calculates the mean squared error for all combinations of one predicted and one expected bounding box. Then, it takes the minimum of those values, assigns the corresponding predicted and expected bounding boxes to each other, takes the next smallest value out of the boxes that were not assigned yet, and so on. You can find the final code in this notebook. Real-world objects Recognizing shapes is a cool and easy example, but obviously it’s not what you want to do in the real world (there aren’t that many abstract 2D shapes in nature, unfortunately). Also, our algorithm can only predict a fixed number of bounding boxes per image. In the real world, however, you have diverse scenarios: A small side road may have no cars on it, but as soon as you drive on the highway, you have to recognize hundreds of cars at the same time. Even though this seems like a minor issue, it’s actually pretty hard to solve — how should the algorithm decide what’s an object and what’s background, if it doesn’t know how many objects there are? Imagine yourself looking at a tree from close by: Even though you only see a bunch of leaves and sticks, you can still clearly say it’s all one object, because you understand what a tree is. If the leaves were lying around on the floor instead, you would easily detect them as individual objects. Unfortunately, neural networks don’t quite understand what trees are, so this is a pretty hard challenge for them. Out of the many algorithms that do object detection on a variable number of objects (e.g. Overfeat or R-CNN; have a look at this lecture for an overview), I only want to highlight one, because it’s pretty similar to the method we used above: It’s called YOLO (You Only Look Once). In contrast to older approaches, it detects objects in an image with a single pass through a neural network. In short, it divides the image into a grid, predicts two bounding boxes for each grid cell (i.e. exactly the same thing we did above), and then tries to find the best bounding boxes across the entire image. Because YOLO only needs a single pass through a network, it’s super fast and even works on videos. Below is a demo, and you can see more examples here. If you want to stay updated about my work, please follow me on Twitter (@jrieke)! You can also have a look at some other projects on my website.
[ { "code": null, "e": 509, "s": 172, "text": "TLDR: A very lightweight tutorial to object detection in images. We will bootstrap simple images and apply increasingly complex neural networks to them. In the end, the algorithm will be able to detect multiple objects of varying shapes and colors (image below). You should have a basic understanding of neural networks to follow along." }, { "code": null, "e": 841, "s": 509, "text": "Image analysis is one of the most prominent fields in deep learning. Images are easy to generate and handle, and they are exactly the right type of data for machine learning: easy to understand for human beings, but difficult for computers. Not surprisingly, image analysis played a key role in the history of deep neural networks." }, { "code": null, "e": 1685, "s": 841, "text": "In this blog post, we’ll look at object detection — finding out which objects are in an image. For example, imagine a self-driving car that needs to detect other cars on the road. There are lots of complicated algorithms for object detection. They often require huge datasets, very deep convolutional networks and long training times. To make this tutorial easy to follow along, we’ll apply two simplifications: 1) We don’t use real photographs, but images with abstract geometric shapes. This allows us to bootstrap the image data and use simpler neural networks. 2) We predict a fixed number of objects in each image. This makes the entire algorithm a lot, lot easier (it’s actually surprisingly simple besides a few tricks). At the end of the post, I will outline how one can expand on this approach to detect many more objects in an image." }, { "code": null, "e": 2152, "s": 1685, "text": "I tried to make this tutorial as simple as possible: I will go step by step, starting with detection of a single object. For each step, there’s a Jupyter notebook with the complete code in this github repo. You don’t need to download any additional dataset. The code is in Python plus keras, so the networks should be easy to understand even for beginners. Also, the networks I use are (mostly) very simple feedforward networks, so you can train them within minutes." }, { "code": null, "e": 2178, "s": 2152, "text": "Detecting a single object" }, { "code": null, "e": 2441, "s": 2178, "text": "Let’s start simple: We will predict the bounding box of a single rectangle. To construct the “images”, I created a bunch of 8x8 numpy arrays, set the background to 0, and a random rectangle within the array to 1. Here are a few examples (white is 0, black is 1):" }, { "code": null, "e": 3175, "s": 2441, "text": "The neural network is a very simple feedforward network with one hidden layer (no convolutions, nothing fancy). It takes the flattened image (i.e. 8 x 8 = 64 values) as input, and predicts the parameters of the bounding box (i.e. the coordinates x and y of the lower left corner, the width w and the height h). During training, we simply do a regression of the predicted to the expected bounding boxes via mean squared error (MSE). I used adadelta as an optimizer here — it’s basically standard stochastic gradient descent, but with an adaptive learning rate. It’s a really great choice for experimentation, because you don’t need to spend a lot of time on hyperparameter optimization. Here’s how the network is implemented in keras:" }, { "code": null, "e": 3334, "s": 3175, "text": "model = Sequential([ Dense(200, input_dim=64), Activation('relu'), Dropout(0.2), Dense(4) ])model.compile('adadelta', 'mse')" }, { "code": null, "e": 3553, "s": 3334, "text": "I trained this network with 40k random images for 50 epochs (~1 minute on my laptop’s CPU) and got almost perfect results. Here are the predicted bounding boxes on the images above (they were held out during training):" }, { "code": null, "e": 4083, "s": 3553, "text": "Quite good, isn’t it? You can see that I also plotted the IOU values above each bounding box: This index is called Intersection Over Union and measures the overlap between the predicted and the real bounding box. It’s calculated by dividing the area of intersection (red in the image below) by the area of union (blue). The IOU is between 0 (no overlap) and 1 (perfect overlap). In the experiment above, I got an almost perfect IOU of 0.9 on average (on held-out test data). The code for this section is in this Jupyter notebook." }, { "code": null, "e": 4110, "s": 4083, "text": "Detecting multiple objects" }, { "code": null, "e": 4489, "s": 4110, "text": "Predicting a single object isn’t that much fun, so let’s add another rectangle. Basically, we use the same approach as above: Bootstrap the images with 8x8 numpy arrays and train a feedforward neural network to predict two bounding boxes (i.e. a vector x1, y1, w1, h1, x2, y2, w2, h2). However, if we just go ahead and do this, we get the following (quite disappointing) result:" }, { "code": null, "e": 5520, "s": 4489, "text": "Both bounding boxes seem to be in the middle of the rectangles. What happened? Imagine the following situation: We train our network on the leftmost image in the plot above. Let’s say that the expected bounding box of the left rectangle is at position 1 in the target vector (x1, y1, w1, h1), and the expected bounding box of the right rectangle is at position 2 in the vector (x2, y2, w2, h2). Apparently, our optimizer will change the parameters of the network so that the first predictor moves to the left, and the second predictor moves to the right. Imagine now that a bit later we come across a similar image, but this time the positions in the target vector are swapped (i.e. left rectangle at position 2, right rectangle at position 1). Now, our optimizer will pull predictor 1 to the right and predictor 2 to the left — exactly the opposite of the previous update step! In effect, the predicted bounding boxes stay in the center. And as we have a huge dataset (40k images), there will be quite a lot of such “duplicates”." }, { "code": null, "e": 6283, "s": 5520, "text": "The solution is to “assign” each predicted bounding box to a rectangle during training. Then, the predictors can learn to specialize on certain locations and/or shapes of rectangles. In order to do this, we process the target vectors after every epoch: For each training image, we calculate the mean squared error between the prediction and the target A) for the current order of bounding boxes in the target vector (i.e. x1, y1, w1, h1, x2, y2, w2, h2) and B) if the bounding boxes in the target vector are flipped (i.e. x2, y2, w2, h2, x1, y1, w1, h1). If the MSE of A is lower than B, we leave the target vector as is; if the MSE of B is lower than A, we flip the vector. I’ve implemented this algorithm here. Below is a visualization of the flipping process:" }, { "code": null, "e": 6606, "s": 6283, "text": "Each row in the plot above is a sample from the training set. From left to right are the epochs of the training process. Black means that the target vector was flipped after this epoch, white means no flip. You can see nicely that most flips occur at the beginning of training, when the predictors haven’t specialized yet." }, { "code": null, "e": 6715, "s": 6606, "text": "If we train our network with flipping enabled, we get the following results (again on held-out test images):" }, { "code": null, "e": 7164, "s": 6715, "text": "Overall, the network achieves a mean IOU of 0.5 on the training data (I haven’t calculated the one for the test dataset, but it should be pretty similar). Not as perfect as for a single rectangle, but pretty good (especially considering that it’s such a simple network). Note that the leftmost image is the same as in the plot before (the one without flipping) — you can clearly see that the predictors have learned to specialize on the rectangles." }, { "code": null, "e": 7816, "s": 7164, "text": "Finally, two more notes on the flipping algorithm: Firstly, the approach presented above is of course only valid for two rectangles. However, you can easily extend it to multiple rectangles by looking at all possible combinations of predictors and rectangles (I will explain this in some more detail below). Secondly, you don’t necessarily have to use the mean squared error to decide whether the target should be flipped or not — you can as well use the IOU or even the distance between the bounding boxes. In my experiments, all three metrics led to pretty similar results, so I decided to stick to the MSE as most people should be familiar with it." }, { "code": null, "e": 7836, "s": 7816, "text": "Classifying objects" }, { "code": null, "e": 8309, "s": 7836, "text": "Detecting objects works pretty well by now, but of course we also want to say what an object is. Therefore, we’ll add triangles and classify whether an object is a rectangle or a triangle. The cool thing is that we don’t need any extra algorithm or workflow for this. We’ll use the exact same network as above and just add one value per bounding box to the target vector: 0 if the object is a rectangle, and 1 if it’s a triangle (i.e. binary classification; code is here)." }, { "code": null, "e": 8417, "s": 8309, "text": "Here are the results (I increased the image size to 16x16 so that small triangles are easier to recognize):" }, { "code": null, "e": 8648, "s": 8417, "text": "A red bounding box means the network predicted a rectangle, and yellow means it predicted a triangle. The samples already indicate that classification works pretty well, and indeed we get an almost perfect classification accuracy." }, { "code": null, "e": 8723, "s": 8648, "text": "Putting it all together: Shapes, Colors, and Convolutional Neural Networks" }, { "code": null, "e": 9121, "s": 8723, "text": "Alright, everything works, so let’s have some fun now: We’ll apply the method to some more “realistic” scenes — that means: different colors, more shapes, and multiple objects at once. To bootstrap the images, I used the pycairo library, which can write RGB images and simple shapes to numpy arrays. I also made some modifications to the network itself, but let’s first have a look at the results:" }, { "code": null, "e": 9599, "s": 9121, "text": "As you can see, the bounding boxes aren’t perfect, but most of the time they are kind of in the right place. The mean IOU on the test dataset is around 0.4, which is not bad for recognizing three objects at once. The predicted shapes and colors (written above the bounding boxes) are pretty much perfect (test accuracy of 95 %). Apparently, the network has really learned to assign the predictors to different objects (as we aimed for with the flipping trick introduced above)." }, { "code": null, "e": 9674, "s": 9599, "text": "In comparison to the simple experiments above, I made three modifications:" }, { "code": null, "e": 10358, "s": 9674, "text": "1) I used a convolutional neural network (CNN) instead of a feedforward network. CNNs scan the image with learnable “filters” and extract more and more abstract features at each layer. Filters in early layers may for example detect edges or color gradients, while later layers may register complex shapes. I won’t go into the technical details here, but you can find excellent introductions in the lectures from Stanford’s CS231n class or this chapter from Michael Nielsen’s book. For the results shown above, I trained a network with four convolutional and two pooling layers for about 30–40 minutes. A deeper/more optimized/longer trained network might probably get better results." }, { "code": null, "e": 10919, "s": 10358, "text": "2) I didn’t use a single (binary) value for classification, but one-hot vectors (0 everywhere, 1 at the index of the class). Specifically, I used one vector per object to classify shape (rectangle, triangle or circle) and one vector to classify color (red, green or blue). Note that I added some random variation to the colors in the input images to see if the network can handle this. All in all, the target vector for an image consists of 10 values for each object (4 for the bounding box, 3 for the shape classification, and 3 for the color classification)." }, { "code": null, "e": 11358, "s": 10919, "text": "3) I adapted the flipping algorithm to work with multiple bounding boxes (as mentioned above). After each epoch, the algorithm calculates the mean squared error for all combinations of one predicted and one expected bounding box. Then, it takes the minimum of those values, assigns the corresponding predicted and expected bounding boxes to each other, takes the next smallest value out of the boxes that were not assigned yet, and so on." }, { "code": null, "e": 11404, "s": 11358, "text": "You can find the final code in this notebook." }, { "code": null, "e": 11423, "s": 11404, "text": "Real-world objects" }, { "code": null, "e": 11878, "s": 11423, "text": "Recognizing shapes is a cool and easy example, but obviously it’s not what you want to do in the real world (there aren’t that many abstract 2D shapes in nature, unfortunately). Also, our algorithm can only predict a fixed number of bounding boxes per image. In the real world, however, you have diverse scenarios: A small side road may have no cars on it, but as soon as you drive on the highway, you have to recognize hundreds of cars at the same time." }, { "code": null, "e": 12489, "s": 11878, "text": "Even though this seems like a minor issue, it’s actually pretty hard to solve — how should the algorithm decide what’s an object and what’s background, if it doesn’t know how many objects there are? Imagine yourself looking at a tree from close by: Even though you only see a bunch of leaves and sticks, you can still clearly say it’s all one object, because you understand what a tree is. If the leaves were lying around on the floor instead, you would easily detect them as individual objects. Unfortunately, neural networks don’t quite understand what trees are, so this is a pretty hard challenge for them." }, { "code": null, "e": 13238, "s": 12489, "text": "Out of the many algorithms that do object detection on a variable number of objects (e.g. Overfeat or R-CNN; have a look at this lecture for an overview), I only want to highlight one, because it’s pretty similar to the method we used above: It’s called YOLO (You Only Look Once). In contrast to older approaches, it detects objects in an image with a single pass through a neural network. In short, it divides the image into a grid, predicts two bounding boxes for each grid cell (i.e. exactly the same thing we did above), and then tries to find the best bounding boxes across the entire image. Because YOLO only needs a single pass through a network, it’s super fast and even works on videos. Below is a demo, and you can see more examples here." } ]
Math.Floor() Method in C#
The Math.Floor() method in C# is used to return the largest integral value less than or equal to the specified number. public static decimal Floor (decimal val); public static double Floor (double val) For the first syntax above, the value val is the decimal number, whereas Val in the second syntax is the double number. Let us now see an example to implement Math.Floor() method − using System; public class Demo { public static void Main(){ decimal val1 = 7.10M; decimal val2 = -79.89M; Console.WriteLine("Result = " + Math.Floor(val1)); Console.WriteLine("Result = " + Math.Floor(val2)); } } This will produce the following output − Result = 7 Result = -80 Let us see another example to implement Math.Floor() method − using System; public class Demo { public static void Main(){ double val1 = 8.9; double val2 = 88.10; double val3 = -31.98; Console.WriteLine("Result = " + Math.Floor(val1)); Console.WriteLine("Result = " + Math.Floor(val2)); Console.WriteLine("Result = " + Math.Floor(val3)); } } This will produce the following output − Result = 8 Result = 88 Result = -32
[ { "code": null, "e": 1181, "s": 1062, "text": "The Math.Floor() method in C# is used to return the largest integral value less than or equal to the specified number." }, { "code": null, "e": 1264, "s": 1181, "text": "public static decimal Floor (decimal val);\npublic static double Floor (double val)" }, { "code": null, "e": 1384, "s": 1264, "text": "For the first syntax above, the value val is the decimal number, whereas Val in the second syntax is the double number." }, { "code": null, "e": 1445, "s": 1384, "text": "Let us now see an example to implement Math.Floor() method −" }, { "code": null, "e": 1688, "s": 1445, "text": "using System;\npublic class Demo {\n public static void Main(){\n decimal val1 = 7.10M;\n decimal val2 = -79.89M;\n Console.WriteLine(\"Result = \" + Math.Floor(val1));\n Console.WriteLine(\"Result = \" + Math.Floor(val2));\n }\n}" }, { "code": null, "e": 1729, "s": 1688, "text": "This will produce the following output −" }, { "code": null, "e": 1753, "s": 1729, "text": "Result = 7\nResult = -80" }, { "code": null, "e": 1815, "s": 1753, "text": "Let us see another example to implement Math.Floor() method −" }, { "code": null, "e": 2137, "s": 1815, "text": "using System;\npublic class Demo {\n public static void Main(){\n double val1 = 8.9;\n double val2 = 88.10;\n double val3 = -31.98;\n Console.WriteLine(\"Result = \" + Math.Floor(val1));\n Console.WriteLine(\"Result = \" + Math.Floor(val2));\n Console.WriteLine(\"Result = \" + Math.Floor(val3));\n }\n}" }, { "code": null, "e": 2178, "s": 2137, "text": "This will produce the following output −" }, { "code": null, "e": 2214, "s": 2178, "text": "Result = 8\nResult = 88\nResult = -32" } ]
Quick ML Concepts: Tensors. Tensorflow, Tensorlab, Deep Tensorized... | by Enoch Kan | Towards Data Science
Tensorflow, Tensorlab, Deep Tensorized Networks, Tensorized LSTMs... it’s no surprise that the word “tensor” is embedded in the names of many machine learning technologies. But what are tensors? And how do they relate to machine learning? In part one of Quick ML Concepts, I aim to provide a short yet concise summary of what tensors are. Don’t let the word “tensor” scare you. It is nothing more than a simple mathematical concept. Tensors are mathematical objects that generalize scalars, vectors and matrices to higher dimensions. If you are familiar with basic linear algebra, you should have no trouble understanding what tensors are. In short, a single-dimensional tensor can be represented as a vector. A two-dimensional tensor, as you may have guessed, can be represented as a matrix. Even though it’s easy to generalize tensors as multi-dimensional matrices ranging from zero to N dimensions, it is important to remember that tensors are dynamic. That is, tensors will transform when interacting with other mathematical entities. Matrices, on the other hand, don’t always have this property. As quoted from Steven Steinke’s wonderful article about the fundamental differences between tensors and matrices: any rank-2 tensor can be represented as a matrix, but not every matrix is really a rank-2 tensor. Tensor operations are simple. Consider the following tensors: a = np.array([[[4,1,2], [3,5,2], [1,6,7]] [[2,1,0], [5,4,3], [6,8,9]] [[1,2,3], [2,3,4], [5,5,5]]])b = np.array([[[1,1,1], [2,2,2], [3,3,3]] [[4,4,4], [5,5,5], [6,6,6]] [[7,7,7], [8,8,8], [9,9,9]]]) It is very easy to see that both tensors are of rank 3. That is, they have 3 axes. You can check a tensor’s dimension by the following code in Python a.ndim>>> 3 Addition of the above two tensors results in a tensor in which each scalar value is the element-wise addition of scalars in the parent tensors. print(a+b)>>> [[[5,2,3], [5,7,4], [4,9,10]] [[6,5,4], [10,9,8], [12,14,15]] [[8,10,11], [10,11,12], [14,14,14]]] If you are interested in learning more about tensor operations, Jason Brownlee’s excellent tensor tutorial has summarized a few commonly seen tensor operations including tensor dot and Hadamart products. So how are tensors related to machine learning? Remember, most machines cannot learn without having any data. And modern data is often multi-dimensional. Tensors can play an important role in ML by encoding multi-dimensional data. For example, a picture is generally represented by three fields: width, height and depth (color). It makes total sense to encode it as a 3D tensor. However, more than often we are dealing with tens of thousands of pictures. Hence this is where the forth field, sample size comes into play. A series of images, such as the famous MNIST dataset, can be easily stored in a 4D tensor in Tensorflow. This representation allows problems involving big data to be solved easily. A real-life example would be in most recommender systems, model-based Collaborative Filtering approaches such as Matrix Factorization do not the flexibility of integrating context information into the models. By using a N-dimensional tensor instead of the traditional 2D User-Item matrix, researchers have developed a more robust model that provides context-aware recommendations. Increase in computing power in the recent years also allows these heavy tensor operations to be realized. At this point you may wonder: why do most machine learning algorithms rely on vectors and matrices, while deep learning algorithms and neural networks mostly rely on tensors? A simple answer is that deep learning usually involves hundreds, if not thousands, of dimensions and fields. As we discussed previously, this is best represented by tensors since they can represent anything ranging from zero to N dimensions. In computer vision problems such as the Merck Molecular Activity Challenge, images can easily be broken down into a few hundred features. Therefore, tensors can be best viewed as containers that wrap and store data features in the context of machine learning and deep learning. Thanks for reading my article.
[ { "code": null, "e": 511, "s": 172, "text": "Tensorflow, Tensorlab, Deep Tensorized Networks, Tensorized LSTMs... it’s no surprise that the word “tensor” is embedded in the names of many machine learning technologies. But what are tensors? And how do they relate to machine learning? In part one of Quick ML Concepts, I aim to provide a short yet concise summary of what tensors are." }, { "code": null, "e": 965, "s": 511, "text": "Don’t let the word “tensor” scare you. It is nothing more than a simple mathematical concept. Tensors are mathematical objects that generalize scalars, vectors and matrices to higher dimensions. If you are familiar with basic linear algebra, you should have no trouble understanding what tensors are. In short, a single-dimensional tensor can be represented as a vector. A two-dimensional tensor, as you may have guessed, can be represented as a matrix." }, { "code": null, "e": 1485, "s": 965, "text": "Even though it’s easy to generalize tensors as multi-dimensional matrices ranging from zero to N dimensions, it is important to remember that tensors are dynamic. That is, tensors will transform when interacting with other mathematical entities. Matrices, on the other hand, don’t always have this property. As quoted from Steven Steinke’s wonderful article about the fundamental differences between tensors and matrices: any rank-2 tensor can be represented as a matrix, but not every matrix is really a rank-2 tensor." }, { "code": null, "e": 1547, "s": 1485, "text": "Tensor operations are simple. Consider the following tensors:" }, { "code": null, "e": 1970, "s": 1547, "text": "a = np.array([[[4,1,2], [3,5,2], [1,6,7]] [[2,1,0], [5,4,3], [6,8,9]] [[1,2,3], [2,3,4], [5,5,5]]])b = np.array([[[1,1,1], [2,2,2], [3,3,3]] [[4,4,4], [5,5,5], [6,6,6]] [[7,7,7], [8,8,8], [9,9,9]]])" }, { "code": null, "e": 2120, "s": 1970, "text": "It is very easy to see that both tensors are of rank 3. That is, they have 3 axes. You can check a tensor’s dimension by the following code in Python" }, { "code": null, "e": 2132, "s": 2120, "text": "a.ndim>>> 3" }, { "code": null, "e": 2276, "s": 2132, "text": "Addition of the above two tensors results in a tensor in which each scalar value is the element-wise addition of scalars in the parent tensors." }, { "code": null, "e": 2429, "s": 2276, "text": "print(a+b)>>> [[[5,2,3], [5,7,4], [4,9,10]] [[6,5,4], [10,9,8], [12,14,15]] [[8,10,11], [10,11,12], [14,14,14]]]" }, { "code": null, "e": 2633, "s": 2429, "text": "If you are interested in learning more about tensor operations, Jason Brownlee’s excellent tensor tutorial has summarized a few commonly seen tensor operations including tensor dot and Hadamart products." }, { "code": null, "e": 2681, "s": 2633, "text": "So how are tensors related to machine learning?" }, { "code": null, "e": 3335, "s": 2681, "text": "Remember, most machines cannot learn without having any data. And modern data is often multi-dimensional. Tensors can play an important role in ML by encoding multi-dimensional data. For example, a picture is generally represented by three fields: width, height and depth (color). It makes total sense to encode it as a 3D tensor. However, more than often we are dealing with tens of thousands of pictures. Hence this is where the forth field, sample size comes into play. A series of images, such as the famous MNIST dataset, can be easily stored in a 4D tensor in Tensorflow. This representation allows problems involving big data to be solved easily." }, { "code": null, "e": 3822, "s": 3335, "text": "A real-life example would be in most recommender systems, model-based Collaborative Filtering approaches such as Matrix Factorization do not the flexibility of integrating context information into the models. By using a N-dimensional tensor instead of the traditional 2D User-Item matrix, researchers have developed a more robust model that provides context-aware recommendations. Increase in computing power in the recent years also allows these heavy tensor operations to be realized." }, { "code": null, "e": 4517, "s": 3822, "text": "At this point you may wonder: why do most machine learning algorithms rely on vectors and matrices, while deep learning algorithms and neural networks mostly rely on tensors? A simple answer is that deep learning usually involves hundreds, if not thousands, of dimensions and fields. As we discussed previously, this is best represented by tensors since they can represent anything ranging from zero to N dimensions. In computer vision problems such as the Merck Molecular Activity Challenge, images can easily be broken down into a few hundred features. Therefore, tensors can be best viewed as containers that wrap and store data features in the context of machine learning and deep learning." } ]
How does default virtual behavior differ in C++ and Java ? - GeeksforGeeks
22 Mar, 2017 Default virtual behavior of methods is opposite in C++ and Java: In C++, class member methods are non-virtual by default. They can be made virtual by using virtual keyword. For example, Base::show() is non-virtual in following program and program prints “Base::show() called”. #include<iostream> using namespace std; class Base {public: // non-virtual by default void show() { cout<<"Base::show() called"; }}; class Derived: public Base {public: void show() { cout<<"Derived::show() called"; } }; int main(){ Derived d; Base &b = d; b.show(); getchar(); return 0;} Adding virtual before definition of Base::show() makes program print “Derived::show() called” In Java, methods are virtual by default and can be made non-virtual by using final keyword. For example, in the following java program, show() is by default virtual and the program prints “Derived::show() called” class Base { // virtual by default public void show() { System.out.println("Base::show() called"); }} class Derived extends Base { public void show() { System.out.println("Derived::show() called"); }} public class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); }} Unlike C++ non-virtual behavior, if we add final before definition of show() in Base , then the above program fails in compilation. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java
[ { "code": null, "e": 24306, "s": 24278, "text": "\n22 Mar, 2017" }, { "code": null, "e": 24371, "s": 24306, "text": "Default virtual behavior of methods is opposite in C++ and Java:" }, { "code": null, "e": 24583, "s": 24371, "text": "In C++, class member methods are non-virtual by default. They can be made virtual by using virtual keyword. For example, Base::show() is non-virtual in following program and program prints “Base::show() called”." }, { "code": "#include<iostream> using namespace std; class Base {public: // non-virtual by default void show() { cout<<\"Base::show() called\"; }}; class Derived: public Base {public: void show() { cout<<\"Derived::show() called\"; } }; int main(){ Derived d; Base &b = d; b.show(); getchar(); return 0;}", "e": 24936, "s": 24583, "text": null }, { "code": null, "e": 25030, "s": 24936, "text": "Adding virtual before definition of Base::show() makes program print “Derived::show() called”" }, { "code": null, "e": 25243, "s": 25030, "text": "In Java, methods are virtual by default and can be made non-virtual by using final keyword. For example, in the following java program, show() is by default virtual and the program prints “Derived::show() called”" }, { "code": "class Base { // virtual by default public void show() { System.out.println(\"Base::show() called\"); }} class Derived extends Base { public void show() { System.out.println(\"Derived::show() called\"); }} public class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); }}", "e": 25594, "s": 25243, "text": null }, { "code": null, "e": 25726, "s": 25594, "text": "Unlike C++ non-virtual behavior, if we add final before definition of show() in Base , then the above program fails in compilation." }, { "code": null, "e": 25851, "s": 25726, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25856, "s": 25851, "text": "Java" }, { "code": null, "e": 25861, "s": 25856, "text": "Java" }, { "code": null, "e": 25959, "s": 25861, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25991, "s": 25959, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26042, "s": 25991, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26072, "s": 26042, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26091, "s": 26072, "text": "Interfaces in Java" }, { "code": null, "e": 26109, "s": 26091, "text": "ArrayList in Java" }, { "code": null, "e": 26140, "s": 26109, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26172, "s": 26140, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26192, "s": 26172, "text": "Stack Class in Java" }, { "code": null, "e": 26207, "s": 26192, "text": "Stream In Java" } ]
Jacobi Iteration and Spectral Radius | by Ryan Reiff | Towards Data Science
One of the main pillars of Numerical Analysis is the solving of large linear systems of equations. There are a variety of methods that Numerical Analysts implement in order to solve such systems; however, the one we will look at today is Jacobi Iteration. Problem Statement: A large linear system can easily be represented with matrices in the form “Ax=b”, where “A” represents a square matrix that contains the ordered coefficients of our linear system of equations, “x” holds all of our different variables, and “b” represents the constants that each linear equation is equal to. We wish to solve for our unknown x-values, and we can do so through the use of Jacobi Iteration. In order to fully understand Jacobi Iteration, we must first understand Fixed Point Iteration. Both methods utilize the same scheme, but Jacobi Iteration can be applied to a larger system of equations. In Fixed Point Iteration, the main idea is to take an equation and arrange it in terms of Xn+1 = F(Xn), so that by starting at some initial x-value (Xn) and plugging it into the F(Xn) equation, we get a new value (Xn+1) that we then use as the next x-value to plug into F(Xn), and so on and so on. We can repeat this process until the two sides of the equation become equal or roughly equal, in which case we have reached our fixed point solution. A small worked out example is shown below. This method does not always converge and there are certain tests to determine if it will; however, we will just stick with this simple explanation to summarize the main idea for now. Now, let’s take a look at the way Jacobi Iteration leverages the principles of Fixed Point Iteration in the example below. Example System of Equations: With Jacobi Iteration, just like with normal Fixed Point Iteration, we are interested in taking an equation and rearranging it so that it takes the form Xn+1 = F(Xn). The only difference is that with Jacobi iteration we are doing this to not just one equation, but rather every equation in our system of equations, so that each equation is equal to a single unique variable (one equation equal to x1, another for x2, and so on). This reorganization of equations is shown below. To iterate through this system, we can start with a set of initial values for X1,X2, and X3 and plug these values into our equations. We can then use our new values and plug them back into the equation once more. Repeat this process, as shown below, for the first few iterations. Assuming that our system of equations converges using Jacobi Iteration, if we continue this process, eventually we will converge upon our solution or get reasonably close up to a given tolerance. While conceptually the process is quite simple, there is a bit of nuance involved when it comes to checking to see if convergence is actually possible. The Formal Jacobi Iteration Equation: The Jacobi Iterative Method can be summarized with the equation below. The “a” variables represent the elements of the coefficient matrix “A”, the “x” variables represent our unknown x-values that we are solving for, and “b” represents the constants of each equation. By applying the Jacobi Iteration Equation above, we are left with the same conclusion that we conceptually derived earlier when discussing the relationship between Fixed Point Iteration and Jacobi Iteration. What is the “T” Matrix? Why is it important?: While the implementation of the Jacobi iteration is very simple, the method will not always converge to a set of solutions. Due to this fact, a convergence test must be run prior to implementing the Jacobi Iteration. This convergence test is entirely dependent on a new matrix called our “T” matrix. Take the matrix representation of our Jacobi Iteration. We can re-write this system of equations in such a way that the entire system is decomposed into the form “Xn+1 = TXn + c”. In other words, we can decompose the matrix on the right hand side of the equation into a matrix of coefficients and into a matrix of constants. The process is shown below. It will be shown later why getting our system of equations into this form (Xn+1=TXn + c) is crucial in order to test for convergence. For our specific example, our Jacobi Iteration Matrix decomposed into this form will be exactly equivalent to Where: While the derivation above is very useful in understanding where the matrix “T” comes from, it is not necessary to do every time in order to actually find out what the matrix “T” is. Rather, the steps below can be used to fill in every element of the “T” matrix in a far more simple and timely fashion. The “T” matrix is extremely important because all that is required for our Jacobi Iteration Method to converge, is that the spectral radius of our matrix “T” is strictly less than 1. The spectral radius for a square matrix is defined simply as the largest absolute value of its eigenvalues. The proof below demonstrates why it is so crucial that we solve for matrix “T” in the first place, and how it’s relationship to the spectral radius creates the condition that the spectral radius must be less than 1 if we wish to see our method converge. Test of Convergence for Jacobi Iteration: Now that we know how to test for convergence (and more importantly why we use this certain test), we can do so with our example system of equations. We have already solved for our “T” matrix from earlier, so all that is left to do is to find all of its eigenvalues and make sure their absolute values are strictly less than one. The eigenvalues for the “T” matrix in our example are listed below. Since all of their absolute values are less than 1, our Jacobi Iteration Method will converge, and all that is left to do is implement some Python code that runs the iterations for us. Implementation: import mathimport numpy as npdef JacobiIteration(n): x1 = np.zeros(n) x2 = np.zeros(n) x3 = np.zeros(n) for i in range(0,n-1): x1[i+1] = -x2[i] - 0.5*x3[i] + 3 x2[i+1] = 0.5*x1[i] - 0.5*x3[i] + 1.5 x3[i+1] = -0.5*x1[i] - x2[i] + 3.5 print ("Our x1 value is",x1[-1], "\nOur x2 value is",x2[-1], "\nOur x3 value is",x3[-1])JacobiIteration(60) After about 60 iterations, and starting from an initial guess of zero for all of our x-values, we can see that we have converged just about exactly upon our solution given the machine precision of the computer. In the image on the left, we can see the output from each iteration. This is only about 30 iterations, and we are still within an extremely high degree of accuracy. The order of the arrays from top to bottom is x1, x2, then x3. They read row by row, left to right. That’s really all there is to Jacobi Iteration. We take a system of equations, rearrange it a bit, test for convergence, run a bit of code, and then we are done. Citations: Burden, Richard L., and J. Douglas. Faires. Numerical Analysis, by Richard L. Burden, J. Douglas Faires. 9th ed., Brooks/Cole, 2010. pp. 452 Hector D. Ceniceros, 2020, Chapter 10.9: Convergence of Linear Iterative Methods, lecture notes, Numerical Analysis 104B, University of California Santa Barbara, delivered February 2020.
[ { "code": null, "e": 427, "s": 171, "text": "One of the main pillars of Numerical Analysis is the solving of large linear systems of equations. There are a variety of methods that Numerical Analysts implement in order to solve such systems; however, the one we will look at today is Jacobi Iteration." }, { "code": null, "e": 446, "s": 427, "text": "Problem Statement:" }, { "code": null, "e": 850, "s": 446, "text": "A large linear system can easily be represented with matrices in the form “Ax=b”, where “A” represents a square matrix that contains the ordered coefficients of our linear system of equations, “x” holds all of our different variables, and “b” represents the constants that each linear equation is equal to. We wish to solve for our unknown x-values, and we can do so through the use of Jacobi Iteration." }, { "code": null, "e": 1726, "s": 850, "text": "In order to fully understand Jacobi Iteration, we must first understand Fixed Point Iteration. Both methods utilize the same scheme, but Jacobi Iteration can be applied to a larger system of equations. In Fixed Point Iteration, the main idea is to take an equation and arrange it in terms of Xn+1 = F(Xn), so that by starting at some initial x-value (Xn) and plugging it into the F(Xn) equation, we get a new value (Xn+1) that we then use as the next x-value to plug into F(Xn), and so on and so on. We can repeat this process until the two sides of the equation become equal or roughly equal, in which case we have reached our fixed point solution. A small worked out example is shown below. This method does not always converge and there are certain tests to determine if it will; however, we will just stick with this simple explanation to summarize the main idea for now." }, { "code": null, "e": 1849, "s": 1726, "text": "Now, let’s take a look at the way Jacobi Iteration leverages the principles of Fixed Point Iteration in the example below." }, { "code": null, "e": 1878, "s": 1849, "text": "Example System of Equations:" }, { "code": null, "e": 2356, "s": 1878, "text": "With Jacobi Iteration, just like with normal Fixed Point Iteration, we are interested in taking an equation and rearranging it so that it takes the form Xn+1 = F(Xn). The only difference is that with Jacobi iteration we are doing this to not just one equation, but rather every equation in our system of equations, so that each equation is equal to a single unique variable (one equation equal to x1, another for x2, and so on). This reorganization of equations is shown below." }, { "code": null, "e": 2636, "s": 2356, "text": "To iterate through this system, we can start with a set of initial values for X1,X2, and X3 and plug these values into our equations. We can then use our new values and plug them back into the equation once more. Repeat this process, as shown below, for the first few iterations." }, { "code": null, "e": 2984, "s": 2636, "text": "Assuming that our system of equations converges using Jacobi Iteration, if we continue this process, eventually we will converge upon our solution or get reasonably close up to a given tolerance. While conceptually the process is quite simple, there is a bit of nuance involved when it comes to checking to see if convergence is actually possible." }, { "code": null, "e": 3022, "s": 2984, "text": "The Formal Jacobi Iteration Equation:" }, { "code": null, "e": 3290, "s": 3022, "text": "The Jacobi Iterative Method can be summarized with the equation below. The “a” variables represent the elements of the coefficient matrix “A”, the “x” variables represent our unknown x-values that we are solving for, and “b” represents the constants of each equation." }, { "code": null, "e": 3498, "s": 3290, "text": "By applying the Jacobi Iteration Equation above, we are left with the same conclusion that we conceptually derived earlier when discussing the relationship between Fixed Point Iteration and Jacobi Iteration." }, { "code": null, "e": 3544, "s": 3498, "text": "What is the “T” Matrix? Why is it important?:" }, { "code": null, "e": 3900, "s": 3544, "text": "While the implementation of the Jacobi iteration is very simple, the method will not always converge to a set of solutions. Due to this fact, a convergence test must be run prior to implementing the Jacobi Iteration. This convergence test is entirely dependent on a new matrix called our “T” matrix. Take the matrix representation of our Jacobi Iteration." }, { "code": null, "e": 4331, "s": 3900, "text": "We can re-write this system of equations in such a way that the entire system is decomposed into the form “Xn+1 = TXn + c”. In other words, we can decompose the matrix on the right hand side of the equation into a matrix of coefficients and into a matrix of constants. The process is shown below. It will be shown later why getting our system of equations into this form (Xn+1=TXn + c) is crucial in order to test for convergence." }, { "code": null, "e": 4441, "s": 4331, "text": "For our specific example, our Jacobi Iteration Matrix decomposed into this form will be exactly equivalent to" }, { "code": null, "e": 4448, "s": 4441, "text": "Where:" }, { "code": null, "e": 4751, "s": 4448, "text": "While the derivation above is very useful in understanding where the matrix “T” comes from, it is not necessary to do every time in order to actually find out what the matrix “T” is. Rather, the steps below can be used to fill in every element of the “T” matrix in a far more simple and timely fashion." }, { "code": null, "e": 4934, "s": 4751, "text": "The “T” matrix is extremely important because all that is required for our Jacobi Iteration Method to converge, is that the spectral radius of our matrix “T” is strictly less than 1." }, { "code": null, "e": 5296, "s": 4934, "text": "The spectral radius for a square matrix is defined simply as the largest absolute value of its eigenvalues. The proof below demonstrates why it is so crucial that we solve for matrix “T” in the first place, and how it’s relationship to the spectral radius creates the condition that the spectral radius must be less than 1 if we wish to see our method converge." }, { "code": null, "e": 5338, "s": 5296, "text": "Test of Convergence for Jacobi Iteration:" }, { "code": null, "e": 5667, "s": 5338, "text": "Now that we know how to test for convergence (and more importantly why we use this certain test), we can do so with our example system of equations. We have already solved for our “T” matrix from earlier, so all that is left to do is to find all of its eigenvalues and make sure their absolute values are strictly less than one." }, { "code": null, "e": 5735, "s": 5667, "text": "The eigenvalues for the “T” matrix in our example are listed below." }, { "code": null, "e": 5920, "s": 5735, "text": "Since all of their absolute values are less than 1, our Jacobi Iteration Method will converge, and all that is left to do is implement some Python code that runs the iterations for us." }, { "code": null, "e": 5936, "s": 5920, "text": "Implementation:" }, { "code": null, "e": 6337, "s": 5936, "text": "import mathimport numpy as npdef JacobiIteration(n): x1 = np.zeros(n) x2 = np.zeros(n) x3 = np.zeros(n) for i in range(0,n-1): x1[i+1] = -x2[i] - 0.5*x3[i] + 3 x2[i+1] = 0.5*x1[i] - 0.5*x3[i] + 1.5 x3[i+1] = -0.5*x1[i] - x2[i] + 3.5 print (\"Our x1 value is\",x1[-1], \"\\nOur x2 value is\",x2[-1], \"\\nOur x3 value is\",x3[-1])JacobiIteration(60)" }, { "code": null, "e": 6548, "s": 6337, "text": "After about 60 iterations, and starting from an initial guess of zero for all of our x-values, we can see that we have converged just about exactly upon our solution given the machine precision of the computer." }, { "code": null, "e": 6813, "s": 6548, "text": "In the image on the left, we can see the output from each iteration. This is only about 30 iterations, and we are still within an extremely high degree of accuracy. The order of the arrays from top to bottom is x1, x2, then x3. They read row by row, left to right." }, { "code": null, "e": 6975, "s": 6813, "text": "That’s really all there is to Jacobi Iteration. We take a system of equations, rearrange it a bit, test for convergence, run a bit of code, and then we are done." }, { "code": null, "e": 6986, "s": 6975, "text": "Citations:" }, { "code": null, "e": 7127, "s": 6986, "text": "Burden, Richard L., and J. Douglas. Faires. Numerical Analysis, by Richard L. Burden, J. Douglas Faires. 9th ed., Brooks/Cole, 2010. pp. 452" } ]
Output Iterators in C++
Here we will see what are the Output iterators in C++. The Output iterators has some properties. These are like below: The output iterators are used to modify the value of the containers. We cannot read data from container using this kind of iterators This is One-Way and Write only iterator It can be incremented, but cannot be decremented. There are two sub-parts of Output iterators. These are Insert Iterator and ostream iterator. The insert iterator is used to insert some element inside the container. The assignment operator on this type of iterator inserts new element at current position. The syntax of insert iterator is like below: template<class Container, class Iterator> insert_iterator<container> inserter(Container &x,Iterator it); This iterator takes two parameters, x and it. The x is the container, on which the iterator will work. The second argument is an iterator object, which is pointing the position which is to be modified. #include <iostream> #include <iterator> #include <vector> #include <algorithm> using namespace std; int main () { vector<int> vec1,vec2; for (int i=1; i<=10; i++) { //insert elements into vectors vec1.push_back(i); vec2.push_back(i+3); } vector<int>::iterator it = vec1.begin(); //iterator works on vector1 advance (it,5); //advance it to 5 position copy (vec2.begin(),vec2.end(),inserter(vec1,it)); cout<<"Elements of vec1 are :"; for ( it = vec1.begin(); it!= vec1.end(); ++it ) cout << ' ' << *it; cout << endl; return 0; } Elements of vec1 are : 1 2 3 4 5 4 5 6 7 8 9 10 11 12 13 6 7 8 9 10 The ostream iterator is used to write to the output stream like cout. The ostream iterator can be created using basic_ostream object. When the assignment operator is used with this type of iterator, it inserts new element to the output stream. The syntax is like below. template<class T, class charT=char, class traits=char_traits<charT>> class ostream_iterator; The member functions of ostream iterator class is like below. ostream_iterator<T, charT, traits>& operator=(const T& value); ostream_iterator<T, charT, traits>& operator*(); ostream_iterator<T, charT, traits>& operator++(); ostream_iterator<T, charT, traits>& operator++(int); The parameters are: T. This is the type of elements that will be inserted, chart, this is the type of elements that ostream can handle, and traits. These are character traits that can be handled by the stream. #include <iostream> #include<iterator> #include<vector> #include<algorithm> using namespace std; main() { vector<int> vector; for(int i=1;i<=10;i++) vector.push_back(i*i); //make square and insert ostream_iterator<int> out(cout,","); copy(vector.begin(),vector.end(),out); } 1,4,9,16,25,36,49,64,81,100, Another example, #include <iostream> #include<iterator> #include<vector> #include<algorithm> using namespace std; main() { ostream_iterator<int> os_out(cout,","); *os_out = 10; os_out++; //point to next *os_out = 20; os_out++; *os_out = 30; } 10,20,30,
[ { "code": null, "e": 1181, "s": 1062, "text": "Here we will see what are the Output iterators in C++. The Output iterators has some\nproperties. These are like below:" }, { "code": null, "e": 1250, "s": 1181, "text": "The output iterators are used to modify the value of the containers." }, { "code": null, "e": 1314, "s": 1250, "text": "We cannot read data from container using this kind of iterators" }, { "code": null, "e": 1354, "s": 1314, "text": "This is One-Way and Write only iterator" }, { "code": null, "e": 1404, "s": 1354, "text": "It can be incremented, but cannot be decremented." }, { "code": null, "e": 1497, "s": 1404, "text": "There are two sub-parts of Output iterators. These are Insert Iterator and ostream\niterator." }, { "code": null, "e": 1705, "s": 1497, "text": "The insert iterator is used to insert some element inside the container. The assignment\noperator on this type of iterator inserts new element at current position. The syntax of insert\niterator is like below:" }, { "code": null, "e": 1810, "s": 1705, "text": "template<class Container, class Iterator>\ninsert_iterator<container> inserter(Container &x,Iterator it);" }, { "code": null, "e": 2012, "s": 1810, "text": "This iterator takes two parameters, x and it. The x is the container, on which the iterator will\nwork. The second argument is an iterator object, which is pointing the position which is to be\nmodified." }, { "code": null, "e": 2590, "s": 2012, "text": "#include <iostream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nint main () {\n vector<int> vec1,vec2;\n for (int i=1; i<=10; i++) { //insert elements into vectors\n vec1.push_back(i);\n vec2.push_back(i+3);\n }\n vector<int>::iterator it = vec1.begin(); //iterator works on vector1\n advance (it,5); //advance it to 5 position\n copy (vec2.begin(),vec2.end(),inserter(vec1,it));\n cout<<\"Elements of vec1 are :\";\n for ( it = vec1.begin(); it!= vec1.end(); ++it )\n cout << ' ' << *it;\n cout << endl;\n return 0;\n}" }, { "code": null, "e": 2658, "s": 2590, "text": "Elements of vec1 are : 1 2 3 4 5 4 5 6 7 8 9 10 11 12 13 6 7 8 9 10" }, { "code": null, "e": 2928, "s": 2658, "text": "The ostream iterator is used to write to the output stream like cout. The ostream\niterator can be created using basic_ostream object. When the assignment operator is used with\nthis type of iterator, it inserts new element to the output stream. The syntax is like below." }, { "code": null, "e": 3021, "s": 2928, "text": "template<class T, class charT=char, class traits=char_traits<charT>>\nclass ostream_iterator;" }, { "code": null, "e": 3083, "s": 3021, "text": "The member functions of ostream iterator class is like below." }, { "code": null, "e": 3298, "s": 3083, "text": "ostream_iterator<T, charT, traits>& operator=(const T& value);\nostream_iterator<T, charT, traits>& operator*();\nostream_iterator<T, charT, traits>& operator++();\nostream_iterator<T, charT, traits>& operator++(int);" }, { "code": null, "e": 3508, "s": 3298, "text": "The parameters are: T. This is the type of elements that will be inserted, chart, this is the type\nof elements that ostream can handle, and traits. These are character traits that can be handled\nby the stream." }, { "code": null, "e": 3807, "s": 3508, "text": "#include <iostream>\n#include<iterator>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nmain() {\n vector<int> vector;\n for(int i=1;i<=10;i++)\n vector.push_back(i*i); //make square and insert\n ostream_iterator<int> out(cout,\",\");\n copy(vector.begin(),vector.end(),out);\n}" }, { "code": null, "e": 3836, "s": 3807, "text": "1,4,9,16,25,36,49,64,81,100," }, { "code": null, "e": 3853, "s": 3836, "text": "Another example," }, { "code": null, "e": 4097, "s": 3853, "text": "#include <iostream>\n#include<iterator>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nmain() {\n ostream_iterator<int> os_out(cout,\",\");\n *os_out = 10;\n os_out++; //point to next\n *os_out = 20;\n os_out++;\n *os_out = 30;\n}" }, { "code": null, "e": 4107, "s": 4097, "text": "10,20,30," } ]
Dijkstra’s shortest path algorithm using set in STL - GeeksforGeeks
08 Apr, 2022 Given a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph. Input : Source = 0 Output : Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14 We have discussed Dijkstra’s shortest Path implementations. Dijkstra’s Algorithm for Adjacency Matrix Representation (In C/C++ with time complexity O(v2) Dijkstra’s Algorithm for Adjacency List Representation (In C with Time Complexity O(ELogV)) The second implementation is time complexity wise better, but is really complex as we have implemented our own priority queue. STL provides priority_queue, but the provided priority queue doesn’t support decrease key and delete operations. And in Dijkstra’s algorithm, we need a priority queue and below operations on priority queue : ExtractMin : from all those vertices whose shortest distance is not yet found, we need to get vertex with minimum distance. DecreaseKey : After extracting vertex we need to update distance of its adjacent vertices, and if new distance is smaller, then update that in data structure. Above operations can be easily implemented by set data structure of c++ STL, set keeps all its keys in sorted order so minimum distant vertex will always be at beginning, we can extract it from there, which is the ExtractMin operation and update other adjacent vertex accordingly if any vertex’s distance becomes smaller then delete its previous entry and insert new updated entry which is DecreaseKey operation. Below is algorithm based on set data structure. 1) Initialize distances of all vertices as infinite. 2) Create an empty set. Every item of set is a pair (weight, vertex). Weight (or distance) is used used as first item of pair as first item is by default used to compare two pairs. 3) Insert source vertex into the set and make its distance as 0. 4) While Set doesn't become empty, do following a) Extract minimum distance vertex from Set. Let the extracted vertex be u. b) Loop through all adjacent of u and do following for every vertex v. // If there is a shorter path to v // through u. If dist[v] > dist[u] + weight(u, v) (i) Update distance of v, i.e., do dist[v] = dist[u] + weight(u, v) (i) If v is in set, update its distance in set by removing it first, then inserting with new distance (ii) If v is not in set, then insert it in set with new distance 5) Print distance array dist[] to print all shortest paths. Below is C++ implementation of above idea. C++ // Program to find Dijkstra's shortest path using STL set#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3f // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list< pair<int, int> > *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // prints shortest path from s void shortestPath(int s);}; // Allocates memory for adjacency listGraph::Graph(int V){ this->V = V; adj = new list< pair<int, int> >[V];} void Graph::addEdge(int u, int v, int w){ adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w));} // Prints shortest paths from src to all other verticesvoid Graph::shortestPath(int src){ // Create a set to store vertices that are being // processed set< pair<int, int> > setds; // Create a vector for distances and initialize all // distances as infinite (INF) vector<int> dist(V, INF); // Insert source itself in Set and initialize its // distance as 0. setds.insert(make_pair(0, src)); dist[src] = 0; /* Looping till all shortest distance are finalized then setds will become empty */ while (!setds.empty()) { // The first vertex in Set is the minimum distance // vertex, extract it from set. pair<int, int> tmp = *(setds.begin()); setds.erase(setds.begin()); // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = tmp.second; // 'i' is used to get all adjacent vertices of a vertex list< pair<int, int> >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // Get vertex label and weight of current adjacent // of u. int v = (*i).first; int weight = (*i).second; // If there is shorter path to v through u. if (dist[v] > dist[u] + weight) { /* If distance of v is not INF then it must be in our set, so removing it and inserting again with updated less distance. Note : We extract only those vertices from Set for which distance is finalized. So for them, we would never reach here. */ if (dist[v] != INF) setds.erase(setds.find(make_pair(dist[v], v))); // Updating distance of v dist[v] = dist[u] + weight; setds.insert(make_pair(dist[v], v)); } } } // Print shortest distances stored in dist[] printf("Vertex Distance from Source\n"); for (int i = 0; i < V; ++i) printf("%d \t\t %d\n", i, dist[i]);} // Driver program to test methods of graph classint main(){ // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); g.shortestPath(0); return 0;} Output : Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14 Time Complexity: Set in C++ are typically implemented using Self-balancing binary search trees. Therefore, time complexity of set operations like insert, delete is logarithmic and time complexity of above solution is O(ELogV)). Dijkstra’s Shortest Path Algorithm using priority_queue of STL This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above code4life surinderdawra388 Dijkstra Shortest Path STL Graph Graph Shortest Path STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Bellman–Ford Algorithm | DP-23 Detect Cycle in a Directed Graph Floyd Warshall Algorithm | DP-16 Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Check whether a given graph is Bipartite or not Traveling Salesman Problem (TSP) Implementation Detect cycle in an undirected graph
[ { "code": null, "e": 25096, "s": 25068, "text": "\n08 Apr, 2022" }, { "code": null, "e": 25208, "s": 25096, "text": "Given a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph." }, { "code": null, "e": 25520, "s": 25208, "text": "Input : Source = 0\nOutput : \n Vertex Distance from Source\n 0 0\n 1 4\n 2 12\n 3 19\n 4 21\n 5 11\n 6 9\n 7 8\n 8 14" }, { "code": null, "e": 25581, "s": 25520, "text": "We have discussed Dijkstra’s shortest Path implementations. " }, { "code": null, "e": 25675, "s": 25581, "text": "Dijkstra’s Algorithm for Adjacency Matrix Representation (In C/C++ with time complexity O(v2)" }, { "code": null, "e": 25767, "s": 25675, "text": "Dijkstra’s Algorithm for Adjacency List Representation (In C with Time Complexity O(ELogV))" }, { "code": null, "e": 26102, "s": 25767, "text": "The second implementation is time complexity wise better, but is really complex as we have implemented our own priority queue. STL provides priority_queue, but the provided priority queue doesn’t support decrease key and delete operations. And in Dijkstra’s algorithm, we need a priority queue and below operations on priority queue :" }, { "code": null, "e": 26226, "s": 26102, "text": "ExtractMin : from all those vertices whose shortest distance is not yet found, we need to get vertex with minimum distance." }, { "code": null, "e": 26385, "s": 26226, "text": "DecreaseKey : After extracting vertex we need to update distance of its adjacent vertices, and if new distance is smaller, then update that in data structure." }, { "code": null, "e": 26798, "s": 26385, "text": "Above operations can be easily implemented by set data structure of c++ STL, set keeps all its keys in sorted order so minimum distant vertex will always be at beginning, we can extract it from there, which is the ExtractMin operation and update other adjacent vertex accordingly if any vertex’s distance becomes smaller then delete its previous entry and insert new updated entry which is DecreaseKey operation." }, { "code": null, "e": 26848, "s": 26798, "text": "Below is algorithm based on set data structure. " }, { "code": null, "e": 27941, "s": 26848, "text": "1) Initialize distances of all vertices as infinite.\n\n2) Create an empty set. Every item of set is a pair\n (weight, vertex). Weight (or distance) is used used\n as first item of pair as first item is by default \n used to compare two pairs.\n\n3) Insert source vertex into the set and make its\n distance as 0.\n\n4) While Set doesn't become empty, do following\n a) Extract minimum distance vertex from Set. \n Let the extracted vertex be u.\n b) Loop through all adjacent of u and do \n following for every vertex v.\n\n // If there is a shorter path to v\n // through u. \n If dist[v] > dist[u] + weight(u, v)\n\n (i) Update distance of v, i.e., do\n dist[v] = dist[u] + weight(u, v)\n (i) If v is in set, update its distance\n in set by removing it first, then\n inserting with new distance\n (ii) If v is not in set, then insert\n it in set with new distance\n \n5) Print distance array dist[] to print all shortest\n paths. " }, { "code": null, "e": 27984, "s": 27941, "text": "Below is C++ implementation of above idea." }, { "code": null, "e": 27988, "s": 27984, "text": "C++" }, { "code": "// Program to find Dijkstra's shortest path using STL set#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3f // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list< pair<int, int> > *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // prints shortest path from s void shortestPath(int s);}; // Allocates memory for adjacency listGraph::Graph(int V){ this->V = V; adj = new list< pair<int, int> >[V];} void Graph::addEdge(int u, int v, int w){ adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w));} // Prints shortest paths from src to all other verticesvoid Graph::shortestPath(int src){ // Create a set to store vertices that are being // processed set< pair<int, int> > setds; // Create a vector for distances and initialize all // distances as infinite (INF) vector<int> dist(V, INF); // Insert source itself in Set and initialize its // distance as 0. setds.insert(make_pair(0, src)); dist[src] = 0; /* Looping till all shortest distance are finalized then setds will become empty */ while (!setds.empty()) { // The first vertex in Set is the minimum distance // vertex, extract it from set. pair<int, int> tmp = *(setds.begin()); setds.erase(setds.begin()); // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = tmp.second; // 'i' is used to get all adjacent vertices of a vertex list< pair<int, int> >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // Get vertex label and weight of current adjacent // of u. int v = (*i).first; int weight = (*i).second; // If there is shorter path to v through u. if (dist[v] > dist[u] + weight) { /* If distance of v is not INF then it must be in our set, so removing it and inserting again with updated less distance. Note : We extract only those vertices from Set for which distance is finalized. So for them, we would never reach here. */ if (dist[v] != INF) setds.erase(setds.find(make_pair(dist[v], v))); // Updating distance of v dist[v] = dist[u] + weight; setds.insert(make_pair(dist[v], v)); } } } // Print shortest distances stored in dist[] printf(\"Vertex Distance from Source\\n\"); for (int i = 0; i < V; ++i) printf(\"%d \\t\\t %d\\n\", i, dist[i]);} // Driver program to test methods of graph classint main(){ // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); g.shortestPath(0); return 0;}", "e": 31496, "s": 27988, "text": null }, { "code": null, "e": 31506, "s": 31496, "text": "Output : " }, { "code": null, "e": 31658, "s": 31506, "text": "Vertex Distance from Source\n0 0\n1 4\n2 12\n3 19\n4 21\n5 11\n6 9\n7 8\n8 14" }, { "code": null, "e": 32122, "s": 31658, "text": "Time Complexity: Set in C++ are typically implemented using Self-balancing binary search trees. Therefore, time complexity of set operations like insert, delete is logarithmic and time complexity of above solution is O(ELogV)). Dijkstra’s Shortest Path Algorithm using priority_queue of STL This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 32132, "s": 32122, "text": "code4life" }, { "code": null, "e": 32149, "s": 32132, "text": "surinderdawra388" }, { "code": null, "e": 32158, "s": 32149, "text": "Dijkstra" }, { "code": null, "e": 32172, "s": 32158, "text": "Shortest Path" }, { "code": null, "e": 32176, "s": 32172, "text": "STL" }, { "code": null, "e": 32182, "s": 32176, "text": "Graph" }, { "code": null, "e": 32188, "s": 32182, "text": "Graph" }, { "code": null, "e": 32202, "s": 32188, "text": "Shortest Path" }, { "code": null, "e": 32206, "s": 32202, "text": "STL" }, { "code": null, "e": 32304, "s": 32206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32324, "s": 32304, "text": "Topological Sorting" }, { "code": null, "e": 32355, "s": 32324, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 32388, "s": 32355, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 32421, "s": 32388, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 32496, "s": 32421, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 32564, "s": 32496, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 32614, "s": 32564, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 32662, "s": 32614, "text": "Check whether a given graph is Bipartite or not" }, { "code": null, "e": 32710, "s": 32662, "text": "Traveling Salesman Problem (TSP) Implementation" } ]
Swing Examples - Adding vertical scrollbar
Following example showcase how to show a Scroll Pane with a vertical bar always on a Panel in a Java Swing application. We are using the following APIs. JScrollPane(Component view) − To create a scrollPane on a component. JScrollPane(Component view) − To create a scrollPane on a component. JScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) − To show a vertical bar always. JScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) − To show a vertical bar always. import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class SwingTester { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingTester(){ prepareGUI(); } public static void main(String[] args){ SwingTester swingControlDemo = new SwingTester(); swingControlDemo.showScrollPaneDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java Swing Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new JLabel("", JLabel.CENTER); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private JTextArea outputTextArea; private void showScrollPaneDemo(){ headerLabel.setText("Control in action: ScrollPane"); outputTextArea = new JTextArea("",5,20); JScrollPane scrollPane = new JScrollPane(outputTextArea); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); controlPanel.add(scrollPane); mainFrame.setVisible(true); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2159, "s": 2039, "text": "Following example showcase how to show a Scroll Pane with a vertical bar always on a Panel in a Java Swing application." }, { "code": null, "e": 2192, "s": 2159, "text": "We are using the following APIs." }, { "code": null, "e": 2261, "s": 2192, "text": "JScrollPane(Component view) − To create a scrollPane on a component." }, { "code": null, "e": 2330, "s": 2261, "text": "JScrollPane(Component view) − To create a scrollPane on a component." }, { "code": null, "e": 2441, "s": 2330, "text": "JScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) − To show a vertical bar always." }, { "code": null, "e": 2552, "s": 2441, "text": "JScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) − To show a vertical bar always." }, { "code": null, "e": 4339, "s": 2552, "text": "import java.awt.FlowLayout;\nimport java.awt.GridLayout;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\n \npublic class SwingTester {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n \n public SwingTester(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingTester swingControlDemo = new SwingTester(); \n swingControlDemo.showScrollPaneDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java Swing Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new JLabel(\"\", JLabel.CENTER); \n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n\n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n \n private JTextArea outputTextArea;\n \n private void showScrollPaneDemo(){\n headerLabel.setText(\"Control in action: ScrollPane\");\n outputTextArea = new JTextArea(\"\",5,20);\n JScrollPane scrollPane = new JScrollPane(outputTextArea); \n scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);\n controlPanel.add(scrollPane);\n mainFrame.setVisible(true); \n } \n}" }, { "code": null, "e": 4346, "s": 4339, "text": " Print" }, { "code": null, "e": 4357, "s": 4346, "text": " Add Notes" } ]
Servlets - Cookies Handling
Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies. There are three steps involved in identifying returning users − Server script sends a set of cookies to the browser. For example name, age, or identification number etc. Server script sends a set of cookies to the browser. For example name, age, or identification number etc. Browser stores this information on local machine for future use. Browser stores this information on local machine for future use. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user. This chapter will teach you how to set or reset cookies, how to access them and how to delete them. Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet that sets a cookie might send headers that look something like this − HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; path = /; domain = tutorialspoint.com Connection: close Content-Type: text/html As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date. If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this − GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name = xyz A servlet will then have access to the cookie through the request method request.getCookies() which returns an array of Cookie objects. Following is the list of useful methods which you can use while manipulating cookies in servlet. public void setDomain(String pattern) This method sets the domain to which cookie applies, for example tutorialspoint.com. public String getDomain() This method gets the domain to which cookie applies, for example tutorialspoint.com. public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session. public int getMaxAge() This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. public String getName() This method returns the name of the cookie. The name cannot be changed after creation. public void setValue(String newValue) This method sets the value associated with the cookie public String getValue() This method gets the value associated with the cookie. public void setPath(String uri) This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories. public String getPath() This method gets the path to which this cookie applies. public void setSecure(boolean flag) This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections. public void setComment(String purpose) This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user. public String getComment() This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment. Setting cookies with servlet involves three steps − (1) Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings. Cookie cookie = new Cookie("key","value"); Keep in mind, neither the name nor the value should contain white space or any of the following characters − [ ] ( ) = , " / ? @ : ; (2) Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours. cookie.setMaxAge(60 * 60 * 24); (3) Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header as follows − response.addCookie(cookie); Let us modify our Form Example to set the cookies for first and last name. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create cookies for first and last names. Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Setting Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head> <title>" + title + "</title> </head>\n" + "<body bgcolor = \"#f0f0f0\">\n" + "<h1 align = \"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>First Name</b>: " + request.getParameter("first_name") + "\n" + " <li><b>Last Name</b>: " + request.getParameter("last_name") + "\n" + "</ul>\n" + "</body> </html>" ); } } Compile the above servlet HelloForm and create appropriate entry in web.xml file and finally try following HTML page to call servlet. <html> <body> <form action = "HelloForm" method = "GET"> First Name: <input type = "text" name = "first_name"> <br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> </body> </html> Keep above HTML content in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form. Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button. Next section would explain you how you would access these cookies back in your web application. To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies() method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value. Let us read cookies which we have set in previous example − // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class ReadCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor = \"#f0f0f0\">\n" ); if( cookies != null ) { out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( ) + " <br/>"); } } else { out.println("<h2>No cookies founds</h2>"); } out.println("</body>"); out.println("</html>"); } } Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would have set first_name cookie as "John" and last_name cookie as "Player" then running http://localhost:8080/ReadCookies would display the following result − Found Cookies Name and Value Name : first_name, Value: John Name : last_name, Value: Player To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps − Read an already existing cookie and store it in Cookie object. Read an already existing cookie and store it in Cookie object. Set cookie age as zero using setMaxAge() method to delete an existing cookie Set cookie age as zero using setMaxAge() method to delete an existing cookie Add this cookie back into response header. Add this cookie back into response header. The following example would delete and existing cookie named "first_name" and when you would run ReadCookies servlet next time it would return null value for first_name. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class DeleteCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Delete Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor = \"#f0f0f0\">\n" ); if( cookies != null ) { out.println("<h2> Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ) { cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie : " + cookie.getName( ) + "<br/>"); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } } else { out.println("<h2>No cookies founds</h2>"); } out.println("</body>"); out.println("</html>"); } } Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now running http://localhost:8080/DeleteCookies would display the following result − Cookies Name and Value Deleted cookie : first_name Name : first_name, Value: John Name : last_name, Value: Player Deleted cookie : first_name Name : first_name, Value: John Name : last_name, Value: Player Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as follows − Found Cookies Name and Value Name : last_name, Value: Player You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet Options. To delete all cookies, press Delete Cookies. 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 31 Lectures 12.5 hours Uplatz 38 Lectures 4.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2349, "s": 2185, "text": "Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies." }, { "code": null, "e": 2413, "s": 2349, "text": "There are three steps involved in identifying returning users −" }, { "code": null, "e": 2519, "s": 2413, "text": "Server script sends a set of cookies to the browser. For example name, age, or identification number etc." }, { "code": null, "e": 2625, "s": 2519, "text": "Server script sends a set of cookies to the browser. For example name, age, or identification number etc." }, { "code": null, "e": 2690, "s": 2625, "text": "Browser stores this information on local machine for future use." }, { "code": null, "e": 2755, "s": 2690, "text": "Browser stores this information on local machine for future use." }, { "code": null, "e": 2919, "s": 2755, "text": "When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user." }, { "code": null, "e": 3083, "s": 2919, "text": "When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user." }, { "code": null, "e": 3183, "s": 3083, "text": "This chapter will teach you how to set or reset cookies, how to access them and how to delete them." }, { "code": null, "e": 3372, "s": 3183, "text": "Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet that sets a cookie might send headers that look something like this −" }, { "code": null, "e": 3613, "s": 3372, "text": "HTTP/1.1 200 OK\nDate: Fri, 04 Feb 2000 21:03:38 GMT\nServer: Apache/1.3.9 (UNIX) PHP/4.0b3\nSet-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; \n path = /; domain = tutorialspoint.com\nConnection: close\nContent-Type: text/html\n" }, { "code": null, "e": 3857, "s": 3613, "text": "As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to \"forget\" the cookie after the given time and date." }, { "code": null, "e": 4149, "s": 3857, "text": "If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this −" }, { "code": null, "e": 4393, "s": 4149, "text": "GET / HTTP/1.0\nConnection: Keep-Alive\nUser-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)\nHost: zink.demon.co.uk:1126\nAccept: image/gif, */*\nAccept-Encoding: gzip\nAccept-Language: en\nAccept-Charset: iso-8859-1,*,utf-8\nCookie: name = xyz\n" }, { "code": null, "e": 4529, "s": 4393, "text": "A servlet will then have access to the cookie through the request method request.getCookies() which returns an array of Cookie objects." }, { "code": null, "e": 4626, "s": 4529, "text": "Following is the list of useful methods which you can use while manipulating cookies in servlet." }, { "code": null, "e": 4665, "s": 4626, "text": "public void setDomain(String pattern) " }, { "code": null, "e": 4750, "s": 4665, "text": "This method sets the domain to which cookie applies, for example tutorialspoint.com." }, { "code": null, "e": 4777, "s": 4750, "text": "public String getDomain() " }, { "code": null, "e": 4862, "s": 4777, "text": "This method gets the domain to which cookie applies, for example tutorialspoint.com." }, { "code": null, "e": 4896, "s": 4862, "text": "public void setMaxAge(int expiry)" }, { "code": null, "e": 5055, "s": 4896, "text": "This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session." }, { "code": null, "e": 5078, "s": 5055, "text": "public int getMaxAge()" }, { "code": null, "e": 5225, "s": 5078, "text": "This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown." }, { "code": null, "e": 5249, "s": 5225, "text": "public String getName()" }, { "code": null, "e": 5336, "s": 5249, "text": "This method returns the name of the cookie. The name cannot be changed after creation." }, { "code": null, "e": 5375, "s": 5336, "text": "public void setValue(String newValue) " }, { "code": null, "e": 5429, "s": 5375, "text": "This method sets the value associated with the cookie" }, { "code": null, "e": 5455, "s": 5429, "text": "public String getValue() " }, { "code": null, "e": 5510, "s": 5455, "text": "This method gets the value associated with the cookie." }, { "code": null, "e": 5543, "s": 5510, "text": "public void setPath(String uri) " }, { "code": null, "e": 5737, "s": 5543, "text": "This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories." }, { "code": null, "e": 5761, "s": 5737, "text": "public String getPath()" }, { "code": null, "e": 5817, "s": 5761, "text": "This method gets the path to which this cookie applies." }, { "code": null, "e": 5853, "s": 5817, "text": "public void setSecure(boolean flag)" }, { "code": null, "e": 5977, "s": 5853, "text": "This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections." }, { "code": null, "e": 6017, "s": 5977, "text": "public void setComment(String purpose) " }, { "code": null, "e": 6154, "s": 6017, "text": "This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user." }, { "code": null, "e": 6181, "s": 6154, "text": "public String getComment()" }, { "code": null, "e": 6290, "s": 6181, "text": "This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment." }, { "code": null, "e": 6342, "s": 6290, "text": "Setting cookies with servlet involves three steps −" }, { "code": null, "e": 6471, "s": 6342, "text": "(1) Creating a Cookie object − You call the Cookie constructor with a cookie name and a cookie value, both of which are strings." }, { "code": null, "e": 6515, "s": 6471, "text": "Cookie cookie = new Cookie(\"key\",\"value\");\n" }, { "code": null, "e": 6624, "s": 6515, "text": "Keep in mind, neither the name nor the value should contain white space or any of the following characters −" }, { "code": null, "e": 6649, "s": 6624, "text": "[ ] ( ) = , \" / ? @ : ;\n" }, { "code": null, "e": 6804, "s": 6649, "text": "(2) Setting the maximum age − You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours." }, { "code": null, "e": 6838, "s": 6804, "text": "cookie.setMaxAge(60 * 60 * 24); \n" }, { "code": null, "e": 6977, "s": 6838, "text": "(3) Sending the Cookie into the HTTP response headers − You use response.addCookie to add cookies in the HTTP response header as follows −" }, { "code": null, "e": 7006, "s": 6977, "text": "response.addCookie(cookie);\n" }, { "code": null, "e": 7081, "s": 7006, "text": "Let us modify our Form Example to set the cookies for first and last name." }, { "code": null, "e": 8764, "s": 7081, "text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n \n// Extend HttpServlet class\npublic class HelloForm extends HttpServlet {\n\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Create cookies for first and last names. \n Cookie firstName = new Cookie(\"first_name\", request.getParameter(\"first_name\"));\n Cookie lastName = new Cookie(\"last_name\", request.getParameter(\"last_name\"));\n\n // Set expiry date after 24 Hrs for both the cookies.\n firstName.setMaxAge(60*60*24);\n lastName.setMaxAge(60*60*24);\n\n // Add both the cookies in the response header.\n response.addCookie( firstName );\n response.addCookie( lastName );\n\n // Set response content type\n response.setContentType(\"text/html\");\n \n PrintWriter out = response.getWriter();\n String title = \"Setting Cookies Example\";\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" + \"transitional//en\\\">\\n\";\n \n out.println(docType +\n \"<html>\\n\" +\n \"<head>\n <title>\" + title + \"</title>\n </head>\\n\" +\n \n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<ul>\\n\" +\n \" <li><b>First Name</b>: \"\n + request.getParameter(\"first_name\") + \"\\n\" +\n \" <li><b>Last Name</b>: \"\n + request.getParameter(\"last_name\") + \"\\n\" +\n \"</ul>\\n\" +\n \"</body>\n </html>\"\n );\n }\n}" }, { "code": null, "e": 8899, "s": 8764, "text": "Compile the above servlet HelloForm and create appropriate entry in web.xml file and finally try following HTML page to call servlet. " }, { "code": null, "e": 9194, "s": 8899, "text": " \n<html>\n <body>\n <form action = \"HelloForm\" method = \"GET\">\n First Name: <input type = \"text\" name = \"first_name\">\n <br />\n Last Name: <input type = \"text\" name = \"last_name\" />\n <input type = \"submit\" value = \"Submit\" />\n </form>\n </body>\n</html>" }, { "code": null, "e": 9407, "s": 9194, "text": "Keep above HTML content in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form." }, { "code": null, "e": 9683, "s": 9407, "text": "Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button." }, { "code": null, "e": 9779, "s": 9683, "text": "Next section would explain you how you would access these cookies back in your web application." }, { "code": null, "e": 10034, "s": 9779, "text": "To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies() method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value." }, { "code": null, "e": 10094, "s": 10034, "text": "Let us read cookies which we have set in previous example −" }, { "code": null, "e": 11483, "s": 10094, "text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n \n// Extend HttpServlet class\npublic class ReadCookies extends HttpServlet {\n \n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n Cookie cookie = null;\n Cookie[] cookies = null;\n\n // Get an array of Cookies associated with this domain\n cookies = request.getCookies();\n\n // Set response content type\n response.setContentType(\"text/html\");\n\n PrintWriter out = response.getWriter();\n String title = \"Reading Cookies Example\";\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" +\n \"transitional//en\\\">\\n\";\n \n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" );\n\n if( cookies != null ) {\n out.println(\"<h2> Found Cookies Name and Value</h2>\");\n\n for (int i = 0; i < cookies.length; i++) {\n cookie = cookies[i];\n out.print(\"Name : \" + cookie.getName( ) + \", \");\n out.print(\"Value: \" + cookie.getValue( ) + \" <br/>\");\n }\n } else {\n out.println(\"<h2>No cookies founds</h2>\");\n }\n out.println(\"</body>\");\n out.println(\"</html>\");\n }\n}" }, { "code": null, "e": 11730, "s": 11483, "text": "Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would have set first_name cookie as \"John\" and last_name cookie as \"Player\" then running http://localhost:8080/ReadCookies would display the following result −" }, { "code": null, "e": 11826, "s": 11730, "text": " Found Cookies Name and Value\nName : first_name, Value: John \nName : last_name, Value: Player\n" }, { "code": null, "e": 11949, "s": 11826, "text": "To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps −" }, { "code": null, "e": 12012, "s": 11949, "text": "Read an already existing cookie and store it in Cookie object." }, { "code": null, "e": 12075, "s": 12012, "text": "Read an already existing cookie and store it in Cookie object." }, { "code": null, "e": 12152, "s": 12075, "text": "Set cookie age as zero using setMaxAge() method to delete an existing cookie" }, { "code": null, "e": 12229, "s": 12152, "text": "Set cookie age as zero using setMaxAge() method to delete an existing cookie" }, { "code": null, "e": 12272, "s": 12229, "text": "Add this cookie back into response header." }, { "code": null, "e": 12315, "s": 12272, "text": "Add this cookie back into response header." }, { "code": null, "e": 12485, "s": 12315, "text": "The following example would delete and existing cookie named \"first_name\" and when you would run ReadCookies servlet next time it would return null value for first_name." }, { "code": null, "e": 14116, "s": 12485, "text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n \n// Extend HttpServlet class\npublic class DeleteCookies extends HttpServlet {\n \n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n Cookie cookie = null;\n Cookie[] cookies = null;\n \n // Get an array of Cookies associated with this domain\n cookies = request.getCookies();\n\n // Set response content type\n response.setContentType(\"text/html\");\n \n PrintWriter out = response.getWriter();\n String title = \"Delete Cookies Example\";\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" + \"transitional//en\\\">\\n\";\n \n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" );\n \n if( cookies != null ) {\n out.println(\"<h2> Cookies Name and Value</h2>\");\n\n for (int i = 0; i < cookies.length; i++) {\n cookie = cookies[i];\n\n if((cookie.getName( )).compareTo(\"first_name\") == 0 ) {\n cookie.setMaxAge(0);\n response.addCookie(cookie);\n out.print(\"Deleted cookie : \" + cookie.getName( ) + \"<br/>\");\n }\n out.print(\"Name : \" + cookie.getName( ) + \", \");\n out.print(\"Value: \" + cookie.getValue( )+\" <br/>\");\n }\n } else {\n out.println(\"<h2>No cookies founds</h2>\");\n }\n out.println(\"</body>\");\n out.println(\"</html>\");\n }\n}" }, { "code": null, "e": 14283, "s": 14116, "text": "Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now running http://localhost:8080/DeleteCookies would display the following result −" }, { "code": null, "e": 14399, "s": 14283, "text": "Cookies Name and Value\nDeleted cookie : first_name\nName : first_name, Value: John\nName : last_name, Value: Player\n" }, { "code": null, "e": 14427, "s": 14399, "text": "Deleted cookie : first_name" }, { "code": null, "e": 14458, "s": 14427, "text": "Name : first_name, Value: John" }, { "code": null, "e": 14491, "s": 14458, "text": "Name : last_name, Value: Player" }, { "code": null, "e": 14590, "s": 14491, "text": "Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as follows −" }, { "code": null, "e": 14654, "s": 14590, "text": " Found Cookies Name and Value\nName : last_name, Value: Player\n" }, { "code": null, "e": 14811, "s": 14654, "text": "You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet Options. To delete all cookies, press Delete Cookies." }, { "code": null, "e": 14846, "s": 14811, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14860, "s": 14846, "text": " Karthikeya T" }, { "code": null, "e": 14895, "s": 14860, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 14911, "s": 14895, "text": " TELCOMA Global" }, { "code": null, "e": 14944, "s": 14911, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 14960, "s": 14944, "text": " TELCOMA Global" }, { "code": null, "e": 14996, "s": 14960, "text": "\n 31 Lectures \n 12.5 hours \n" }, { "code": null, "e": 15004, "s": 14996, "text": " Uplatz" }, { "code": null, "e": 15039, "s": 15004, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 15057, "s": 15039, "text": " Packt Publishing" }, { "code": null, "e": 15064, "s": 15057, "text": " Print" }, { "code": null, "e": 15075, "s": 15064, "text": " Add Notes" } ]
What is a trend in time series? - GeeksforGeeks
12 Dec, 2021 Time series data is a sequence of data points that measure some variable over ordered period of time. It is the fastest-growing category of databases as it is widely used in a variety of industries to understand and forecast data patterns. So while preparing this time series data for modeling it’s important to check for time series components or patterns. One of these components is Trend. Trend is a pattern in data that shows the movement of a series to relatively higher or lower values over a long period of time. In other words, a trend is observed when there is an increasing or decreasing slope in the time series. Trend usually happens for some time and then disappears, it does not repeat. For example, some new song comes, it goes trending for a while, and then disappears. There is fairly any chance that it would be trending again. A trend could be : Uptrend: Time Series Analysis shows a general pattern that is upward then it is Uptrend. Downtrend: Time Series Analysis shows a pattern that is downward then it is Downtrend. Horizontal or Stationary trend: If no pattern observed then it is called a Horizontal or stationary trend. You can find trends in data either by simply visualizing or by the decomposing dataset. By simply plotting the dataset you can see the general trend in data Approach : Import module Load dataset Cast month column to date time object Set month as index Create plot Note: In the examples given below the same code is used to show all three trends just the dataset used is different to reflect that particular trend. Link for datasets : click here Example: Uptrend Python3 # importing the librariesimport pandas as pdimport matplotlib # importing datasetdata = pd.read_csv(r'C:\Users\admin\Downloads\Electric_Production.csv') # casting Month column to datetime objectdata['DATE'] = pd.to_datetime(data['DATE']) # Setting Month as indexdata = data.set_index('DATE') # Creating the plotdata.plot() Output : Example: Downtrend Python3 import pandas as pdimport matplotlib # importing datasetdata = pd.read_csv(r'C:\Users\admin\Downloads\AlcoholSale.csv') # casting Date column to datetime objectdata['DATE'] = pd.to_datetime(data['DATE']) # Setting Date column as indexdata = data.set_index('DATE') # Creating the plotdata.plot() Output : Example: Horizontal trend Python3 # importing the librariesimport pandas as pdimport matplotlib # importing datasetdata = pd.read_csv( r'C:\Users\admin\Downloads\monthly-beer-production-in-austr.csv') # casting Month column to datetime objectdata['Month'] = pd.to_datetime(data['Month']) # Setting Month as indexdata = data.set_index('Month') # Creating the plotdata['1984':'1994'].plot() Output : Decomposition To see the complexity behind linear visualization we can decompose the data. The function called seasonal_decompose within the statsmodels package can help us to decompose the data into its components/show patterns — trend, seasonality and residual components of time series. Here we are interested in trend component only so will acces it using seasonal_decompose().trend . seasonal_decompose function uses moving averages method to estimate the trend. Syntax : statsmodels.tsa.seasonal.seasonal_decompose(x, model=’additive’, period=None, extrapolate_trend=0) Important parameters : x : array-like. Time-Series. If 2d, individual series are in columns. x must contain 2 complete cycles. model : {“additive”, “multiplicative”}, optional (Depends on nature on seasonal component) period(freq.) : int, optional . Must be use if x is not pandas object or index of x does not have a frequency. Returns : A object with seasonal, trend, and resid attributes. Example : Python3 # importing functionfrom statsmodels.tsa.seasonal import seasonal_decompose # creating trend object by assuming multiplicative modeloutput = seasonal_decompose(data, model='multiplicative').trend # creating plotoutput.plot() Output : varshagumber28 Picked Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n12 Dec, 2021" }, { "code": null, "e": 24686, "s": 24292, "text": "Time series data is a sequence of data points that measure some variable over ordered period of time. It is the fastest-growing category of databases as it is widely used in a variety of industries to understand and forecast data patterns. So while preparing this time series data for modeling it’s important to check for time series components or patterns. One of these components is Trend. " }, { "code": null, "e": 25140, "s": 24686, "text": "Trend is a pattern in data that shows the movement of a series to relatively higher or lower values over a long period of time. In other words, a trend is observed when there is an increasing or decreasing slope in the time series. Trend usually happens for some time and then disappears, it does not repeat. For example, some new song comes, it goes trending for a while, and then disappears. There is fairly any chance that it would be trending again." }, { "code": null, "e": 25159, "s": 25140, "text": "A trend could be :" }, { "code": null, "e": 25248, "s": 25159, "text": "Uptrend: Time Series Analysis shows a general pattern that is upward then it is Uptrend." }, { "code": null, "e": 25335, "s": 25248, "text": "Downtrend: Time Series Analysis shows a pattern that is downward then it is Downtrend." }, { "code": null, "e": 25442, "s": 25335, "text": "Horizontal or Stationary trend: If no pattern observed then it is called a Horizontal or stationary trend." }, { "code": null, "e": 25530, "s": 25442, "text": "You can find trends in data either by simply visualizing or by the decomposing dataset." }, { "code": null, "e": 25599, "s": 25530, "text": "By simply plotting the dataset you can see the general trend in data" }, { "code": null, "e": 25612, "s": 25599, "text": "Approach : " }, { "code": null, "e": 25626, "s": 25612, "text": "Import module" }, { "code": null, "e": 25639, "s": 25626, "text": "Load dataset" }, { "code": null, "e": 25677, "s": 25639, "text": "Cast month column to date time object" }, { "code": null, "e": 25696, "s": 25677, "text": "Set month as index" }, { "code": null, "e": 25708, "s": 25696, "text": "Create plot" }, { "code": null, "e": 25858, "s": 25708, "text": "Note: In the examples given below the same code is used to show all three trends just the dataset used is different to reflect that particular trend." }, { "code": null, "e": 25889, "s": 25858, "text": "Link for datasets : click here" }, { "code": null, "e": 25907, "s": 25889, "text": "Example: Uptrend " }, { "code": null, "e": 25915, "s": 25907, "text": "Python3" }, { "code": "# importing the librariesimport pandas as pdimport matplotlib # importing datasetdata = pd.read_csv(r'C:\\Users\\admin\\Downloads\\Electric_Production.csv') # casting Month column to datetime objectdata['DATE'] = pd.to_datetime(data['DATE']) # Setting Month as indexdata = data.set_index('DATE') # Creating the plotdata.plot()", "e": 26238, "s": 25915, "text": null }, { "code": null, "e": 26248, "s": 26238, "text": "Output : " }, { "code": null, "e": 26267, "s": 26248, "text": "Example: Downtrend" }, { "code": null, "e": 26275, "s": 26267, "text": "Python3" }, { "code": "import pandas as pdimport matplotlib # importing datasetdata = pd.read_csv(r'C:\\Users\\admin\\Downloads\\AlcoholSale.csv') # casting Date column to datetime objectdata['DATE'] = pd.to_datetime(data['DATE']) # Setting Date column as indexdata = data.set_index('DATE') # Creating the plotdata.plot()", "e": 26570, "s": 26275, "text": null }, { "code": null, "e": 26580, "s": 26570, "text": "Output : " }, { "code": null, "e": 26606, "s": 26580, "text": "Example: Horizontal trend" }, { "code": null, "e": 26614, "s": 26606, "text": "Python3" }, { "code": "# importing the librariesimport pandas as pdimport matplotlib # importing datasetdata = pd.read_csv( r'C:\\Users\\admin\\Downloads\\monthly-beer-production-in-austr.csv') # casting Month column to datetime objectdata['Month'] = pd.to_datetime(data['Month']) # Setting Month as indexdata = data.set_index('Month') # Creating the plotdata['1984':'1994'].plot()", "e": 26972, "s": 26614, "text": null }, { "code": null, "e": 26982, "s": 26972, "text": "Output : " }, { "code": null, "e": 26996, "s": 26982, "text": "Decomposition" }, { "code": null, "e": 27371, "s": 26996, "text": "To see the complexity behind linear visualization we can decompose the data. The function called seasonal_decompose within the statsmodels package can help us to decompose the data into its components/show patterns — trend, seasonality and residual components of time series. Here we are interested in trend component only so will acces it using seasonal_decompose().trend ." }, { "code": null, "e": 27450, "s": 27371, "text": "seasonal_decompose function uses moving averages method to estimate the trend." }, { "code": null, "e": 27460, "s": 27450, "text": "Syntax : " }, { "code": null, "e": 27559, "s": 27460, "text": "statsmodels.tsa.seasonal.seasonal_decompose(x, model=’additive’, period=None, extrapolate_trend=0)" }, { "code": null, "e": 27583, "s": 27559, "text": "Important parameters : " }, { "code": null, "e": 27689, "s": 27583, "text": "x : array-like. Time-Series. If 2d, individual series are in columns. x must contain 2 complete cycles." }, { "code": null, "e": 27780, "s": 27689, "text": "model : {“additive”, “multiplicative”}, optional (Depends on nature on seasonal component)" }, { "code": null, "e": 27892, "s": 27780, "text": "period(freq.) : int, optional . Must be use if x is not pandas object or index of x does not have a frequency." }, { "code": null, "e": 27955, "s": 27892, "text": "Returns : A object with seasonal, trend, and resid attributes." }, { "code": null, "e": 27966, "s": 27955, "text": "Example : " }, { "code": null, "e": 27974, "s": 27966, "text": "Python3" }, { "code": "# importing functionfrom statsmodels.tsa.seasonal import seasonal_decompose # creating trend object by assuming multiplicative modeloutput = seasonal_decompose(data, model='multiplicative').trend # creating plotoutput.plot()", "e": 28199, "s": 27974, "text": null }, { "code": null, "e": 28209, "s": 28199, "text": "Output : " }, { "code": null, "e": 28224, "s": 28209, "text": "varshagumber28" }, { "code": null, "e": 28231, "s": 28224, "text": "Picked" }, { "code": null, "e": 28245, "s": 28231, "text": "Python-pandas" }, { "code": null, "e": 28252, "s": 28245, "text": "Python" }, { "code": null, "e": 28350, "s": 28252, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28382, "s": 28350, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28438, "s": 28382, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28480, "s": 28438, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28522, "s": 28480, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28544, "s": 28522, "text": "Defaultdict in Python" }, { "code": null, "e": 28583, "s": 28544, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28614, "s": 28583, "text": "Python | os.path.join() method" }, { "code": null, "e": 28669, "s": 28614, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28698, "s": 28669, "text": "Create a directory in Python" } ]
Deploying Smart Contract on Test/Main Network Using Truffle - GeeksforGeeks
14 Oct, 2020 A Smart Contract is a computer program that directly and automatically controls the transfer of digital assets between the parties under certain conditions. A smart contract works in the same way as a traditional contract while also automatically enforcing the contract. Smart contracts are programs that execute exactly as they are set up(coded, programmed) by their creators. Just like a traditional contract is enforceable by law, smart contracts are enforceable by code. Up to this point, we have our smart contracts written and compiled without any errors. Let’s see how we can deploy our smart contract on rinkeby test network. Deploying a contract on the main blockchain costs money (in the form of cryptocurrency), so we have test networks to develop and test our smart contracts. In the test network, fake ethers are added to our wallet to facilitate transactions. One such network provided by Ethereum is Rinkeby. MetaMask provides browser support to communicate with blockchain networks. We can add an account, get ethers to our account or send transactions to another account. It is like a wallet from where we can spend our cryptocurrency. To install metamask, Go to https://metamask.io/ Download it to your browser. Go to https://metamask.io/ Download it to your browser. On starting for the first time, to set up your wallet MetaMask gives you a seed phrase of 12 words. This phrase is unique and can be used to restore your account, in case you forgot your password. Deploying contracts on the test network requires some test ethers, which, obviously does not have any real value. In the blockchain, every interaction with a contract costs some fees(gas) and the interaction is known as a transaction. Since deploying our contract on rinkeby is also a transaction, we need some test ethers to facilitate the transaction. To get test ethers we will be using a Faucet. Go to https://faucet.metamask.io/ and do the simple task asked to get some free test ethers. We need an API through which we can access the rinkeby network. Infura makes it quite easier to access the test/main network and deploy our contract on them. Create an infura endpoint on the rinkeby network. Go to infura.io and sign up for an account if you don’t have one. Click on Ethereum on the left panel. Write your project name and click to create the project. This should create an endpoint for your project and it should look somewhat similar to below. Now we need an npm package HDWalletProvider, this signs our transaction and makes the deployment process a less pain. npm install @truffle/hdwallet-provider Now we have, our truffle hdWallet-provider in our node modules, an endpoint from infura account, and the seed-phrase which we have used during MetaMask installation. Let’s configure our truffle-config.js. Open truffle-config.js and import truffle hdWallet provider at the top. const HDWalletProvider = require('truffle-hdwallet-provider'); To configure the network, we will edit the network section of truffle-config.js. This should look somewhat like this. const HDWalletProvider = require('truffle-hdwallet-provider'); // Useful for deploying to a public network. // NB: It's important to wrap the provider as a function. // ropsten: { // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`), // network_id: 3, // Ropsten's id // gas: 5500000, // Ropsten has a lower block limit than mainnet // confirmations: 2, // # of confs to wait between deployments. (default: 0) // timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) // skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) // }, Replace ropsten with rinkeby. Mnemonic with seed-phrase (obtained from MetaMask). https://ropsten.infura.io/v3/YOUR-PROJECT-ID with the infura endpoint you created for your project. network_id:4, After doing these changes your section should look something like this. rinkeby: { provider: () => new HDWalletProvider(`YOUR_SEED_PHRASE`, `https://rinkeby.infura.io/v3/b63bffeec2e545f2a3e9b3e9423d6180`), network_id: 4, // Ropsten's id gas: 5500000, // Ropsten has a lower block limit than mainnet confirmations: 2, // # of confs to wait between deployments. (default: 0) timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) }, Save the file and then open the truffle console and then migrate on the rinkeby network. truffle migrate --network rinkeby That’s all done. Once your contract is deployed on rinkeby, you can check the transaction detail on etherscan. Go to the link and copy and paste your deployed contract address to get the details about your transaction. Note: To deploy on the main network, get infura endpoint for the main network, and configure the config file.Replace rinkeby with main, and network id with 1.Then truffle migrate –network main. To deploy on the main network, get infura endpoint for the main network, and configure the config file. Replace rinkeby with main, and network id with 1. Then truffle migrate –network main. Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Decentralized Voting Application (DApps)? Solidity - Break and Continue Statements Creating Ownable Contracts in Solidity Solidity - Libraries Solidity - Programming ERC-20 Token Solidity - Assembly Solidity - Basics of Contracts Build a To-do List Web Application Powered by Blockchain Solidity - Decision Making Statements What is Escrow Smart Contract?
[ { "code": null, "e": 24456, "s": 24428, "text": "\n14 Oct, 2020" }, { "code": null, "e": 24931, "s": 24456, "text": "A Smart Contract is a computer program that directly and automatically controls the transfer of digital assets between the parties under certain conditions. A smart contract works in the same way as a traditional contract while also automatically enforcing the contract. Smart contracts are programs that execute exactly as they are set up(coded, programmed) by their creators. Just like a traditional contract is enforceable by law, smart contracts are enforceable by code." }, { "code": null, "e": 25380, "s": 24931, "text": "Up to this point, we have our smart contracts written and compiled without any errors. Let’s see how we can deploy our smart contract on rinkeby test network. Deploying a contract on the main blockchain costs money (in the form of cryptocurrency), so we have test networks to develop and test our smart contracts. In the test network, fake ethers are added to our wallet to facilitate transactions. One such network provided by Ethereum is Rinkeby." }, { "code": null, "e": 25631, "s": 25380, "text": "MetaMask provides browser support to communicate with blockchain networks. We can add an account, get ethers to our account or send transactions to another account. It is like a wallet from where we can spend our cryptocurrency. To install metamask, " }, { "code": null, "e": 25687, "s": 25631, "text": "Go to https://metamask.io/ Download it to your browser." }, { "code": null, "e": 25715, "s": 25687, "text": "Go to https://metamask.io/ " }, { "code": null, "e": 25744, "s": 25715, "text": "Download it to your browser." }, { "code": null, "e": 25941, "s": 25744, "text": "On starting for the first time, to set up your wallet MetaMask gives you a seed phrase of 12 words. This phrase is unique and can be used to restore your account, in case you forgot your password." }, { "code": null, "e": 26436, "s": 25941, "text": "Deploying contracts on the test network requires some test ethers, which, obviously does not have any real value. In the blockchain, every interaction with a contract costs some fees(gas) and the interaction is known as a transaction. Since deploying our contract on rinkeby is also a transaction, we need some test ethers to facilitate the transaction. To get test ethers we will be using a Faucet. Go to https://faucet.metamask.io/ and do the simple task asked to get some free test ethers. " }, { "code": null, "e": 26645, "s": 26436, "text": "We need an API through which we can access the rinkeby network. Infura makes it quite easier to access the test/main network and deploy our contract on them. Create an infura endpoint on the rinkeby network. " }, { "code": null, "e": 26711, "s": 26645, "text": "Go to infura.io and sign up for an account if you don’t have one." }, { "code": null, "e": 26748, "s": 26711, "text": "Click on Ethereum on the left panel." }, { "code": null, "e": 26805, "s": 26748, "text": "Write your project name and click to create the project." }, { "code": null, "e": 26899, "s": 26805, "text": "This should create an endpoint for your project and it should look somewhat similar to below." }, { "code": null, "e": 27018, "s": 26899, "text": "Now we need an npm package HDWalletProvider, this signs our transaction and makes the deployment process a less pain. " }, { "code": null, "e": 27059, "s": 27018, "text": "npm install @truffle/hdwallet-provider\n\n" }, { "code": null, "e": 27225, "s": 27059, "text": "Now we have, our truffle hdWallet-provider in our node modules, an endpoint from infura account, and the seed-phrase which we have used during MetaMask installation." }, { "code": null, "e": 27337, "s": 27225, "text": "Let’s configure our truffle-config.js. Open truffle-config.js and import truffle hdWallet provider at the top." }, { "code": null, "e": 27401, "s": 27337, "text": "const HDWalletProvider = require('truffle-hdwallet-provider');\n" }, { "code": null, "e": 27519, "s": 27401, "text": "To configure the network, we will edit the network section of truffle-config.js. This should look somewhat like this." }, { "code": null, "e": 28233, "s": 27519, "text": "const HDWalletProvider = require('truffle-hdwallet-provider'); // Useful for deploying to a public network.\n // NB: It's important to wrap the provider as a function.\n // ropsten: {\n // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),\n // network_id: 3, // Ropsten's id\n // gas: 5500000, // Ropsten has a lower block limit than mainnet\n // confirmations: 2, // # of confs to wait between deployments. (default: 0)\n // timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)\n // skipDryRun: true // Skip dry run before migrations? (default: false for public nets )\n // },\n" }, { "code": null, "e": 28263, "s": 28233, "text": "Replace ropsten with rinkeby." }, { "code": null, "e": 28315, "s": 28263, "text": "Mnemonic with seed-phrase (obtained from MetaMask)." }, { "code": null, "e": 28415, "s": 28315, "text": "https://ropsten.infura.io/v3/YOUR-PROJECT-ID with the infura endpoint you created for your project." }, { "code": null, "e": 28429, "s": 28415, "text": "network_id:4," }, { "code": null, "e": 28501, "s": 28429, "text": "After doing these changes your section should look something like this." }, { "code": null, "e": 29049, "s": 28501, "text": " rinkeby: {\n provider: () => new HDWalletProvider(`YOUR_SEED_PHRASE`, `https://rinkeby.infura.io/v3/b63bffeec2e545f2a3e9b3e9423d6180`),\n network_id: 4, // Ropsten's id\n gas: 5500000, // Ropsten has a lower block limit than mainnet\n confirmations: 2, // # of confs to wait between deployments. (default: 0)\n timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)\n skipDryRun: true // Skip dry run before migrations? (default: false for public nets )\n },\n" }, { "code": null, "e": 29138, "s": 29049, "text": "Save the file and then open the truffle console and then migrate on the rinkeby network." }, { "code": null, "e": 29173, "s": 29138, "text": "truffle migrate --network rinkeby\n" }, { "code": null, "e": 29393, "s": 29173, "text": "That’s all done. Once your contract is deployed on rinkeby, you can check the transaction detail on etherscan. Go to the link and copy and paste your deployed contract address to get the details about your transaction." }, { "code": null, "e": 29399, "s": 29393, "text": "Note:" }, { "code": null, "e": 29587, "s": 29399, "text": "To deploy on the main network, get infura endpoint for the main network, and configure the config file.Replace rinkeby with main, and network id with 1.Then truffle migrate –network main." }, { "code": null, "e": 29691, "s": 29587, "text": "To deploy on the main network, get infura endpoint for the main network, and configure the config file." }, { "code": null, "e": 29741, "s": 29691, "text": "Replace rinkeby with main, and network id with 1." }, { "code": null, "e": 29777, "s": 29741, "text": "Then truffle migrate –network main." }, { "code": null, "e": 29786, "s": 29777, "text": "Solidity" }, { "code": null, "e": 29884, "s": 29786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29934, "s": 29884, "text": "What is Decentralized Voting Application (DApps)?" }, { "code": null, "e": 29975, "s": 29934, "text": "Solidity - Break and Continue Statements" }, { "code": null, "e": 30014, "s": 29975, "text": "Creating Ownable Contracts in Solidity" }, { "code": null, "e": 30035, "s": 30014, "text": "Solidity - Libraries" }, { "code": null, "e": 30071, "s": 30035, "text": "Solidity - Programming ERC-20 Token" }, { "code": null, "e": 30091, "s": 30071, "text": "Solidity - Assembly" }, { "code": null, "e": 30122, "s": 30091, "text": "Solidity - Basics of Contracts" }, { "code": null, "e": 30179, "s": 30122, "text": "Build a To-do List Web Application Powered by Blockchain" }, { "code": null, "e": 30217, "s": 30179, "text": "Solidity - Decision Making Statements" } ]
5 Explainable Machine Learning Models You Should Understand | Towards Data Science
As we know, Machine Learning is ubiquitous in our day to day lives. From product recommendations on Amazon, targeted advertising, and suggestions of what to watch, to funny Instagram filters. If something goes wrong with these, it probably won’t ruin your life. Maybe you won’t get that perfect selfie, or maybe companies will have to spend more on advertising. How about facial recognition in law enforcement? Loan or mortgage applications? Driverless vehicles? In these high-risk applications, we can’t go in blind. We need to be able to dissect our model, we will need to be able to understand and explain our model before it goes anywhere near a production system. Explainable Machine Learning is essential when we are making decisions about people that can negatively impact their lives such as mortgages or credit scoring. Using explainable models also allows more efficient debugging as well as better understand of fairness, privacy, causality, and more trust in the model. Types of Explainability Explainable Models- Generalised Linear Models- Decision Trees- Generalised Additive Models- Monotonic Gradient Boosting- TabNet Comparison Conclusion Post-hoc: This is when we explain a model after predictions have been made or after the model has been trained. This is great because these methods allow us to explain highly complicated models. However these methods can be fooled, are flawed under specific conditions and require an extra layer of complexity to generate the explanations. Common examples are the SHAP and LIME Python packages. Inherent: Some models can be explained out of the box, without additional models or libraries laid on top. These are typically simpler and in some cases might have less predictive power — although some researchers argue that this isn’t always the case! This article will cover inherently explainable models. Lipton, 2016 (https://arxiv.org/abs/1606.03490) defines model explainability using 3 criteria: Simulatability: Can a human walk through the model’s steps in a ‘reasonable’ amount of time?Decomposability: Can all aspects of the model, including its features, parameters and weights be broken down?Algorithmic Transparency: Can we understand how the model will react to unseen data. Simulatability: Can a human walk through the model’s steps in a ‘reasonable’ amount of time? Decomposability: Can all aspects of the model, including its features, parameters and weights be broken down? Algorithmic Transparency: Can we understand how the model will react to unseen data. You may already be aware of models that meet this criteria; Decision Trees and Logistic Regression. As long as the model doesn’t use too many features, both meet all 3 criteria. Even if you use an explainable model, using too many features or highly engineered features can reduce your model explainability. We need to keep our data and preprocessing explainable too. However, there are several lesser known explainable models that are great to have in your toolkit. These methods also can have more predictive power than Decision Trees and Logistic Regression, while still maintaining some level of explainability, allowing you to balance explainability with accuracy in your next project. What is it and how does it work? A GLM is really just a fancy way of talking about Linear or Logistic Regression. The key concept here is that there are other linear models that make these more flexible. A GLM has 3 components: Linear predictor: This is just the regression equation — a linear combination of variables and some predictor variable. Linear predictor: This is just the regression equation — a linear combination of variables and some predictor variable. 2. Link function: Links our linear combination of variables to a probability distribution. In linear regression, this is just the identity link function. 3. Probability distribution: This is how our y variable is generated. In Linear regression, this is a normal distribution. By varying these, we can get different models. Using Logit link function with a Bernoulli distribution gets us a logistic regression. A lesser known version is the Poisson regression, which uses a Poisson distribution. This assumes our linear combination of variables relates to the logarithm of y. To learn more about Logistic Regression, check out my article here: towardsdatascience.com Why is it explainable? Because its just simple(ish) maths The below graph shows a simple linear regression equation for just one variable. We know that we can calculate y, our target, for any value of x by using the line. We also know how the line is calculated (by minimising the errors). We can scale this up to as many variables as we want and the maths still hold. We simply add our terms together to generate a result. Logistic or Poisson Regression are more complex but the core concept holds true. We are summing a linear combination of variables. The coefficients mean something In a linear regression, our coefficients are given in terms of the target variable. This allows us to make statements such as: Increasing square footage by 50m2 will increase our house price by £1000 In logistic regression, these are in terms of log odds which we can convert to probabilities. The fact that these coefficients can be converted into human-understandable statements really increases the explainability of linear models. Interactions have to be programmed explicitly Tree based models will work out interactions between variables which can increase complexity. Many explainability methods don’t cover interactions well and they can be hard to work out. For example Increasing square footage by 50m2 will increase our house price by £1000 until we get to 200m2, where our house price increases by £1000 per 50m2 * number of bedrooms. This type of complex relationship will only be found in a Linear model if it is calculated and programmed in explicitly during feature engineering. Implementation scikit-learn offers an implementation of GLMs Statsmodels also offers a good implementation What is it and how does it work? Most people should have seen a Decision Tree at some point in their lives! The algorithmic version uses some simple maths to generate an ‘optimum’ Decision Tree, i.e. the tree which splits our data best. To understand how it works, take a look here: towardsdatascience.com Why is it explainable? The great thing about Decision Trees is that we can literally just extract the whole tree and follow along why the model made a prediction for any sample in the dataset. Once trees get very large (max_depth = 7+), they become difficult for humans to follow due to exponential growth in the number of leaves. However at this point we could still write some basic code to highlight the path our data took to reach its prediction, as well as test how the model will react to unseen data. I find these to be one of the most explainable models due to very little maths and a concept which is found elsewhere in the world. Implementation As usual, scikit-learn would be my go-to for this model. To plot the tree, there are many different options, here is a good list. What is it and how does it work? Generalised Additive Models (GAMs) are an extension of GLM’s that drop one of the main limitations; we can now model non-linear relationships in our data. GAMs do these by using a series of complex functions known as splines to estimate each variable. We still sum up our variables, but splines mean the variables and target value can have a non-linear relationship. To read more about GAMs, take a look here: towardsdatascience.com Why is it explainable? Undoubtedly, GAMs are less explainable than Logistic or Linear regression. The model is much more complex, as is the maths behind it. However, they still maintain a level to explainability which is a great trade-off when you consider their flexibility. A combination of non-linear variables? The target variable is still just the sum of all other variables with some weighting, we now have a complex function modelling each variable. We can still extract and visualise this function per variable and most GAM packages use partial dependence plots to do this for all features. Interactions have to be programmed manually which limits complexity. We also can understand broadly how the model will behave on unseen data, as we know the spline functions for each feature. Implementation From my research, it seems that the mgcv package in R is the best for GAMs. However, I prefer Python; the two best options are Statsmodels and PyGAM. Microsoft Research have open sourced their InterpretML package which includes their Explainable Boosting Machine, which they term GAM 2.0, as it uses GAMs with automatic interaction terms and gradient boosting to maintain explainability, increase performance and reduce the need for Data Scientists to get to deep into the model. What is it and how does it work? Gradient Boosting models are considered the best in class for tabular data, but due to the nature of boosting, they are not interpretable. These models can use hundreds of individual trees with different weights. They also tend to work out interaction terms themselves which we have little transparency around. It is common to use SHAP or LIME to increase interpretability with these models. A monotonic relationship is where the target and a feature have a linear relationship, for example: Your BMI increases and your risk of heart attack increases. Your credit score decreases and your likelihood to get a loan decreases. The amount of rain increases and the number of bike rented decreases. Linear models are fully monotonic, but as gradient boosting includes interactions and can model non-linear relationships, they typically do not generate monotonic relationships. XGBoost, LightGBM and Catboost all have a simple hyperparameter that forces a variable to have a positive or negative monotonic relationship. Why is it explainable? Using monotonic relationships means we can use statements like those above to explain our model. It causes the model to fill the Algorithmic Transparency criteria because this relationship is fixed. We can also build some of our real world knowledge into the model which can make it more understandable for businesspeople, giving it more change of reaching production. Implementation XGBoost In XGBoost we specify the monotone_constraints parameter a string tuple (brackets inside speech marks) with one number per feature in our dataset, so “(1,0,-1)” indicates features 1, 2 and 3. 1 is a positive monotonic relationship, -1 is negative and 0 is no relationship. import xgboost as xgbparams = {'monotone_constraints':'(1,0,-1)'}model = xgb.train(params, X_train, num_boost_round = 1000, early_stopping_rounds = 10) LightGBM LightGBM is broadly the same as XGBoost but we are required to pass our features as a list rather than a string/tuple. LightGBM also offers an extra parameter the method. Using this means we can choose how strongly the model will try to stick the constraint. The documentation states: basic, the most basic monotone constraints method. It does not slow the library at all, but over-constrains the predictions intermediate, a more advanced method, which may slow the library very slightly. However, this method is much less constraining than the basic method and should significantly improve the results advanced, an even more advanced method, which may slow the library. However, this method is even less constraining than the intermediate method and should again significantly improve the results import lightgbm as lgbparams = {'monotone_constraints': [-1, 0, 1], 'monotone_constraints_method':'basic'}model = lgb.train(params, X_train, num_round = 1000, early_stopping_rounds = 10) Catboost Catboost is very similar to the others but offers more flexibility as we can pass the constraints as an array, use slicing and name a feature explicitily. The parameter is called monotone_constraints and you can check out the Catboost docs here. What is it and how does it work? TabNet was published by Google Brain researchers in in 2019. Traditionally, Neural Network approaches have not significantly improved on gradient boosting when dealing with Tabular data. However, Tabnet was able to outperform the leading tree based models across a variety of benchmarks. It is considerably more explainable than boosted tree models as it has built-in explainability. It can also be used without any feature preprocessing. My article on TabNet covers the model in more detail, take a look here: towardsdatascience.com Why is it explainable? TabNet uses a sequential attention mechanism to select the most important features, this influences the ‘mask’ whichcovers up the least important features. We can use the weights of this mask to understand which features are being used more often than others, which essentially allows us to understand which features the model is using to make its predictions. Feature selection is performed at the row level of the dataset, which means we can actually explore which features were selected for a single prediction. The number of masks is a hyperparameter of the model Implementation The best way to use TabNet is with Dreamquark’s PyTorch implementation. It uses a scikit-learn style wrapper and is GPU compatible. Dreamquark also provide some really great notebooks which perfectly show how to implement TabNet while also working to validate the original authors claims about the models accuracy on certain benchmarks. Classification github.com Regression github.com Lets go back to Lipton’s 3 criteria and apply these to each model. As a reminder, the criteria are... Simulatability: Can a human walk through the model’s steps in a ‘reasonable’ amount of time?Decomposability: Can all aspects of the model, including its features, parameters and weights be broken down?Algorithmic Transparency: Can we understand how the model will react to unseen data. Simulatability: Can a human walk through the model’s steps in a ‘reasonable’ amount of time? Decomposability: Can all aspects of the model, including its features, parameters and weights be broken down? Algorithmic Transparency: Can we understand how the model will react to unseen data. We also want to consider Local Explainability; to what extend can a single prediction be made by the model, in terms of what features it used and what extent did it use each feature to make its decision. I have summarised this in the chart below, scoring each model Low, Medium or High for each criteria. This isn’t an exact science but you can consider each score relative to a Linear Regression. Remember, that any feature engineering can completely throw these scores off. Creating complex interaction terms, mathematical transformations or features derived from a neural network may increase accuracy but will certainly decrease explainability. More features can also reduce explainability. The drive and discussions around model explainability is only increasing. With AI being used in language modelling, facial recognition and driverless cars, having models that can give reasoning behind their decision is more essential than ever. Give one of these explainable models a try in your next project and let me know how it turns out.
[ { "code": null, "e": 364, "s": 172, "text": "As we know, Machine Learning is ubiquitous in our day to day lives. From product recommendations on Amazon, targeted advertising, and suggestions of what to watch, to funny Instagram filters." }, { "code": null, "e": 534, "s": 364, "text": "If something goes wrong with these, it probably won’t ruin your life. Maybe you won’t get that perfect selfie, or maybe companies will have to spend more on advertising." }, { "code": null, "e": 635, "s": 534, "text": "How about facial recognition in law enforcement? Loan or mortgage applications? Driverless vehicles?" }, { "code": null, "e": 841, "s": 635, "text": "In these high-risk applications, we can’t go in blind. We need to be able to dissect our model, we will need to be able to understand and explain our model before it goes anywhere near a production system." }, { "code": null, "e": 1001, "s": 841, "text": "Explainable Machine Learning is essential when we are making decisions about people that can negatively impact their lives such as mortgages or credit scoring." }, { "code": null, "e": 1154, "s": 1001, "text": "Using explainable models also allows more efficient debugging as well as better understand of fairness, privacy, causality, and more trust in the model." }, { "code": null, "e": 1178, "s": 1154, "text": "Types of Explainability" }, { "code": null, "e": 1306, "s": 1178, "text": "Explainable Models- Generalised Linear Models- Decision Trees- Generalised Additive Models- Monotonic Gradient Boosting- TabNet" }, { "code": null, "e": 1317, "s": 1306, "text": "Comparison" }, { "code": null, "e": 1328, "s": 1317, "text": "Conclusion" }, { "code": null, "e": 1723, "s": 1328, "text": "Post-hoc: This is when we explain a model after predictions have been made or after the model has been trained. This is great because these methods allow us to explain highly complicated models. However these methods can be fooled, are flawed under specific conditions and require an extra layer of complexity to generate the explanations. Common examples are the SHAP and LIME Python packages." }, { "code": null, "e": 1976, "s": 1723, "text": "Inherent: Some models can be explained out of the box, without additional models or libraries laid on top. These are typically simpler and in some cases might have less predictive power — although some researchers argue that this isn’t always the case!" }, { "code": null, "e": 2031, "s": 1976, "text": "This article will cover inherently explainable models." }, { "code": null, "e": 2126, "s": 2031, "text": "Lipton, 2016 (https://arxiv.org/abs/1606.03490) defines model explainability using 3 criteria:" }, { "code": null, "e": 2412, "s": 2126, "text": "Simulatability: Can a human walk through the model’s steps in a ‘reasonable’ amount of time?Decomposability: Can all aspects of the model, including its features, parameters and weights be broken down?Algorithmic Transparency: Can we understand how the model will react to unseen data." }, { "code": null, "e": 2505, "s": 2412, "text": "Simulatability: Can a human walk through the model’s steps in a ‘reasonable’ amount of time?" }, { "code": null, "e": 2615, "s": 2505, "text": "Decomposability: Can all aspects of the model, including its features, parameters and weights be broken down?" }, { "code": null, "e": 2700, "s": 2615, "text": "Algorithmic Transparency: Can we understand how the model will react to unseen data." }, { "code": null, "e": 2878, "s": 2700, "text": "You may already be aware of models that meet this criteria; Decision Trees and Logistic Regression. As long as the model doesn’t use too many features, both meet all 3 criteria." }, { "code": null, "e": 3068, "s": 2878, "text": "Even if you use an explainable model, using too many features or highly engineered features can reduce your model explainability. We need to keep our data and preprocessing explainable too." }, { "code": null, "e": 3391, "s": 3068, "text": "However, there are several lesser known explainable models that are great to have in your toolkit. These methods also can have more predictive power than Decision Trees and Logistic Regression, while still maintaining some level of explainability, allowing you to balance explainability with accuracy in your next project." }, { "code": null, "e": 3424, "s": 3391, "text": "What is it and how does it work?" }, { "code": null, "e": 3595, "s": 3424, "text": "A GLM is really just a fancy way of talking about Linear or Logistic Regression. The key concept here is that there are other linear models that make these more flexible." }, { "code": null, "e": 3619, "s": 3595, "text": "A GLM has 3 components:" }, { "code": null, "e": 3739, "s": 3619, "text": "Linear predictor: This is just the regression equation — a linear combination of variables and some predictor variable." }, { "code": null, "e": 3859, "s": 3739, "text": "Linear predictor: This is just the regression equation — a linear combination of variables and some predictor variable." }, { "code": null, "e": 4013, "s": 3859, "text": "2. Link function: Links our linear combination of variables to a probability distribution. In linear regression, this is just the identity link function." }, { "code": null, "e": 4136, "s": 4013, "text": "3. Probability distribution: This is how our y variable is generated. In Linear regression, this is a normal distribution." }, { "code": null, "e": 4270, "s": 4136, "text": "By varying these, we can get different models. Using Logit link function with a Bernoulli distribution gets us a logistic regression." }, { "code": null, "e": 4435, "s": 4270, "text": "A lesser known version is the Poisson regression, which uses a Poisson distribution. This assumes our linear combination of variables relates to the logarithm of y." }, { "code": null, "e": 4503, "s": 4435, "text": "To learn more about Logistic Regression, check out my article here:" }, { "code": null, "e": 4526, "s": 4503, "text": "towardsdatascience.com" }, { "code": null, "e": 4549, "s": 4526, "text": "Why is it explainable?" }, { "code": null, "e": 4584, "s": 4549, "text": "Because its just simple(ish) maths" }, { "code": null, "e": 4816, "s": 4584, "text": "The below graph shows a simple linear regression equation for just one variable. We know that we can calculate y, our target, for any value of x by using the line. We also know how the line is calculated (by minimising the errors)." }, { "code": null, "e": 4950, "s": 4816, "text": "We can scale this up to as many variables as we want and the maths still hold. We simply add our terms together to generate a result." }, { "code": null, "e": 5081, "s": 4950, "text": "Logistic or Poisson Regression are more complex but the core concept holds true. We are summing a linear combination of variables." }, { "code": null, "e": 5113, "s": 5081, "text": "The coefficients mean something" }, { "code": null, "e": 5240, "s": 5113, "text": "In a linear regression, our coefficients are given in terms of the target variable. This allows us to make statements such as:" }, { "code": null, "e": 5313, "s": 5240, "text": "Increasing square footage by 50m2 will increase our house price by £1000" }, { "code": null, "e": 5407, "s": 5313, "text": "In logistic regression, these are in terms of log odds which we can convert to probabilities." }, { "code": null, "e": 5548, "s": 5407, "text": "The fact that these coefficients can be converted into human-understandable statements really increases the explainability of linear models." }, { "code": null, "e": 5594, "s": 5548, "text": "Interactions have to be programmed explicitly" }, { "code": null, "e": 5792, "s": 5594, "text": "Tree based models will work out interactions between variables which can increase complexity. Many explainability methods don’t cover interactions well and they can be hard to work out. For example" }, { "code": null, "e": 5960, "s": 5792, "text": "Increasing square footage by 50m2 will increase our house price by £1000 until we get to 200m2, where our house price increases by £1000 per 50m2 * number of bedrooms." }, { "code": null, "e": 6108, "s": 5960, "text": "This type of complex relationship will only be found in a Linear model if it is calculated and programmed in explicitly during feature engineering." }, { "code": null, "e": 6123, "s": 6108, "text": "Implementation" }, { "code": null, "e": 6169, "s": 6123, "text": "scikit-learn offers an implementation of GLMs" }, { "code": null, "e": 6215, "s": 6169, "text": "Statsmodels also offers a good implementation" }, { "code": null, "e": 6248, "s": 6215, "text": "What is it and how does it work?" }, { "code": null, "e": 6452, "s": 6248, "text": "Most people should have seen a Decision Tree at some point in their lives! The algorithmic version uses some simple maths to generate an ‘optimum’ Decision Tree, i.e. the tree which splits our data best." }, { "code": null, "e": 6498, "s": 6452, "text": "To understand how it works, take a look here:" }, { "code": null, "e": 6521, "s": 6498, "text": "towardsdatascience.com" }, { "code": null, "e": 6544, "s": 6521, "text": "Why is it explainable?" }, { "code": null, "e": 6714, "s": 6544, "text": "The great thing about Decision Trees is that we can literally just extract the whole tree and follow along why the model made a prediction for any sample in the dataset." }, { "code": null, "e": 7029, "s": 6714, "text": "Once trees get very large (max_depth = 7+), they become difficult for humans to follow due to exponential growth in the number of leaves. However at this point we could still write some basic code to highlight the path our data took to reach its prediction, as well as test how the model will react to unseen data." }, { "code": null, "e": 7161, "s": 7029, "text": "I find these to be one of the most explainable models due to very little maths and a concept which is found elsewhere in the world." }, { "code": null, "e": 7176, "s": 7161, "text": "Implementation" }, { "code": null, "e": 7233, "s": 7176, "text": "As usual, scikit-learn would be my go-to for this model." }, { "code": null, "e": 7306, "s": 7233, "text": "To plot the tree, there are many different options, here is a good list." }, { "code": null, "e": 7339, "s": 7306, "text": "What is it and how does it work?" }, { "code": null, "e": 7494, "s": 7339, "text": "Generalised Additive Models (GAMs) are an extension of GLM’s that drop one of the main limitations; we can now model non-linear relationships in our data." }, { "code": null, "e": 7706, "s": 7494, "text": "GAMs do these by using a series of complex functions known as splines to estimate each variable. We still sum up our variables, but splines mean the variables and target value can have a non-linear relationship." }, { "code": null, "e": 7749, "s": 7706, "text": "To read more about GAMs, take a look here:" }, { "code": null, "e": 7772, "s": 7749, "text": "towardsdatascience.com" }, { "code": null, "e": 7795, "s": 7772, "text": "Why is it explainable?" }, { "code": null, "e": 8048, "s": 7795, "text": "Undoubtedly, GAMs are less explainable than Logistic or Linear regression. The model is much more complex, as is the maths behind it. However, they still maintain a level to explainability which is a great trade-off when you consider their flexibility." }, { "code": null, "e": 8087, "s": 8048, "text": "A combination of non-linear variables?" }, { "code": null, "e": 8371, "s": 8087, "text": "The target variable is still just the sum of all other variables with some weighting, we now have a complex function modelling each variable. We can still extract and visualise this function per variable and most GAM packages use partial dependence plots to do this for all features." }, { "code": null, "e": 8563, "s": 8371, "text": "Interactions have to be programmed manually which limits complexity. We also can understand broadly how the model will behave on unseen data, as we know the spline functions for each feature." }, { "code": null, "e": 8578, "s": 8563, "text": "Implementation" }, { "code": null, "e": 8728, "s": 8578, "text": "From my research, it seems that the mgcv package in R is the best for GAMs. However, I prefer Python; the two best options are Statsmodels and PyGAM." }, { "code": null, "e": 9058, "s": 8728, "text": "Microsoft Research have open sourced their InterpretML package which includes their Explainable Boosting Machine, which they term GAM 2.0, as it uses GAMs with automatic interaction terms and gradient boosting to maintain explainability, increase performance and reduce the need for Data Scientists to get to deep into the model." }, { "code": null, "e": 9091, "s": 9058, "text": "What is it and how does it work?" }, { "code": null, "e": 9483, "s": 9091, "text": "Gradient Boosting models are considered the best in class for tabular data, but due to the nature of boosting, they are not interpretable. These models can use hundreds of individual trees with different weights. They also tend to work out interaction terms themselves which we have little transparency around. It is common to use SHAP or LIME to increase interpretability with these models." }, { "code": null, "e": 9583, "s": 9483, "text": "A monotonic relationship is where the target and a feature have a linear relationship, for example:" }, { "code": null, "e": 9643, "s": 9583, "text": "Your BMI increases and your risk of heart attack increases." }, { "code": null, "e": 9716, "s": 9643, "text": "Your credit score decreases and your likelihood to get a loan decreases." }, { "code": null, "e": 9786, "s": 9716, "text": "The amount of rain increases and the number of bike rented decreases." }, { "code": null, "e": 9964, "s": 9786, "text": "Linear models are fully monotonic, but as gradient boosting includes interactions and can model non-linear relationships, they typically do not generate monotonic relationships." }, { "code": null, "e": 10106, "s": 9964, "text": "XGBoost, LightGBM and Catboost all have a simple hyperparameter that forces a variable to have a positive or negative monotonic relationship." }, { "code": null, "e": 10129, "s": 10106, "text": "Why is it explainable?" }, { "code": null, "e": 10498, "s": 10129, "text": "Using monotonic relationships means we can use statements like those above to explain our model. It causes the model to fill the Algorithmic Transparency criteria because this relationship is fixed. We can also build some of our real world knowledge into the model which can make it more understandable for businesspeople, giving it more change of reaching production." }, { "code": null, "e": 10513, "s": 10498, "text": "Implementation" }, { "code": null, "e": 10521, "s": 10513, "text": "XGBoost" }, { "code": null, "e": 10794, "s": 10521, "text": "In XGBoost we specify the monotone_constraints parameter a string tuple (brackets inside speech marks) with one number per feature in our dataset, so “(1,0,-1)” indicates features 1, 2 and 3. 1 is a positive monotonic relationship, -1 is negative and 0 is no relationship." }, { "code": null, "e": 10998, "s": 10794, "text": "import xgboost as xgbparams = {'monotone_constraints':'(1,0,-1)'}model = xgb.train(params, X_train, num_boost_round = 1000, early_stopping_rounds = 10)" }, { "code": null, "e": 11007, "s": 10998, "text": "LightGBM" }, { "code": null, "e": 11266, "s": 11007, "text": "LightGBM is broadly the same as XGBoost but we are required to pass our features as a list rather than a string/tuple. LightGBM also offers an extra parameter the method. Using this means we can choose how strongly the model will try to stick the constraint." }, { "code": null, "e": 11292, "s": 11266, "text": "The documentation states:" }, { "code": null, "e": 11416, "s": 11292, "text": "basic, the most basic monotone constraints method. It does not slow the library at all, but over-constrains the predictions" }, { "code": null, "e": 11610, "s": 11416, "text": "intermediate, a more advanced method, which may slow the library very slightly. However, this method is much less constraining than the basic method and should significantly improve the results" }, { "code": null, "e": 11805, "s": 11610, "text": "advanced, an even more advanced method, which may slow the library. However, this method is even less constraining than the intermediate method and should again significantly improve the results" }, { "code": null, "e": 12055, "s": 11805, "text": "import lightgbm as lgbparams = {'monotone_constraints': [-1, 0, 1], 'monotone_constraints_method':'basic'}model = lgb.train(params, X_train, num_round = 1000, early_stopping_rounds = 10)" }, { "code": null, "e": 12064, "s": 12055, "text": "Catboost" }, { "code": null, "e": 12219, "s": 12064, "text": "Catboost is very similar to the others but offers more flexibility as we can pass the constraints as an array, use slicing and name a feature explicitily." }, { "code": null, "e": 12310, "s": 12219, "text": "The parameter is called monotone_constraints and you can check out the Catboost docs here." }, { "code": null, "e": 12343, "s": 12310, "text": "What is it and how does it work?" }, { "code": null, "e": 12782, "s": 12343, "text": "TabNet was published by Google Brain researchers in in 2019. Traditionally, Neural Network approaches have not significantly improved on gradient boosting when dealing with Tabular data. However, Tabnet was able to outperform the leading tree based models across a variety of benchmarks. It is considerably more explainable than boosted tree models as it has built-in explainability. It can also be used without any feature preprocessing." }, { "code": null, "e": 12854, "s": 12782, "text": "My article on TabNet covers the model in more detail, take a look here:" }, { "code": null, "e": 12877, "s": 12854, "text": "towardsdatascience.com" }, { "code": null, "e": 12900, "s": 12877, "text": "Why is it explainable?" }, { "code": null, "e": 13261, "s": 12900, "text": "TabNet uses a sequential attention mechanism to select the most important features, this influences the ‘mask’ whichcovers up the least important features. We can use the weights of this mask to understand which features are being used more often than others, which essentially allows us to understand which features the model is using to make its predictions." }, { "code": null, "e": 13468, "s": 13261, "text": "Feature selection is performed at the row level of the dataset, which means we can actually explore which features were selected for a single prediction. The number of masks is a hyperparameter of the model" }, { "code": null, "e": 13483, "s": 13468, "text": "Implementation" }, { "code": null, "e": 13820, "s": 13483, "text": "The best way to use TabNet is with Dreamquark’s PyTorch implementation. It uses a scikit-learn style wrapper and is GPU compatible. Dreamquark also provide some really great notebooks which perfectly show how to implement TabNet while also working to validate the original authors claims about the models accuracy on certain benchmarks." }, { "code": null, "e": 13835, "s": 13820, "text": "Classification" }, { "code": null, "e": 13846, "s": 13835, "text": "github.com" }, { "code": null, "e": 13857, "s": 13846, "text": "Regression" }, { "code": null, "e": 13868, "s": 13857, "text": "github.com" }, { "code": null, "e": 13970, "s": 13868, "text": "Lets go back to Lipton’s 3 criteria and apply these to each model. As a reminder, the criteria are..." }, { "code": null, "e": 14256, "s": 13970, "text": "Simulatability: Can a human walk through the model’s steps in a ‘reasonable’ amount of time?Decomposability: Can all aspects of the model, including its features, parameters and weights be broken down?Algorithmic Transparency: Can we understand how the model will react to unseen data." }, { "code": null, "e": 14349, "s": 14256, "text": "Simulatability: Can a human walk through the model’s steps in a ‘reasonable’ amount of time?" }, { "code": null, "e": 14459, "s": 14349, "text": "Decomposability: Can all aspects of the model, including its features, parameters and weights be broken down?" }, { "code": null, "e": 14544, "s": 14459, "text": "Algorithmic Transparency: Can we understand how the model will react to unseen data." }, { "code": null, "e": 14748, "s": 14544, "text": "We also want to consider Local Explainability; to what extend can a single prediction be made by the model, in terms of what features it used and what extent did it use each feature to make its decision." }, { "code": null, "e": 14942, "s": 14748, "text": "I have summarised this in the chart below, scoring each model Low, Medium or High for each criteria. This isn’t an exact science but you can consider each score relative to a Linear Regression." }, { "code": null, "e": 15239, "s": 14942, "text": "Remember, that any feature engineering can completely throw these scores off. Creating complex interaction terms, mathematical transformations or features derived from a neural network may increase accuracy but will certainly decrease explainability. More features can also reduce explainability." }, { "code": null, "e": 15484, "s": 15239, "text": "The drive and discussions around model explainability is only increasing. With AI being used in language modelling, facial recognition and driverless cars, having models that can give reasoning behind their decision is more essential than ever." } ]
Deploying Static Website to Cloudflare Pages - GeeksforGeeks
21 Jun, 2021 Cloudflare Pages is a JAMStack hosting service provided by Cloudflare, a company that specializes in Web infrastructure and Security. Cloudflare Pages also referred to as “Pages” is newcomer in JAMStack hosting, but their Infrastructure makes almost as equivalent to their competitors. In this tutorial, we will teach you how to host you JAMstack website on cloudflare pages. They also have a free tier with 500 builds and unlimited bandwidth(when used according to their AUP), with custom domain names with free SSL, analytics, and access policies. Cloudflare account, if you don’t have one create here GitHub account, if you don’t have one create here A GitHub repository with an index.html file Cloudflare pages similar to Netlify pulls content from the Github repository then build the site and publishes it to their CDN. You can your static site with plain HTML (or) any static Site generator like Hugo, Next.js, Jekyll. Your repository must have at least 1 file and a compulsory index.html file should be present. Below is my simple GitHub repository with index.html file HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cloudflare Pages Demo</title></head><body> <h1>This is demo site for geeksforgeeks article on cloudflare pages</h1></body></html> And our GitHub Repository to Sample Github Repo Step 1: Login into your Cloudflare account and click on the Pages icon on the right side menu, this will take you Cloudflare Pages dashboard. Then click on create the project. Click on this icon Click on create project Step 2: This will take to you a webpage that asks you to connect to your GitHub account. Connect to Github account Now authorize the repositories you want Cloudflare pages to get installed, you can select all repositories (or) selected repositories Authorize Cloudflare pages Step 3: Select the repository you want to deploy and configure the deployment settings select your repository Now select the deployment configurations Name of the project: give a name to your project Production branch: branch of the repository you want to deploy Framework: Select the framework you have used in your project select None for static HTML, React, Hugo, and more Build command: Command to build the website, If you choose none in the framework leave it blank, or else it will be automatically applied according to your framework. If you have used a custom framework give your custom build command. Build Output folder: Directory of output from the build command, If you choose none in framework leave it blank, or else it will be automatically applied according to your framework. If you have used a custom framework give your custom build output directory. After you have selected your configuration, click on save and deploy. build configuration Now Cloudflare will build and deploy your site, if you have done everything correctly you will see something like below: Success You can connect to a custom domain from the project dashboard, and You can also enable analytics and access policies from project settings. Add custom domain if you have one Add analytics and access policies How To TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Create and Setup Spring Boot Project in Eclipse IDE? Docker - COPY Instruction Top Programming Languages for Android App Development How to Run a Python Script using Docker? Setting up the environment in Java How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 26197, "s": 26169, "text": "\n21 Jun, 2021" }, { "code": null, "e": 26747, "s": 26197, "text": "Cloudflare Pages is a JAMStack hosting service provided by Cloudflare, a company that specializes in Web infrastructure and Security. Cloudflare Pages also referred to as “Pages” is newcomer in JAMStack hosting, but their Infrastructure makes almost as equivalent to their competitors. In this tutorial, we will teach you how to host you JAMstack website on cloudflare pages. They also have a free tier with 500 builds and unlimited bandwidth(when used according to their AUP), with custom domain names with free SSL, analytics, and access policies." }, { "code": null, "e": 26801, "s": 26747, "text": "Cloudflare account, if you don’t have one create here" }, { "code": null, "e": 26851, "s": 26801, "text": "GitHub account, if you don’t have one create here" }, { "code": null, "e": 26895, "s": 26851, "text": "A GitHub repository with an index.html file" }, { "code": null, "e": 27275, "s": 26895, "text": "Cloudflare pages similar to Netlify pulls content from the Github repository then build the site and publishes it to their CDN. You can your static site with plain HTML (or) any static Site generator like Hugo, Next.js, Jekyll. Your repository must have at least 1 file and a compulsory index.html file should be present. Below is my simple GitHub repository with index.html file" }, { "code": null, "e": 27280, "s": 27275, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Cloudflare Pages Demo</title></head><body> <h1>This is demo site for geeksforgeeks article on cloudflare pages</h1></body></html>", "e": 27618, "s": 27280, "text": null }, { "code": null, "e": 27647, "s": 27618, "text": "And our GitHub Repository to" }, { "code": null, "e": 27666, "s": 27647, "text": "Sample Github Repo" }, { "code": null, "e": 27842, "s": 27666, "text": "Step 1: Login into your Cloudflare account and click on the Pages icon on the right side menu, this will take you Cloudflare Pages dashboard. Then click on create the project." }, { "code": null, "e": 27861, "s": 27842, "text": "Click on this icon" }, { "code": null, "e": 27885, "s": 27861, "text": "Click on create project" }, { "code": null, "e": 27974, "s": 27885, "text": "Step 2: This will take to you a webpage that asks you to connect to your GitHub account." }, { "code": null, "e": 28000, "s": 27974, "text": "Connect to Github account" }, { "code": null, "e": 28134, "s": 28000, "text": "Now authorize the repositories you want Cloudflare pages to get installed, you can select all repositories (or) selected repositories" }, { "code": null, "e": 28161, "s": 28134, "text": "Authorize Cloudflare pages" }, { "code": null, "e": 28248, "s": 28161, "text": "Step 3: Select the repository you want to deploy and configure the deployment settings" }, { "code": null, "e": 28271, "s": 28248, "text": "select your repository" }, { "code": null, "e": 28312, "s": 28271, "text": "Now select the deployment configurations" }, { "code": null, "e": 28361, "s": 28312, "text": "Name of the project: give a name to your project" }, { "code": null, "e": 28424, "s": 28361, "text": "Production branch: branch of the repository you want to deploy" }, { "code": null, "e": 28537, "s": 28424, "text": "Framework: Select the framework you have used in your project select None for static HTML, React, Hugo, and more" }, { "code": null, "e": 28772, "s": 28537, "text": "Build command: Command to build the website, If you choose none in the framework leave it blank, or else it will be automatically applied according to your framework. If you have used a custom framework give your custom build command." }, { "code": null, "e": 29032, "s": 28772, "text": "Build Output folder: Directory of output from the build command, If you choose none in framework leave it blank, or else it will be automatically applied according to your framework. If you have used a custom framework give your custom build output directory." }, { "code": null, "e": 29102, "s": 29032, "text": "After you have selected your configuration, click on save and deploy." }, { "code": null, "e": 29122, "s": 29102, "text": "build configuration" }, { "code": null, "e": 29243, "s": 29122, "text": "Now Cloudflare will build and deploy your site, if you have done everything correctly you will see something like below:" }, { "code": null, "e": 29251, "s": 29243, "text": "Success" }, { "code": null, "e": 29391, "s": 29251, "text": "You can connect to a custom domain from the project dashboard, and You can also enable analytics and access policies from project settings." }, { "code": null, "e": 29425, "s": 29391, "text": "Add custom domain if you have one" }, { "code": null, "e": 29459, "s": 29425, "text": "Add analytics and access policies" }, { "code": null, "e": 29466, "s": 29459, "text": "How To" }, { "code": null, "e": 29475, "s": 29466, "text": "TechTips" }, { "code": null, "e": 29573, "s": 29475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29607, "s": 29573, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29665, "s": 29607, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29714, "s": 29665, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 29761, "s": 29714, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 29821, "s": 29761, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 29847, "s": 29821, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29901, "s": 29847, "text": "Top Programming Languages for Android App Development" }, { "code": null, "e": 29942, "s": 29901, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 29977, "s": 29942, "text": "Setting up the environment in Java" } ]
SQLite - Syntax
SQLite is followed by unique set of rules and guidelines called Syntax. This chapter lists all the basic SQLite Syntax. The important point to be noted is that SQLite is case insensitive, i.e. the clauses GLOB and glob have the same meaning in SQLite statements. SQLite comments are extra notes, which you can add in your SQLite code to increase its readability and they can appear anywhere; whitespace can occur, including inside expressions and in the middle of other SQL statements but they cannot be nested. SQL comments begin with two consecutive "-" characters (ASCII 0x2d) and extend up to and including the next newline character (ASCII 0x0a) or until the end of input, whichever comes first. You can also use C-style comments, which begin with "/*" and extend up to and including the next "*/" character pair or until the end of input, whichever comes first. C-style comments can span multiple lines. sqlite> .help -- This is a single line comment All the SQLite statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, etc., and all the statements end with a semicolon (;). ANALYZE; or ANALYZE database_name; or ANALYZE database_name.table_name; SELECT column1, column2....columnN FROM table_name WHERE CONDITION-1 {AND|OR} CONDITION-2; ALTER TABLE table_name ADD COLUMN column_def...; ALTER TABLE table_name RENAME TO new_table_name; ATTACH DATABASE 'DatabaseName' As 'Alias-Name'; BEGIN; or BEGIN EXCLUSIVE TRANSACTION; SELECT column1, column2....columnN FROM table_name WHERE column_name BETWEEN val-1 AND val-2; COMMIT; CREATE INDEX index_name ON table_name ( column_name COLLATE NOCASE ); CREATE UNIQUE INDEX index_name ON table_name ( column1, column2,...columnN); CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) ); CREATE TRIGGER database_name.trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN stmt1; stmt2; .... END; CREATE VIEW database_name.view_name AS SELECT statement....; CREATE VIRTUAL TABLE database_name.table_name USING weblog( access.log ); or CREATE VIRTUAL TABLE database_name.table_name USING fts3( ); COMMIT; SELECT COUNT(column_name) FROM table_name WHERE CONDITION; DELETE FROM table_name WHERE {CONDITION}; DETACH DATABASE 'Alias-Name'; SELECT DISTINCT column1, column2....columnN FROM table_name; DROP INDEX database_name.index_name; DROP TABLE database_name.table_name; DROP INDEX database_name.view_name; DROP INDEX database_name.trigger_name; SELECT column1, column2....columnN FROM table_name WHERE column_name EXISTS (SELECT * FROM table_name ); EXPLAIN INSERT statement...; or EXPLAIN QUERY PLAN SELECT statement...; SELECT column1, column2....columnN FROM table_name WHERE column_name GLOB { PATTERN }; SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name; SELECT SUM(column_name) FROM table_name WHERE CONDITION GROUP BY column_name HAVING (arithematic function condition); INSERT INTO table_name( column1, column2....columnN) VALUES ( value1, value2....valueN); SELECT column1, column2....columnN FROM table_name WHERE column_name IN (val-1, val-2,...val-N); SELECT column1, column2....columnN FROM table_name WHERE column_name LIKE { PATTERN }; SELECT column1, column2....columnN FROM table_name WHERE column_name NOT IN (val-1, val-2,...val-N); SELECT column1, column2....columnN FROM table_name WHERE CONDITION ORDER BY column_name {ASC|DESC}; PRAGMA pragma_name; For example: PRAGMA page_size; PRAGMA cache_size = 1024; PRAGMA table_info(table_name); RELEASE savepoint_name; REINDEX collation_name; REINDEX database_name.index_name; REINDEX database_name.table_name; ROLLBACK; or ROLLBACK TO SAVEPOINT savepoint_name; SAVEPOINT savepoint_name; SELECT column1, column2....columnN FROM table_name; UPDATE table_name SET column1 = value1, column2 = value2....columnN=valueN [ WHERE CONDITION ]; VACUUM; SELECT column1, column2....columnN FROM table_name WHERE CONDITION; 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2758, "s": 2638, "text": "SQLite is followed by unique set of rules and guidelines called Syntax. This chapter lists all the basic SQLite Syntax." }, { "code": null, "e": 2901, "s": 2758, "text": "The important point to be noted is that SQLite is case insensitive, i.e. the clauses GLOB and glob have the same meaning in SQLite statements." }, { "code": null, "e": 3150, "s": 2901, "text": "SQLite comments are extra notes, which you can add in your SQLite code to increase its readability and they can appear anywhere; whitespace can occur, including inside expressions and in the middle of other SQL statements but they cannot be nested." }, { "code": null, "e": 3339, "s": 3150, "text": "SQL comments begin with two consecutive \"-\" characters (ASCII 0x2d) and extend up to and including the next newline character (ASCII 0x0a) or until the end of input, whichever comes first." }, { "code": null, "e": 3548, "s": 3339, "text": "You can also use C-style comments, which begin with \"/*\" and extend up to and including the next \"*/\" character pair or until the end of input, whichever comes first. C-style comments can span multiple lines." }, { "code": null, "e": 3595, "s": 3548, "text": "sqlite> .help -- This is a single line comment" }, { "code": null, "e": 3757, "s": 3595, "text": "All the SQLite statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, etc., and all the statements end with a semicolon (;)." }, { "code": null, "e": 3829, "s": 3757, "text": "ANALYZE;\nor\nANALYZE database_name;\nor\nANALYZE database_name.table_name;" }, { "code": null, "e": 3920, "s": 3829, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION-1 {AND|OR} CONDITION-2;" }, { "code": null, "e": 3969, "s": 3920, "text": "ALTER TABLE table_name ADD COLUMN column_def...;" }, { "code": null, "e": 4018, "s": 3969, "text": "ALTER TABLE table_name RENAME TO new_table_name;" }, { "code": null, "e": 4066, "s": 4018, "text": "ATTACH DATABASE 'DatabaseName' As 'Alias-Name';" }, { "code": null, "e": 4105, "s": 4066, "text": "BEGIN;\nor\nBEGIN EXCLUSIVE TRANSACTION;" }, { "code": null, "e": 4199, "s": 4105, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name BETWEEN val-1 AND val-2;" }, { "code": null, "e": 4207, "s": 4199, "text": "COMMIT;" }, { "code": null, "e": 4277, "s": 4207, "text": "CREATE INDEX index_name\nON table_name ( column_name COLLATE NOCASE );" }, { "code": null, "e": 4354, "s": 4277, "text": "CREATE UNIQUE INDEX index_name\nON table_name ( column1, column2,...columnN);" }, { "code": null, "e": 4513, "s": 4354, "text": "CREATE TABLE table_name(\n column1 datatype,\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype,\n PRIMARY KEY( one or more columns )\n);" }, { "code": null, "e": 4638, "s": 4513, "text": "CREATE TRIGGER database_name.trigger_name \nBEFORE INSERT ON table_name FOR EACH ROW\nBEGIN \n stmt1; \n stmt2;\n ....\nEND;" }, { "code": null, "e": 4699, "s": 4638, "text": "CREATE VIEW database_name.view_name AS\nSELECT statement....;" }, { "code": null, "e": 4837, "s": 4699, "text": "CREATE VIRTUAL TABLE database_name.table_name USING weblog( access.log );\nor\nCREATE VIRTUAL TABLE database_name.table_name USING fts3( );" }, { "code": null, "e": 4845, "s": 4837, "text": "COMMIT;" }, { "code": null, "e": 4904, "s": 4845, "text": "SELECT COUNT(column_name)\nFROM table_name\nWHERE CONDITION;" }, { "code": null, "e": 4946, "s": 4904, "text": "DELETE FROM table_name\nWHERE {CONDITION};" }, { "code": null, "e": 4976, "s": 4946, "text": "DETACH DATABASE 'Alias-Name';" }, { "code": null, "e": 5037, "s": 4976, "text": "SELECT DISTINCT column1, column2....columnN\nFROM table_name;" }, { "code": null, "e": 5074, "s": 5037, "text": "DROP INDEX database_name.index_name;" }, { "code": null, "e": 5111, "s": 5074, "text": "DROP TABLE database_name.table_name;" }, { "code": null, "e": 5147, "s": 5111, "text": "DROP INDEX database_name.view_name;" }, { "code": null, "e": 5186, "s": 5147, "text": "DROP INDEX database_name.trigger_name;" }, { "code": null, "e": 5293, "s": 5186, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name EXISTS (SELECT * FROM table_name );" }, { "code": null, "e": 5366, "s": 5293, "text": "EXPLAIN INSERT statement...;\nor \nEXPLAIN QUERY PLAN SELECT statement...;" }, { "code": null, "e": 5453, "s": 5366, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name GLOB { PATTERN };" }, { "code": null, "e": 5531, "s": 5453, "text": "SELECT SUM(column_name)\nFROM table_name\nWHERE CONDITION\nGROUP BY column_name;" }, { "code": null, "e": 5649, "s": 5531, "text": "SELECT SUM(column_name)\nFROM table_name\nWHERE CONDITION\nGROUP BY column_name\nHAVING (arithematic function condition);" }, { "code": null, "e": 5738, "s": 5649, "text": "INSERT INTO table_name( column1, column2....columnN)\nVALUES ( value1, value2....valueN);" }, { "code": null, "e": 5835, "s": 5738, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name IN (val-1, val-2,...val-N);" }, { "code": null, "e": 5922, "s": 5835, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name LIKE { PATTERN };" }, { "code": null, "e": 6023, "s": 5922, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE column_name NOT IN (val-1, val-2,...val-N);" }, { "code": null, "e": 6123, "s": 6023, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION\nORDER BY column_name {ASC|DESC};" }, { "code": null, "e": 6233, "s": 6123, "text": "PRAGMA pragma_name;\n\nFor example:\n\nPRAGMA page_size;\nPRAGMA cache_size = 1024;\nPRAGMA table_info(table_name);" }, { "code": null, "e": 6257, "s": 6233, "text": "RELEASE savepoint_name;" }, { "code": null, "e": 6349, "s": 6257, "text": "REINDEX collation_name;\nREINDEX database_name.index_name;\nREINDEX database_name.table_name;" }, { "code": null, "e": 6400, "s": 6349, "text": "ROLLBACK;\nor\nROLLBACK TO SAVEPOINT savepoint_name;" }, { "code": null, "e": 6426, "s": 6400, "text": "SAVEPOINT savepoint_name;" }, { "code": null, "e": 6478, "s": 6426, "text": "SELECT column1, column2....columnN\nFROM table_name;" }, { "code": null, "e": 6575, "s": 6478, "text": "UPDATE table_name\nSET column1 = value1, column2 = value2....columnN=valueN\n[ WHERE CONDITION ];" }, { "code": null, "e": 6583, "s": 6575, "text": "VACUUM;" }, { "code": null, "e": 6651, "s": 6583, "text": "SELECT column1, column2....columnN\nFROM table_name\nWHERE CONDITION;" }, { "code": null, "e": 6686, "s": 6651, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6707, "s": 6686, "text": " Sandip Bhattacharya" }, { "code": null, "e": 6740, "s": 6707, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 6757, "s": 6740, "text": " Laurence Svekis" }, { "code": null, "e": 6788, "s": 6757, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 6801, "s": 6788, "text": " Vinay Kumar" }, { "code": null, "e": 6808, "s": 6801, "text": " Print" }, { "code": null, "e": 6819, "s": 6808, "text": " Add Notes" } ]
How to Install xlrd in Python on Linux? - GeeksforGeeks
18 Oct, 2021 In this article, we will learn how to install xlrd in Python on Linux. The xlrd is a library for reading data and formatting information from Excel files in the historical .xls format. Follow the below steps to install the xlrd package on Linux using pip: Step 1: Install the latest Python3 in Linux Step 2: Check if pip3 and python3 are correctly installed. python3 --version pip3 --version Step 3: Upgrade your pip to avoid errors during installation. pip3 install --upgrade pip Step 4: Enter the following command to install xlrd using pip3. pip3 install xlrd Follow the below steps to install the xlrd package on Linux using the setup.py file: Step 1: Download the latest source package of xlrd for python3 from here. curl https://files.pythonhosted.org/packages/a6/b3/19a2540d21dea5f908304375bd43f5ed7a4c28a370dc9122c565423e6b44/xlrd-2.0.1.tar.gz > xlrd.tar.gz Step 2: Extract the downloaded package using the following command. tar -xvzf xlrd.tar.gz Step 3: Go inside the folder and Enter the following command to install the package. cd xlrd-2.0.1 python3 setup.py install Make the following import in your python terminal to verify if the installation has been done properly: import xlrd If there is any error while importing the module then is not installed properly. how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Align Text in HTML? How to filter object array based on attributes? How to Install OpenCV for Python on Windows? Java Tutorial How to Install FFmpeg on Windows? Installation of Node.js on Linux How to Install OpenCV for Python on Windows? How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 26251, "s": 26223, "text": "\n18 Oct, 2021" }, { "code": null, "e": 26436, "s": 26251, "text": "In this article, we will learn how to install xlrd in Python on Linux. The xlrd is a library for reading data and formatting information from Excel files in the historical .xls format." }, { "code": null, "e": 26507, "s": 26436, "text": "Follow the below steps to install the xlrd package on Linux using pip:" }, { "code": null, "e": 26551, "s": 26507, "text": "Step 1: Install the latest Python3 in Linux" }, { "code": null, "e": 26610, "s": 26551, "text": "Step 2: Check if pip3 and python3 are correctly installed." }, { "code": null, "e": 26643, "s": 26610, "text": "python3 --version\npip3 --version" }, { "code": null, "e": 26705, "s": 26643, "text": "Step 3: Upgrade your pip to avoid errors during installation." }, { "code": null, "e": 26732, "s": 26705, "text": "pip3 install --upgrade pip" }, { "code": null, "e": 26796, "s": 26732, "text": "Step 4: Enter the following command to install xlrd using pip3." }, { "code": null, "e": 26814, "s": 26796, "text": "pip3 install xlrd" }, { "code": null, "e": 26899, "s": 26814, "text": "Follow the below steps to install the xlrd package on Linux using the setup.py file:" }, { "code": null, "e": 26973, "s": 26899, "text": "Step 1: Download the latest source package of xlrd for python3 from here." }, { "code": null, "e": 27117, "s": 26973, "text": "curl https://files.pythonhosted.org/packages/a6/b3/19a2540d21dea5f908304375bd43f5ed7a4c28a370dc9122c565423e6b44/xlrd-2.0.1.tar.gz > xlrd.tar.gz" }, { "code": null, "e": 27185, "s": 27117, "text": "Step 2: Extract the downloaded package using the following command." }, { "code": null, "e": 27207, "s": 27185, "text": "tar -xvzf xlrd.tar.gz" }, { "code": null, "e": 27292, "s": 27207, "text": "Step 3: Go inside the folder and Enter the following command to install the package." }, { "code": null, "e": 27331, "s": 27292, "text": "cd xlrd-2.0.1\npython3 setup.py install" }, { "code": null, "e": 27435, "s": 27331, "text": "Make the following import in your python terminal to verify if the installation has been done properly:" }, { "code": null, "e": 27447, "s": 27435, "text": "import xlrd" }, { "code": null, "e": 27528, "s": 27447, "text": "If there is any error while importing the module then is not installed properly." }, { "code": null, "e": 27543, "s": 27528, "text": "how-to-install" }, { "code": null, "e": 27550, "s": 27543, "text": "Picked" }, { "code": null, "e": 27557, "s": 27550, "text": "How To" }, { "code": null, "e": 27576, "s": 27557, "text": "Installation Guide" }, { "code": null, "e": 27674, "s": 27576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27701, "s": 27674, "text": "How to Align Text in HTML?" }, { "code": null, "e": 27749, "s": 27701, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27794, "s": 27749, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 27808, "s": 27794, "text": "Java Tutorial" }, { "code": null, "e": 27842, "s": 27808, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27875, "s": 27842, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27920, "s": 27875, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 27954, "s": 27920, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27989, "s": 27954, "text": "How to Install Pygame on Windows ?" } ]