title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Inference in Graph Database. In this blog post, I will try to... | by Atakan Güney | Towards Data Science
In this blog post, I will try to explain what the inference is on Semantic Web and to show how the inference can be applied in a local graph database. The outline of my blog is the following: What is Inference?What is used for?Types of the procedureGraph Database and OntologyInference on DatabaseConclusion What is Inference? What is used for? Types of the procedure Graph Database and Ontology Inference on Database Conclusion As described in W3 standards, the inference is briefly discovering new edges within a graph based on a given ontology. On Semantic Web, the data as modeled as triples, i.e. two resources and one relationship between them. The inference is that inferring new triples based on the data and some additional information, which may be in the form of vocabularies(ontologies) and rule sets(logic). For example, let’s say we have two sources: John the human and Max the dog and we have information that John has Max and Max is Dog. In addition, if we have an additional vocabulary, which includes information; Dog is Mammal. We can infer that Max is Mammal and John has Mammal. Inference on Semantic Web is used for improving the quality of data integration on the web. It automatically provides new links within the data and analyzes the content. Similarly, it also checks for consistency of the data on the web. For example, let’s say we have the data that includes information Dora is Cow and Dora is Carnivore. If we check the animal’s ontology, it is inconsistent with that the Cows are vegetarians. As stated, the automatic discovery of new links is done by either using vocabulary or a rule set. On the Semantic Web, vocabularies or ontologies can be described in OWL, SKOS, and RDF whereas rule sets are described in RIF. These technologies are recommendations of the W3C foundation. Additionally, the ontologies are based on class and sub-class relationships, however, rule sets are describing general rules to generate new relationships based on existing ones. We are able to store our data as graphs thanks to the new handy technologies in the database field. Especially, the Graph Databases. It is very nice to have such a powerful tool. The nicer is that we can make them more powerful by including common vocabularies, ONTOLOGIES 🚀 In my previous blog post, I described how to import an ontology into a Neo4j database by using a plugin called NSMNTX — Neo4j RDF & Semantics toolkit. Please read first that blog post before continue. medium.com In addition to importing a database, now we do inference on it. As you would remember from the previous post, we could import the ontology from an external store online. But for simplicity in this blog post, we will create our Animal World ontology by ourselves. Let’s do it 😅 CREATE (a: AnimalType{authoritativeLabel: "Mammals", dbLabel: "Mammals"})CREATE (b: AnimalType{authoritativeLabel: "Dog", dbLabel: "Dog"})CREATE (c: AnimalType{authoritativeLabel: "Cat", dbLabel: "Cat"})CREATE (d: AnimalType{authoritativeLabel: "Horse", dbLabel: "Horse"})CREATE (a)<-[:IS_A]-(b)CREATE (a)<-[:IS_A]-(c)CREATE (a)<-[:IS_A]-(d) This will produce some nodes which have the type AnimalType and they have IS_A relationship. Let’s see. This AnimalType is telling us about relations between animals. So, now create some animal instances which are considered as Pets. CREATE (:Pet:Dog{name: "Max"})CREATE (:Pet:Cat{name: "Missy"})CREATE (:Pet:Horse{name: "DulDul"}) And this will produce Our first inference would be getting all Mammals. So, as you can see our data consists of only three distinct nodes. CALL semantics.inference.nodesLabelled('Mammals', { catNameProp: "dbLabel", catLabel: "AnimalType", subCatRel: "IS_A" }) YIELD nodeRETURN node.name as name, labels(node) as categories This will return So, without having any relation in our database we inferred common label relation by using our vocabulary. Now, let’s add some relations. MATCH (c:Cat{name: "Missy"})MATCH (d:Dog{name: "Max"})MATCH (h:Horse{name: "DulDul"})CREATE(jn: Person{name: "John"})CREATE(al: Person{name: "Alex"})CREATE (jn)-[:LOVES]->(d)CREATE (h)-[:LOVES]->(d)CREATE (al)-[:LOVES]->(c) This will result As a second kind of inference, let’s try to get all animal lovers ❤️ MATCH (p)-[:LOVES]->(pt)WHERE semantics.inference.hasLabel(pt,'Mammals', { catNameProp: "dbLabel", catLabel: "AnimalType", subCatRel: "IS_A" })RETURN p.name as name And results come... Now, let’s do inference on vocabulary itself. Before that, let’s extend it a little bit MATCH (h:AnimalType{authoritativeLabel: "Horse"})MATCH (d:AnimalType{authoritativeLabel: "Dog"})MATCH (c:AnimalType{authoritativeLabel: "Cat"})CREATE (:Film {title: "A Dog's Journey"})-[:HAS_SUBJECT]->(d)CREATE (:Film {title: "Cats"})-[:HAS_SUBJECT]->(c)CREATE (:Film {title: "The Mustang"})-[:HAS_SUBJECT]->(h) And visualize it We added some movies, which has subject as animals. Our next inference type would be node in category type of inference. Let’s try to get all films, which has subject as Mammals MATCH (cat:AnimalType { authoritativeLabel: "Mammals"})CALL semantics.inference.nodesInCategory(cat, { inCatRel: "HAS_SUBJECT", subCatRel: "IS_A"}) yield nodereturn node.title as film And... We got what we asked for 😈 Now, let’s see our last inference type. Our data takes place, again. But before that let’s define other AnimalType, which is different than Mammals: Fish and Shark. Similarly, let’s add another IS_A relationship. CREATE (f:AnimalType{authoritativeLabel: "Fish", dbLabel: "Fish"})CREATE (sh:AnimalType{authoritativeLabel: "Shark", dbLabel: "Shark"})CREATE (f)<-[:IS_A]-(sh) And create a film about Shark MATCH (s: AnimalType{authoritativeLabel: "Shark"})CREATE (:Film {title: "Frenzen"})-[:HAS_SUBJECT]->(s) Our final vocabulary will look like the following Now add new information into our data MERGE (p:Person { name : "John"}) with pMATCH (film1:Film { title : "Cats" })MATCH (film2:Film { title : "Frenzen" })WITH p, film1, film2CREATE (film1)<-[:LIKES]-(p)-[:LIKES]->(film2) See the corresponding data in our graph database So, our person John likes both Cats and Frenzen. Let’s query which of the films that John likes has subject about Fish. MATCH (fish:AnimalType { authoritativeLabel: "Fish"})MATCH (:Person { name : "John"})-[:LIKES]->(b:Film)WHERE semantics.inference.inCategory(b,fish,{ inCatRel: "HAS_SUBJECT", subCatRel: "IS_A"})RETURN b.title as title Yeah, we got our result 💪 Recently, NoSQL databases attracted attention instead of relational databases. Among various kinds of NoSQL databases, Graph-based ones are getting more attraction in time. In my humble opinion, it will be valuable including external information onto a Graph Database and managing, analyzing and proof checking it. Importing ontologies is a nice and compact way of doing that. I hope you enjoyed the blog. For more interesting tools, stay tuned 🚀
[ { "code": null, "e": 364, "s": 172, "text": "In this blog post, I will try to explain what the inference is on Semantic Web and to show how the inference can be applied in a local graph database. The outline of my blog is the following:" }, { "code": null, "e": 480, "s": 364, "text": "What is Inference?What is used for?Types of the procedureGraph Database and OntologyInference on DatabaseConclusion" }, { "code": null, "e": 499, "s": 480, "text": "What is Inference?" }, { "code": null, "e": 517, "s": 499, "text": "What is used for?" }, { "code": null, "e": 540, "s": 517, "text": "Types of the procedure" }, { "code": null, "e": 568, "s": 540, "text": "Graph Database and Ontology" }, { "code": null, "e": 590, "s": 568, "text": "Inference on Database" }, { "code": null, "e": 601, "s": 590, "text": "Conclusion" }, { "code": null, "e": 1272, "s": 601, "text": "As described in W3 standards, the inference is briefly discovering new edges within a graph based on a given ontology. On Semantic Web, the data as modeled as triples, i.e. two resources and one relationship between them. The inference is that inferring new triples based on the data and some additional information, which may be in the form of vocabularies(ontologies) and rule sets(logic). For example, let’s say we have two sources: John the human and Max the dog and we have information that John has Max and Max is Dog. In addition, if we have an additional vocabulary, which includes information; Dog is Mammal. We can infer that Max is Mammal and John has Mammal." }, { "code": null, "e": 1699, "s": 1272, "text": "Inference on Semantic Web is used for improving the quality of data integration on the web. It automatically provides new links within the data and analyzes the content. Similarly, it also checks for consistency of the data on the web. For example, let’s say we have the data that includes information Dora is Cow and Dora is Carnivore. If we check the animal’s ontology, it is inconsistent with that the Cows are vegetarians." }, { "code": null, "e": 2165, "s": 1699, "text": "As stated, the automatic discovery of new links is done by either using vocabulary or a rule set. On the Semantic Web, vocabularies or ontologies can be described in OWL, SKOS, and RDF whereas rule sets are described in RIF. These technologies are recommendations of the W3C foundation. Additionally, the ontologies are based on class and sub-class relationships, however, rule sets are describing general rules to generate new relationships based on existing ones." }, { "code": null, "e": 2440, "s": 2165, "text": "We are able to store our data as graphs thanks to the new handy technologies in the database field. Especially, the Graph Databases. It is very nice to have such a powerful tool. The nicer is that we can make them more powerful by including common vocabularies, ONTOLOGIES 🚀" }, { "code": null, "e": 2641, "s": 2440, "text": "In my previous blog post, I described how to import an ontology into a Neo4j database by using a plugin called NSMNTX — Neo4j RDF & Semantics toolkit. Please read first that blog post before continue." }, { "code": null, "e": 2652, "s": 2641, "text": "medium.com" }, { "code": null, "e": 2929, "s": 2652, "text": "In addition to importing a database, now we do inference on it. As you would remember from the previous post, we could import the ontology from an external store online. But for simplicity in this blog post, we will create our Animal World ontology by ourselves. Let’s do it 😅" }, { "code": null, "e": 3271, "s": 2929, "text": "CREATE (a: AnimalType{authoritativeLabel: \"Mammals\", dbLabel: \"Mammals\"})CREATE (b: AnimalType{authoritativeLabel: \"Dog\", dbLabel: \"Dog\"})CREATE (c: AnimalType{authoritativeLabel: \"Cat\", dbLabel: \"Cat\"})CREATE (d: AnimalType{authoritativeLabel: \"Horse\", dbLabel: \"Horse\"})CREATE (a)<-[:IS_A]-(b)CREATE (a)<-[:IS_A]-(c)CREATE (a)<-[:IS_A]-(d)" }, { "code": null, "e": 3375, "s": 3271, "text": "This will produce some nodes which have the type AnimalType and they have IS_A relationship. Let’s see." }, { "code": null, "e": 3505, "s": 3375, "text": "This AnimalType is telling us about relations between animals. So, now create some animal instances which are considered as Pets." }, { "code": null, "e": 3603, "s": 3505, "text": "CREATE (:Pet:Dog{name: \"Max\"})CREATE (:Pet:Cat{name: \"Missy\"})CREATE (:Pet:Horse{name: \"DulDul\"})" }, { "code": null, "e": 3625, "s": 3603, "text": "And this will produce" }, { "code": null, "e": 3742, "s": 3625, "text": "Our first inference would be getting all Mammals. So, as you can see our data consists of only three distinct nodes." }, { "code": null, "e": 3927, "s": 3742, "text": "CALL semantics.inference.nodesLabelled('Mammals', { catNameProp: \"dbLabel\", catLabel: \"AnimalType\", subCatRel: \"IS_A\" }) YIELD nodeRETURN node.name as name, labels(node) as categories" }, { "code": null, "e": 3944, "s": 3927, "text": "This will return" }, { "code": null, "e": 4051, "s": 3944, "text": "So, without having any relation in our database we inferred common label relation by using our vocabulary." }, { "code": null, "e": 4082, "s": 4051, "text": "Now, let’s add some relations." }, { "code": null, "e": 4306, "s": 4082, "text": "MATCH (c:Cat{name: \"Missy\"})MATCH (d:Dog{name: \"Max\"})MATCH (h:Horse{name: \"DulDul\"})CREATE(jn: Person{name: \"John\"})CREATE(al: Person{name: \"Alex\"})CREATE (jn)-[:LOVES]->(d)CREATE (h)-[:LOVES]->(d)CREATE (al)-[:LOVES]->(c)" }, { "code": null, "e": 4323, "s": 4306, "text": "This will result" }, { "code": null, "e": 4392, "s": 4323, "text": "As a second kind of inference, let’s try to get all animal lovers ❤️" }, { "code": null, "e": 4557, "s": 4392, "text": "MATCH (p)-[:LOVES]->(pt)WHERE semantics.inference.hasLabel(pt,'Mammals', { catNameProp: \"dbLabel\", catLabel: \"AnimalType\", subCatRel: \"IS_A\" })RETURN p.name as name" }, { "code": null, "e": 4577, "s": 4557, "text": "And results come..." }, { "code": null, "e": 4665, "s": 4577, "text": "Now, let’s do inference on vocabulary itself. Before that, let’s extend it a little bit" }, { "code": null, "e": 4977, "s": 4665, "text": "MATCH (h:AnimalType{authoritativeLabel: \"Horse\"})MATCH (d:AnimalType{authoritativeLabel: \"Dog\"})MATCH (c:AnimalType{authoritativeLabel: \"Cat\"})CREATE (:Film {title: \"A Dog's Journey\"})-[:HAS_SUBJECT]->(d)CREATE (:Film {title: \"Cats\"})-[:HAS_SUBJECT]->(c)CREATE (:Film {title: \"The Mustang\"})-[:HAS_SUBJECT]->(h)" }, { "code": null, "e": 4994, "s": 4977, "text": "And visualize it" }, { "code": null, "e": 5172, "s": 4994, "text": "We added some movies, which has subject as animals. Our next inference type would be node in category type of inference. Let’s try to get all films, which has subject as Mammals" }, { "code": null, "e": 5356, "s": 5172, "text": "MATCH (cat:AnimalType { authoritativeLabel: \"Mammals\"})CALL semantics.inference.nodesInCategory(cat, { inCatRel: \"HAS_SUBJECT\", subCatRel: \"IS_A\"}) yield nodereturn node.title as film" }, { "code": null, "e": 5363, "s": 5356, "text": "And..." }, { "code": null, "e": 5390, "s": 5363, "text": "We got what we asked for 😈" }, { "code": null, "e": 5603, "s": 5390, "text": "Now, let’s see our last inference type. Our data takes place, again. But before that let’s define other AnimalType, which is different than Mammals: Fish and Shark. Similarly, let’s add another IS_A relationship." }, { "code": null, "e": 5763, "s": 5603, "text": "CREATE (f:AnimalType{authoritativeLabel: \"Fish\", dbLabel: \"Fish\"})CREATE (sh:AnimalType{authoritativeLabel: \"Shark\", dbLabel: \"Shark\"})CREATE (f)<-[:IS_A]-(sh)" }, { "code": null, "e": 5793, "s": 5763, "text": "And create a film about Shark" }, { "code": null, "e": 5897, "s": 5793, "text": "MATCH (s: AnimalType{authoritativeLabel: \"Shark\"})CREATE (:Film {title: \"Frenzen\"})-[:HAS_SUBJECT]->(s)" }, { "code": null, "e": 5947, "s": 5897, "text": "Our final vocabulary will look like the following" }, { "code": null, "e": 5985, "s": 5947, "text": "Now add new information into our data" }, { "code": null, "e": 6169, "s": 5985, "text": "MERGE (p:Person { name : \"John\"}) with pMATCH (film1:Film { title : \"Cats\" })MATCH (film2:Film { title : \"Frenzen\" })WITH p, film1, film2CREATE (film1)<-[:LIKES]-(p)-[:LIKES]->(film2)" }, { "code": null, "e": 6218, "s": 6169, "text": "See the corresponding data in our graph database" }, { "code": null, "e": 6338, "s": 6218, "text": "So, our person John likes both Cats and Frenzen. Let’s query which of the films that John likes has subject about Fish." }, { "code": null, "e": 6556, "s": 6338, "text": "MATCH (fish:AnimalType { authoritativeLabel: \"Fish\"})MATCH (:Person { name : \"John\"})-[:LIKES]->(b:Film)WHERE semantics.inference.inCategory(b,fish,{ inCatRel: \"HAS_SUBJECT\", subCatRel: \"IS_A\"})RETURN b.title as title" }, { "code": null, "e": 6582, "s": 6556, "text": "Yeah, we got our result 💪" } ]
Allocate minimum number of pages in C++
Allocate a minimum number of pages is a programming problem. Let's discuss this problem in detail and see what can be the solution to it. You are given the number of pages of n different books. Also, there are m students to whom the books are to be assigned. The books are arranged in ascending order of the number of pages. And every student can be assigned some consecutive books. The program should return the maximum number of pages read by a student which should be minimum. Let's take an example to understand this problem in a better way, Input : books[] = {13 , 43, 65, 87, 92} m = 2 Output : 179 In this problem, we have two students who are reading books. So, there can be the following ways to distribute books between them. CASE 1 − [13] , [43, 65, 87, 92 ] This makes the maximum number of pages read by a student is 13 / 287 CASE 2 − [13, 43] , [65, 87,92] This makes the maximum number of pages read by a student is 56/ 244 CASE 3 − [13, 43 , 65] , [87, 92] This makes the maximum number of pages read by a student is 121 / 179 CASE 4 − [13, 43 , 65 , 87] , [92] This makes the maximum number of pages read by a student is 208 / 92 Out of all these 4 cases, the result is 179 This example must have made the problem clear to you. Now, let's understand the logic behind it and create a program for it. To solve this problem an easy approach is using the binary search algorithm. For this binary search approach, initialize minimum and a maximum number of pages as 0 and sum of pages of all books. And then fix the mid of these values as the intermediate result which will change as the algo proceeds further. Now, using the mid-value we will try to find the possibility to find the final solution. If the current mid has chances to become a solution, then the lower half i.e minimum to mid is searching. If this case is not true then the other half i.e. mid to maximum is searched. This method can be used to find the solution to this problem but as the number of students increases this algorithm tends to provide a less reliable solution. Live Demo #include<bits/stdc++.h> using namespace std; bool isPossible(int arr[], int n, int m, int curr_min) ; int min_pages(int arr[], int n, int m) ; int main(){ int n = 5; int books[] = {13 , 43, 65, 87, 92}; cout<<"The number of page in books are :\n"; for(int i = 0 ; i< n; i++){ cout<<books[i]<<"\t"; } int m = 2; cout<<"\nMinimum number of pages = "<<min_pages(books, n, m)<<endl; return 0; } bool isPossible(int arr[], int n, int m, int curr_min){ int studentsRequired = 1; int curr_sum = 0; for (int i = 0; i < n; i++){ if (arr[i] > curr_min) return false; if (curr_sum + arr[i] > curr_min){ studentsRequired++; curr_sum = arr[i]; if (studentsRequired > m) return false; } else curr_sum += arr[i]; } return true; } int min_pages(int arr[], int n, int m){ long long sum = 0; if (n < m) return -1; for (int i = 0; i < n; i++) sum += arr[i]; int minimum = 0, maximum = sum; int result = INT_MAX; while (minimum <= maximum){ int mid = (minimum + maximum) / 2; if (isPossible(arr, n, m, mid)){ result = min(result, mid); maximum = mid - 1; } else minimum = mid + 1; } return result; } The number of page in books are : 13 43 65 87 92 Minimum number of pages = 179
[ { "code": null, "e": 1200, "s": 1062, "text": "Allocate a minimum number of pages is a programming problem. Let's discuss this problem in detail and see what can be the solution to it." }, { "code": null, "e": 1542, "s": 1200, "text": "You are given the number of pages of n different books. Also, there are m students to whom the books are to be assigned. The books are arranged in ascending order of the number of pages. And every student can be assigned some consecutive books. The program should return the maximum number of pages read by a student which should be minimum." }, { "code": null, "e": 1608, "s": 1542, "text": "Let's take an example to understand this problem in a better way," }, { "code": null, "e": 1670, "s": 1608, "text": "Input : books[] = {13 , 43, 65, 87, 92}\n m = 2\nOutput : 179" }, { "code": null, "e": 1801, "s": 1670, "text": "In this problem, we have two students who are reading books. So, there can be the following ways to distribute books between them." }, { "code": null, "e": 1835, "s": 1801, "text": "CASE 1 − [13] , [43, 65, 87, 92 ]" }, { "code": null, "e": 1904, "s": 1835, "text": "This makes the maximum number of pages read by a student is 13 / 287" }, { "code": null, "e": 1936, "s": 1904, "text": "CASE 2 − [13, 43] , [65, 87,92]" }, { "code": null, "e": 2004, "s": 1936, "text": "This makes the maximum number of pages read by a student is 56/ 244" }, { "code": null, "e": 2038, "s": 2004, "text": "CASE 3 − [13, 43 , 65] , [87, 92]" }, { "code": null, "e": 2108, "s": 2038, "text": "This makes the maximum number of pages read by a student is 121 / 179" }, { "code": null, "e": 2143, "s": 2108, "text": "CASE 4 − [13, 43 , 65 , 87] , [92]" }, { "code": null, "e": 2212, "s": 2143, "text": "This makes the maximum number of pages read by a student is 208 / 92" }, { "code": null, "e": 2256, "s": 2212, "text": "Out of all these 4 cases, the result is 179" }, { "code": null, "e": 2381, "s": 2256, "text": "This example must have made the problem clear to you. Now, let's understand the logic behind it and create a program for it." }, { "code": null, "e": 2688, "s": 2381, "text": "To solve this problem an easy approach is using the binary search algorithm. For this binary search approach, initialize minimum and a maximum number of pages as 0 and sum of pages of all books. And then fix the mid of these values as the intermediate result which will change as the algo proceeds further." }, { "code": null, "e": 2961, "s": 2688, "text": "Now, using the mid-value we will try to find the possibility to find the final solution. If the current mid has chances to become a solution, then the lower half i.e minimum to mid is searching. If this case is not true then the other half i.e. mid to maximum is searched." }, { "code": null, "e": 3120, "s": 2961, "text": "This method can be used to find the solution to this problem but as the number of students increases this algorithm tends to provide a less reliable solution." }, { "code": null, "e": 3131, "s": 3120, "text": " Live Demo" }, { "code": null, "e": 4424, "s": 3131, "text": "#include<bits/stdc++.h>\nusing namespace std;\nbool isPossible(int arr[], int n, int m, int curr_min) ;\nint min_pages(int arr[], int n, int m) ;\nint main(){\n int n = 5;\n int books[] = {13 , 43, 65, 87, 92};\n cout<<\"The number of page in books are :\\n\";\n for(int i = 0 ; i< n; i++){\n cout<<books[i]<<\"\\t\";\n }\n int m = 2;\n cout<<\"\\nMinimum number of pages = \"<<min_pages(books, n, m)<<endl;\n return 0;\n}\nbool isPossible(int arr[], int n, int m, int curr_min){\n int studentsRequired = 1;\n int curr_sum = 0;\n for (int i = 0; i < n; i++){\n if (arr[i] > curr_min)\n return false;\n if (curr_sum + arr[i] > curr_min){\n studentsRequired++;\n curr_sum = arr[i];\n if (studentsRequired > m)\n return false;\n }\n else\n curr_sum += arr[i];\n }\n return true;\n}\nint min_pages(int arr[], int n, int m){\n long long sum = 0;\n if (n < m)\n return -1;\n for (int i = 0; i < n; i++)\n sum += arr[i];\n int minimum = 0, maximum = sum;\n int result = INT_MAX;\n while (minimum <= maximum){\n int mid = (minimum + maximum) / 2;\n if (isPossible(arr, n, m, mid)){\n result = min(result, mid);\n maximum = mid - 1;\n }\n else\n minimum = mid + 1;\n }\n return result;\n}" }, { "code": null, "e": 4503, "s": 4424, "text": "The number of page in books are :\n13 43 65 87 92\nMinimum number of pages = 179" } ]
What is the difference between static classes and non-static inner classes in Java?
Following are the notable differences between inner classes and static inner classes. The static inner class can access the static members of the outer class directly. But, to access the instance members of the outer class you need to instantiate the outer class. public class Outer { int num = 234; static int data = 300; public static class Inner{ public static void main(String args[]){ Outer obj = new Outer(); System.out.println(obj.num); System.out.println(data); } } } 234 300 The non inner class can access the members of its outer class (both instance and static) directly without instantiation. Live Demo public class Outer2 { int num = 234; static int data =300; public class Inner{ public void main(){ System.out.println(num); System.out.println(data); } } public static void main(String args[]){ new Outer2().new Inner().main(); } } 234 300 You cannot have members of a non-static inner class static. Static methods are allowed only in top-level classes and static inner classes.
[ { "code": null, "e": 1148, "s": 1062, "text": "Following are the notable differences between inner classes and static inner classes." }, { "code": null, "e": 1326, "s": 1148, "text": "The static inner class can access the static members of the outer class directly. But, to access the instance members of the outer class you need to instantiate the outer class." }, { "code": null, "e": 1589, "s": 1326, "text": "public class Outer {\n int num = 234;\n static int data = 300;\n public static class Inner{\n public static void main(String args[]){\n Outer obj = new Outer();\n System.out.println(obj.num);\n System.out.println(data);\n }\n }\n}" }, { "code": null, "e": 1597, "s": 1589, "text": "234\n300" }, { "code": null, "e": 1718, "s": 1597, "text": "The non inner class can access the members of its outer class (both instance and static) directly without instantiation." }, { "code": null, "e": 1728, "s": 1718, "text": "Live Demo" }, { "code": null, "e": 2013, "s": 1728, "text": "public class Outer2 {\n int num = 234;\n static int data =300;\n public class Inner{\n public void main(){\n System.out.println(num);\n System.out.println(data);\n }\n }\n public static void main(String args[]){\n new Outer2().new Inner().main();\n }\n}" }, { "code": null, "e": 2021, "s": 2013, "text": "234\n300" }, { "code": null, "e": 2160, "s": 2021, "text": "You cannot have members of a non-static inner class static. Static methods are allowed only in top-level classes and static inner classes." } ]
Deep Transfer Learning for Natural Language Processing — Text Classification with Universal Embeddings | by Dipanjan (DJ) Sarkar | Towards Data Science
Transfer learning is an exciting concept where we try to leverage prior knowledge from one domain and task into a different domain and task. The inspiration comes from us — humans, ourselves — where in, we have an inherent ability to not learn everything from scratch. We transfer and leverage our knowledge from what we have learnt in the past for tackling a wide variety of tasks. With computer vision, we have excellent big datasets available to us, like Imagenet, on which, we get a suite of world-class, state-of-the-art pre-trained model to leverage transfer learning. But what about Natural Language Processing? Therein lies the challenge, considering text data is so diverse, noisy and unstructured. We’ve had some recent successes with word embeddings including methods like Word2Vec, GloVe and FastText, all of which I have covered in my article ‘Feature Engineering for Text Data’. towardsdatascience.com In this article, we will be showcasing several state-of-the-art generic sentence embedding encoders, which tend to give surprisingly good performance, especially on small amounts of data for transfer learning tasks as compared to word embedding models. We will be covering the following models: Baseline Averaged Sentence Embeddings Doc2Vec Neural-Net Language Models (Hands-on Demo!) Skip-Thought Vectors Quick-Thought Vectors InferSent Universal Sentence Encoder We will try to cover essential concepts and also showcase some hands-on examples leveraging Python and Tensorflow, in a text classification problem focused on sentiment analysis! What is this sudden craze behind embeddings? I’m sure many of you might be hearing it everywhere. Let’s clear up the basics first and cut through the hype. An embedding is a fixed-length vector typically used to encode and represent an entity (document, sentence, word, graph!) I’ve talked about the need for embeddings in the context of text data and NLP in one of my previous articles. But I will briefly reiterate this here for the sake of convenience. With regard to speech or image recognition systems, we already get information in the form of rich dense feature vectors embedded in high-dimensional datasets like audio spectrograms and image pixel intensities. However, when it comes to raw text data, especially count-based models like Bag of Words, we are dealing with individual words, which may have their own identifiers, and do not capture the semantic relationship among words. This leads to huge sparse word vectors for textual data and thus, if we do not have enough data, we may end up getting poor models or even overfitting the data due to the curse of dimensionality. Predictive methods like Neural Network based language models try to predict words from its neighboring words looking at word sequences in the corpus and in the process, it learns distributed representations, giving us dense word embeddings. Now you might be thinking, big deal, we get a bunch of vectors from text. What now? Well, this craze for embeddings is that, if we have a good numeric representation of text data which captures even the context and semantics, we can use it for a wide variety of downstream real-world tasks like sentiment analysis, text classification, clustering, summarization, translation and so on. The fact of the matter is, machine learning or deep learning models run on numbers, and embeddings are the key to encoding text data that will be used by these models. A big trend here has been finding out so-called ‘Universal Embeddings’ which are basically pre-trained embeddings obtained from training deep learning models on a huge corpus. This enables us to use these pre-trained (generic) embeddings in a wide variety of tasks including, scenarios with constraints like lack of adequate data. This is a perfect example of transfer learning, leveraging prior knowledge from pre-trained embeddings to solve a completely new task! The following figure showcases some recent trends in Universal Word & Sentence Embeddings, thanks to an amazing article from the folks over at HuggingFace! Definitely, some interesting trends in the above figure including, Google’s Universal Sentence Encoder, which we will be exploring in detail in this article! I definitely recommend readers to check out the article on universal embedding trends from HuggingFace. medium.com Now, let’s take a brief look at trends and developments in word and sentence embedding models before diving deeper into Universal Sentence Encoder. The word embedding models are perhaps some of the older and more mature models which have been developed starting with Word2Vec in 2013. The three most common models leveraging deep learning (unsupervised approaches) models based on embedding word vectors in a continuous vector space based on semantic and contextual similarity are: Word2Vec GloVe FastText These models are based on the principle of distributional hypothesis in the field of distributional semantics, which tells us that words which occur and are used in the same context, are semantically similar to one another and have similar meanings (‘a word is characterized by the company it keeps’). Do refer to my article on word embeddings which cover these three methods in detail, if you are interested in the gory details! Another interesting model in this area which has been developed recently, is ELMo. This has been developed by the Allen Institute for Artificial Intelligence. ELMo is a take on the famous muppet character of the same name from the famed show, ‘Sesame Street’, but actually is an acronym which stands for ‘Embeddings from Language Models’. Basically, ELMo gives us word embeddings which are learnt from a deep bidirectional language model (biLM), which is typically pre-trained on a large text corpus, enabling transfer learning for these embeddings to be used across different NLP tasks. Allen AI tells us that ELMo representations are contextual, deep and character-based which uses morphological clues to form representations even for OOV (out-of-vocabulary) tokens. The concept of sentence embeddings is not a very new concept, because back when word embeddings were built, one of the easiest ways to build a baseline sentence embedding model was by averaging. A baseline sentence embedding model can be built by just averaging out the individual word embeddings for every sentence\document (kind of similar to bag of words, where we lose that inherent context and sequence of words in the sentence). We do cover this in detail in my article. The following figure shows a way of implementing this. Of course, there are more sophisticated approaches like encoding sentences in a linear weighted combination of their word embeddings and then removing some of the common principal components. Do check out, ‘A Simple but Tough-to-Beat Baseline for Sentence Embeddings’. Doc2Vec is also a very popular approach proposed by Mikolov et. al. in their paper ‘Distributed Representations of Sentences and Documents’. Herein, they propose the Paragraph Vector, an unsupervised algorithm that learns fixed-length feature embeddings from variable-length pieces of texts, such as sentences, paragraphs, and documents. Based on the above depiction, the model represents each document by a dense vector which is trained to predict words in the document. The only difference being the paragraph or document ID, used along with the regular word tokens to build out the embeddings. Such a design enables this model to overcome the weaknesses of bag-of-words models. Neural-Net Language Models (NNLM) is a very early idea based on a neural probabilistic language model proposed by Bengio et al. in their paper, ‘A Neural Probabilistic Language Model’ in 2003, they talk about learning a distributed representation for words which allows each training sentence to inform the model about an exponential number of semantically neighboring sentences. The model learns simultaneously a distributed representation for each word along with the probability function for word sequences, expressed in terms of these representations. Generalization is obtained because a sequence of words that has never been seen before gets high probability if it is made of words that are similar (in the sense of having a nearby representation) to words forming an already seen sentence. Google has built a universal sentence embedding model, nnlm-en-dim128 which is a token-based text embedding-trained model that uses a three-hidden-layer feed-forward Neural-Net Language Model on the English Google News 200B corpus. This model maps any body of text into 128-dimensional embeddings. We will be using this in our hands-on demonstration shortly! Skip-Thought Vectors were also one of the first models in the domain of unsupervised learning-based generic sentence encoders. In their proposed paper, ‘Skip-Thought Vectors’, using the continuity of text from books, they have trained an encoder-decoder model that tries to reconstruct the surrounding sentences of an encoded passage. Sentences that share semantic and syntactic properties are mapped to similar vector representations. This is just like the Skip-gram model, but for sentences, where we try to predict the surrounding sentences of a given source sentence. Quick Thought Vectors is a more recent unupervised approach towards learning sentence emebddings. Details are mentioned in the paper ‘An efficient framework for learning sentence representations’. Interestingly, they reformulate the problem of predicting the context in which a sentence appears as a classification problem by replacing the decoder with a classfier in the regular encoder-decoder architecture. Thus, given a sentence and the context in which it appears, a classifier distinguishes context sentences from other contrastive sentences based on their embedding representations. Given an input sentence, it is first encoded by using some function. But instead of generating the target sentence, the model chooses the correct target sentence from a set of candidate sentences. Viewing generation as choosing a sentence from all possible sentences, this can be seen as a discriminative approximation to the generation problem. InferSent is interestingly a supervised learning approach to learning universal sentence embeddings using natural language inference data. This is hardcore supervised transfer learning, where just like we get pre-trained models trained on the ImageNet dataset for computer vision, they have universal sentence representations trained using supervised data from the Stanford Natural Language Inference datasets. Details are mentioned in their paper, ‘Supervised Learning of Universal Sentence Representations from Natural Language Inference Data’. The dataset used by this model is the SNLI dataset that comprises 570k human-generated English sentence pairs, manually labeled with one of the three categories: entailment, contradiction and neutral. It captures natural language inference useful for understanding sentence semantics. Based on the architecture depicted in the above figure, we can see that it uses a shared sentence encoder that outputs a representation for the premise u and the hypothesis v. Once the sentence vectors are generated, 3 matching methods are applied to extract relations between u and v : Concatenation (u, v) Element-wise product u ∗ v Absolute element-wise difference |u − v| The resulting vector is then fed into a 3-class classifier consisting of multiple fully connected layers culminating in a softmax layer. Universal Sentence Encoder from Google is one of the latest and best universal sentence embedding models which was published in early 2018! The Universal Sentence Encoder encodes any body of text into 512-dimensional embeddings that can be used for a wide variety of NLP tasks including text classification, semantic similarity and clustering. It is trained on a variety of data sources and a variety of tasks with the aim of dynamically accommodating a wide variety of natural language understanding tasks which require modeling the meaning of sequences of words rather than just individual words. Their key finding is that, transfer learning using sentence embeddings tends to outperform word embedding level transfer. Do check out their paper, ‘Universal Sentence Encoder’ for further details. Essentially, they have two versions of their model available in TF-Hub as universal-sentence-encoder. Version 1 makes use of the transformer-network based sentence encoding model and Version 2 makes use of a Deep Averaging Network (DAN) where input embeddings for words and bi-grams are first averaged together and then passed through a feed-forward deep neural network (DNN) to produce sentence embeddings. We will be using Version 2 in our hands-on demonstration shortly. It’s time for putting some of these universal sentence encoders into action with a hands-on demonstration! Like the article mentions, the premise of our demonstration today will focus on a very popular NLP task, text classification — in the context of sentiment analysis. We will be working with the benchmark IMDB Large Movie Review Dataset. Feel free to download it here or you can even download it from my GitHub repository. This dataset comprises a total of 50,000 movie reviews, where 25K have positive sentiment and 25K have negative sentiment. We will be training our models on a total of 30,000 reviews as our training dataset, validate on 5,000 reviews and use 15,000 reviews as our test dataset. The main objective is to correctly predict the sentiment of each review as either positive or negative. Now that we have our main objective cleared up, let’s put universal sentence encoders into action! The entire tutorial is available in my GitHub repository as a Jupyter Notebook. Feel free to download it and play around with it. I recommend using a GPU-based instance for playing around with this. I love using Paperspace where you can spin up notebooks in the cloud without needing to worry about configuring instances manually. www.paperspace.com My setup was an 8 CPU, 30 GB, 250 GB SSD and an NVIDIA Quadro P4000 which is usually cheaper than most AWS GPU instances (I love AWS though!). Note: This tutorial is built using TensorFlow entirely given that they provide an easy access to the sentence encoders. However I’m not a big fan of their old APIs and I’m looking for someone to assist me on re-implementing the code using the tf.keras APIs instead of tf.estimator. Do reach out to me if you are interested in contributing and we can even feature your work on the same! (contact links in my profile and in the footer) We start by installing tensorflow-hub which enables us to use these sentence encoders easily. Let’s now load up our essential dependencies for this tutorial! import tensorflow as tfimport tensorflow_hub as hubimport numpy as npimport pandas as pd The following commands help you check if tensorflow will be using a GPU (if you have one set up already!) In [12]: tf.test.is_gpu_available()Out[12]: TrueIn [13]: tf.test.gpu_device_name()Out[13]: '/device:GPU:0' We can now load up out dataset and view it using pandas. I provide a compressed version of the dataset in my repository which you can use as follows. <class 'pandas.core.frame.DataFrame'>RangeIndex: 50000 entries, 0 to 49999Data columns (total 2 columns):review 50000 non-null objectsentiment 50000 non-null objectdtypes: object(2)memory usage: 781.3+ KB We encode the sentiment column as 1s and 0s just to make things easier for us during model development (label encoding). We will now create train, validation and test datasets before we start modeling. We will use 30,000 reviews for train, 5,000 for validation and 15,000 for test. You can use a train-test splitting function also like train_test_split() from scikit-learn. I was just lazy and subsetted the dataset using simple list slicing. ((30000,), (5000,), (15000,)) There is some basic text wrangling and pre-processing we need to do to remove some noise from our text like contractions, unnecessary special characters, HTML tags and so on. The following code helps us build a simple, yet effective text wrangling system. Do install the following libraries in case you don’t have them. The following functions help us build our text wrangling system. Let’s now pre-process our datasets using the function we implemented above. Since we will be implementing our models in tensorflow using the tf.estimator API, we need to define some functions to build data and feature engineering pipelines to enable data flowing into our models during training. The following functions will help us. We leverage the numpy_input_fn() which helps in feeding a dict of numpy arrays into the model. We are now ready to build our models! We need to first define the sentence embedding feature which leverages the universal sentence encoder before building the model. We can do that using the following code. INFO:tensorflow:Using /tmp/tfhub_modules to cache modules. Like we discussed, we use the Universal Sentence Encoder Version 2 and it works on the sentence attribute in our input dictionary which will be a numpy array of our reviews. We will build a simple feed-forward DNN now with two hidden layers. Just a standard model, nothing too sophisticated since we want to see how well these embeddings perform even on a simple model. Here we are leveraging transfer learning in the form of pre-trained embeddings. We are not fine-tuning here by keeping the embedding weights fixed by setting trainable=False. We had set our batch_size to 256 and we will be flowing in data in batches of 256 records for 1500 steps which translates to roughly 12–13 epochs. Let’s train our model now on our training dataset and evaluate on both train and validation datasets at steps of 100. --------------------------------------------------------------------Training for step = 0Train Time (s): 78.62789511680603Eval Metrics (Train): {'accuracy': 0.84863335, 'accuracy_baseline': 0.5005, 'auc': 0.9279859, 'auc_precision_recall': 0.92819566, 'average_loss': 0.34581015, 'label/mean': 0.5005, 'loss': 44.145977, 'precision': 0.86890674, 'prediction/mean': 0.47957155, 'recall': 0.8215118, 'global_step': 100}Eval Metrics (Validation): {'accuracy': 0.8454, 'accuracy_baseline': 0.505, 'auc': 0.92413086, 'auc_precision_recall': 0.9200026, 'average_loss': 0.35258815, 'label/mean': 0.495, 'loss': 44.073517, 'precision': 0.8522351, 'prediction/mean': 0.48447067, 'recall': 0.8319192, 'global_step': 100}--------------------------------------------------------------------Training for step = 100Train Time (s): 76.1651611328125Eval Metrics (Train): {'accuracy': 0.85436666, 'accuracy_baseline': 0.5005, 'auc': 0.9321357, 'auc_precision_recall': 0.93224275, 'average_loss': 0.3330773, 'label/mean': 0.5005, 'loss': 42.520508, 'precision': 0.8501513, 'prediction/mean': 0.5098621, 'recall': 0.86073923, 'global_step': 200}Eval Metrics (Validation): {'accuracy': 0.8494, 'accuracy_baseline': 0.505, 'auc': 0.92772096, 'auc_precision_recall': 0.92323804, 'average_loss': 0.34418356, 'label/mean': 0.495, 'loss': 43.022945, 'precision': 0.83501947, 'prediction/mean': 0.5149463, 'recall': 0.86707073, 'global_step': 200}--------------------------------------------------------------------.........--------------------------------------------------------------------Training for step = 1400Train Time (s): 85.99037742614746Eval Metrics (Train): {'accuracy': 0.8783, 'accuracy_baseline': 0.5005, 'auc': 0.9500882, 'auc_precision_recall': 0.94986326, 'average_loss': 0.28882334, 'label/mean': 0.5005, 'loss': 36.871063, 'precision': 0.865308, 'prediction/mean': 0.5196238, 'recall': 0.8963703, 'global_step': 1500}Eval Metrics (Validation): {'accuracy': 0.8626, 'accuracy_baseline': 0.505, 'auc': 0.93708724, 'auc_precision_recall': 0.9336051, 'average_loss': 0.32389137, 'label/mean': 0.495, 'loss': 40.486423, 'precision': 0.84044176, 'prediction/mean': 0.5226699, 'recall': 0.8917172, 'global_step': 1500}--------------------------------------------------------------------Training for step = 1500Train Time (s): 86.91469407081604Eval Metrics (Train): {'accuracy': 0.8802, 'accuracy_baseline': 0.5005, 'auc': 0.95115364, 'auc_precision_recall': 0.950775, 'average_loss': 0.2844779, 'label/mean': 0.5005, 'loss': 36.316326, 'precision': 0.8735527, 'prediction/mean': 0.51057553, 'recall': 0.8893773, 'global_step': 1600}Eval Metrics (Validation): {'accuracy': 0.8626, 'accuracy_baseline': 0.505, 'auc': 0.9373224, 'auc_precision_recall': 0.9336302, 'average_loss': 0.32108024, 'label/mean': 0.495, 'loss': 40.135033, 'precision': 0.8478599, 'prediction/mean': 0.5134171, 'recall': 0.88040406, 'global_step': 1600} I have highlighted the metrics of interest in the output logs above and as you can see, we get an overall accuracy of close to 87% on our validation dataset and an AUC of 94% which is quite good on such a simple model! Let’s now evaluate our model and check the overall performance on the train and test datasets. We get an overall accuracy of close to 87% on the test data giving us consistent results based on what we observed on our validation dataset earlier! Thus, this should give you an idea of how easy it is to leverage pre-trained universal sentence embeddings and not worry about the hassle of feature engineering or complex modeling. Let’s now try building different deep learning classifiers based on different sentence embeddings. We will try the following: NNLM-128 USE-512 We will also cover the two most prominent methodologies for transfer learning here. Build a model using freezed pre-trained sentence embeddings Build a model where we fine-tune and update the pre-trained sentence embeddings during training The following generic function can plug and play different universal sentence encoders from tensorflow-hub! We can now train our models using the above-defined approaches. ====================================================================Training with https://tfhub.dev/google/nnlm-en-dim128/1Trainable is: False====================================================================--------------------------------------------------------------------Training for step = 0Train Time (s): 30.525171756744385Eval Metrics (Train): {'accuracy': 0.8480667, 'auc': 0.9287864, 'precision': 0.8288572, 'recall': 0.8776557}Eval Metrics (Validation): {'accuracy': 0.8288, 'auc': 0.91452694, 'precision': 0.7999259, 'recall': 0.8723232}--------------------------------------------------------------------......--------------------------------------------------------------------Training for step = 1500Train Time (s): 28.242169618606567Eval Metrics (Train): {'accuracy': 0.8616, 'auc': 0.9385461, 'precision': 0.8443543, 'recall': 0.8869797}Eval Metrics (Validation): {'accuracy': 0.828, 'auc': 0.91572505, 'precision': 0.80322945, 'recall': 0.86424243}====================================================================Training with https://tfhub.dev/google/nnlm-en-dim128/1Trainable is: True====================================================================--------------------------------------------------------------------Training for step = 0Train Time (s): 45.97756814956665Eval Metrics (Train): {'accuracy': 0.9997, 'auc': 0.9998141, 'precision': 0.99980015, 'recall': 0.9996004}Eval Metrics (Validation): {'accuracy': 0.877, 'auc': 0.9225529, 'precision': 0.86671925, 'recall': 0.88808084}--------------------------------------------------------------------......--------------------------------------------------------------------Training for step = 1500Train Time (s): 44.654765605926514Eval Metrics (Train): {'accuracy': 1.0, 'auc': 1.0, 'precision': 1.0, 'recall': 1.0}Eval Metrics (Validation): {'accuracy': 0.875, 'auc': 0.91479605, 'precision': 0.8661916, 'recall': 0.8840404}====================================================================Training with https://tfhub.dev/google/universal-sentence-encoder/2Trainable is: False====================================================================--------------------------------------------------------------------Training for step = 0Train Time (s): 261.7671597003937Eval Metrics (Train): {'accuracy': 0.8591, 'auc': 0.9373971, 'precision': 0.8820655, 'recall': 0.8293706}Eval Metrics (Validation): {'accuracy': 0.8522, 'auc': 0.93081224, 'precision': 0.8631799, 'recall': 0.8335354}--------------------------------------------------------------------......--------------------------------------------------------------------Training for step = 1500Train Time (s): 258.4421606063843Eval Metrics (Train): {'accuracy': 0.88733333, 'auc': 0.9558296, 'precision': 0.8979955, 'recall': 0.8741925}Eval Metrics (Validation): {'accuracy': 0.864, 'auc': 0.938815, 'precision': 0.864393, 'recall': 0.860202}====================================================================Training with https://tfhub.dev/google/universal-sentence-encoder/2Trainable is: True====================================================================--------------------------------------------------------------------Training for step = 0Train Time (s): 313.1993100643158Eval Metrics (Train): {'accuracy': 0.99916667, 'auc': 0.9996535, 'precision': 0.9989349, 'recall': 0.9994006}Eval Metrics (Validation): {'accuracy': 0.9056, 'auc': 0.95068294, 'precision': 0.9020474, 'recall': 0.9078788}--------------------------------------------------------------------......--------------------------------------------------------------------Training for step = 1500Train Time (s): 305.9913341999054Eval Metrics (Train): {'accuracy': 1.0, 'auc': 1.0, 'precision': 1.0, 'recall': 1.0}Eval Metrics (Validation): {'accuracy': 0.9032, 'auc': 0.929281, 'precision': 0.8986784, 'recall': 0.9066667} I’ve depicted the evaluation metrics of importance in the above outputs, and you can see we definitely get some good results with our models. The following table summarizes these comparative results in a nice way. Looks like Google’s Universal Sentence Encoder with fine-tuning gave us the best results on the test data. Let’s load up this saved model and run an evaluation on the test data. [0, 1, 0, 1, 1, 0, 1, 1, 1, 1] One of the best ways to evaluate our model performance is to visualize the model predictions in the form of a confusion matrix. We can also print out the model’s classification report using scikit-learn to show the other important metrics which can be derived from the confusion matrix including precision, recall and f1-score. We obtain an overall model accuracy and f1-score of 90% on the test data which is really good! Go ahead and try this out and maybe get an even better score and let me know about it! Universal Sentence Embeddings are definitely a huge step forward in enabling transfer learning for diverse NLP tasks. In fact, we have seen models like ELMo, Universal Sentence Encoder, ULMFiT have indeed made headlines by showcasing that pre-trained models can be used to achieve state-of-the-art results on NLP tasks. Famed Research Scientist and Blogger Sebastian Ruder, mentioned the same in his recent tweet based on a very interesting article which he wrote recently. I’m definitely excited about what the future holds for generalizing NLP even further, and enabling us to solve complex tasks with ease! The code used for hands-on demonstrations in this article is available in my GitHub repository as a Jupyter Notebook which you can play around with! Help Needed: Like I mentioned, I’m looking for someone to help me convert this code to use the newer tf.keras APIs instead of tf.estimator. Interested? Reach out to me! Have feedback for me? Or interested in working with me on research, data science, artificial intelligence or even publishing an article on TDS? You can reach out to me on LinkedIn. www.linkedin.co Thanks to Durba for editing this article.
[ { "code": null, "e": 1064, "s": 171, "text": "Transfer learning is an exciting concept where we try to leverage prior knowledge from one domain and task into a different domain and task. The inspiration comes from us — humans, ourselves — where in, we have an inherent ability to not learn everything from scratch. We transfer and leverage our knowledge from what we have learnt in the past for tackling a wide variety of tasks. With computer vision, we have excellent big datasets available to us, like Imagenet, on which, we get a suite of world-class, state-of-the-art pre-trained model to leverage transfer learning. But what about Natural Language Processing? Therein lies the challenge, considering text data is so diverse, noisy and unstructured. We’ve had some recent successes with word embeddings including methods like Word2Vec, GloVe and FastText, all of which I have covered in my article ‘Feature Engineering for Text Data’." }, { "code": null, "e": 1087, "s": 1064, "text": "towardsdatascience.com" }, { "code": null, "e": 1382, "s": 1087, "text": "In this article, we will be showcasing several state-of-the-art generic sentence embedding encoders, which tend to give surprisingly good performance, especially on small amounts of data for transfer learning tasks as compared to word embedding models. We will be covering the following models:" }, { "code": null, "e": 1420, "s": 1382, "text": "Baseline Averaged Sentence Embeddings" }, { "code": null, "e": 1428, "s": 1420, "text": "Doc2Vec" }, { "code": null, "e": 1472, "s": 1428, "text": "Neural-Net Language Models (Hands-on Demo!)" }, { "code": null, "e": 1493, "s": 1472, "text": "Skip-Thought Vectors" }, { "code": null, "e": 1515, "s": 1493, "text": "Quick-Thought Vectors" }, { "code": null, "e": 1525, "s": 1515, "text": "InferSent" }, { "code": null, "e": 1552, "s": 1525, "text": "Universal Sentence Encoder" }, { "code": null, "e": 1731, "s": 1552, "text": "We will try to cover essential concepts and also showcase some hands-on examples leveraging Python and Tensorflow, in a text classification problem focused on sentiment analysis!" }, { "code": null, "e": 1887, "s": 1731, "text": "What is this sudden craze behind embeddings? I’m sure many of you might be hearing it everywhere. Let’s clear up the basics first and cut through the hype." }, { "code": null, "e": 2009, "s": 1887, "text": "An embedding is a fixed-length vector typically used to encode and represent an entity (document, sentence, word, graph!)" }, { "code": null, "e": 2819, "s": 2009, "text": "I’ve talked about the need for embeddings in the context of text data and NLP in one of my previous articles. But I will briefly reiterate this here for the sake of convenience. With regard to speech or image recognition systems, we already get information in the form of rich dense feature vectors embedded in high-dimensional datasets like audio spectrograms and image pixel intensities. However, when it comes to raw text data, especially count-based models like Bag of Words, we are dealing with individual words, which may have their own identifiers, and do not capture the semantic relationship among words. This leads to huge sparse word vectors for textual data and thus, if we do not have enough data, we may end up getting poor models or even overfitting the data due to the curse of dimensionality." }, { "code": null, "e": 3060, "s": 2819, "text": "Predictive methods like Neural Network based language models try to predict words from its neighboring words looking at word sequences in the corpus and in the process, it learns distributed representations, giving us dense word embeddings." }, { "code": null, "e": 3614, "s": 3060, "text": "Now you might be thinking, big deal, we get a bunch of vectors from text. What now? Well, this craze for embeddings is that, if we have a good numeric representation of text data which captures even the context and semantics, we can use it for a wide variety of downstream real-world tasks like sentiment analysis, text classification, clustering, summarization, translation and so on. The fact of the matter is, machine learning or deep learning models run on numbers, and embeddings are the key to encoding text data that will be used by these models." }, { "code": null, "e": 4236, "s": 3614, "text": "A big trend here has been finding out so-called ‘Universal Embeddings’ which are basically pre-trained embeddings obtained from training deep learning models on a huge corpus. This enables us to use these pre-trained (generic) embeddings in a wide variety of tasks including, scenarios with constraints like lack of adequate data. This is a perfect example of transfer learning, leveraging prior knowledge from pre-trained embeddings to solve a completely new task! The following figure showcases some recent trends in Universal Word & Sentence Embeddings, thanks to an amazing article from the folks over at HuggingFace!" }, { "code": null, "e": 4498, "s": 4236, "text": "Definitely, some interesting trends in the above figure including, Google’s Universal Sentence Encoder, which we will be exploring in detail in this article! I definitely recommend readers to check out the article on universal embedding trends from HuggingFace." }, { "code": null, "e": 4509, "s": 4498, "text": "medium.com" }, { "code": null, "e": 4657, "s": 4509, "text": "Now, let’s take a brief look at trends and developments in word and sentence embedding models before diving deeper into Universal Sentence Encoder." }, { "code": null, "e": 4991, "s": 4657, "text": "The word embedding models are perhaps some of the older and more mature models which have been developed starting with Word2Vec in 2013. The three most common models leveraging deep learning (unsupervised approaches) models based on embedding word vectors in a continuous vector space based on semantic and contextual similarity are:" }, { "code": null, "e": 5000, "s": 4991, "text": "Word2Vec" }, { "code": null, "e": 5006, "s": 5000, "text": "GloVe" }, { "code": null, "e": 5015, "s": 5006, "text": "FastText" }, { "code": null, "e": 5445, "s": 5015, "text": "These models are based on the principle of distributional hypothesis in the field of distributional semantics, which tells us that words which occur and are used in the same context, are semantically similar to one another and have similar meanings (‘a word is characterized by the company it keeps’). Do refer to my article on word embeddings which cover these three methods in detail, if you are interested in the gory details!" }, { "code": null, "e": 5784, "s": 5445, "text": "Another interesting model in this area which has been developed recently, is ELMo. This has been developed by the Allen Institute for Artificial Intelligence. ELMo is a take on the famous muppet character of the same name from the famed show, ‘Sesame Street’, but actually is an acronym which stands for ‘Embeddings from Language Models’." }, { "code": null, "e": 6214, "s": 5784, "text": "Basically, ELMo gives us word embeddings which are learnt from a deep bidirectional language model (biLM), which is typically pre-trained on a large text corpus, enabling transfer learning for these embeddings to be used across different NLP tasks. Allen AI tells us that ELMo representations are contextual, deep and character-based which uses morphological clues to form representations even for OOV (out-of-vocabulary) tokens." }, { "code": null, "e": 6409, "s": 6214, "text": "The concept of sentence embeddings is not a very new concept, because back when word embeddings were built, one of the easiest ways to build a baseline sentence embedding model was by averaging." }, { "code": null, "e": 6746, "s": 6409, "text": "A baseline sentence embedding model can be built by just averaging out the individual word embeddings for every sentence\\document (kind of similar to bag of words, where we lose that inherent context and sequence of words in the sentence). We do cover this in detail in my article. The following figure shows a way of implementing this." }, { "code": null, "e": 7015, "s": 6746, "text": "Of course, there are more sophisticated approaches like encoding sentences in a linear weighted combination of their word embeddings and then removing some of the common principal components. Do check out, ‘A Simple but Tough-to-Beat Baseline for Sentence Embeddings’." }, { "code": null, "e": 7353, "s": 7015, "text": "Doc2Vec is also a very popular approach proposed by Mikolov et. al. in their paper ‘Distributed Representations of Sentences and Documents’. Herein, they propose the Paragraph Vector, an unsupervised algorithm that learns fixed-length feature embeddings from variable-length pieces of texts, such as sentences, paragraphs, and documents." }, { "code": null, "e": 7696, "s": 7353, "text": "Based on the above depiction, the model represents each document by a dense vector which is trained to predict words in the document. The only difference being the paragraph or document ID, used along with the regular word tokens to build out the embeddings. Such a design enables this model to overcome the weaknesses of bag-of-words models." }, { "code": null, "e": 8493, "s": 7696, "text": "Neural-Net Language Models (NNLM) is a very early idea based on a neural probabilistic language model proposed by Bengio et al. in their paper, ‘A Neural Probabilistic Language Model’ in 2003, they talk about learning a distributed representation for words which allows each training sentence to inform the model about an exponential number of semantically neighboring sentences. The model learns simultaneously a distributed representation for each word along with the probability function for word sequences, expressed in terms of these representations. Generalization is obtained because a sequence of words that has never been seen before gets high probability if it is made of words that are similar (in the sense of having a nearby representation) to words forming an already seen sentence." }, { "code": null, "e": 8852, "s": 8493, "text": "Google has built a universal sentence embedding model, nnlm-en-dim128 which is a token-based text embedding-trained model that uses a three-hidden-layer feed-forward Neural-Net Language Model on the English Google News 200B corpus. This model maps any body of text into 128-dimensional embeddings. We will be using this in our hands-on demonstration shortly!" }, { "code": null, "e": 9288, "s": 8852, "text": "Skip-Thought Vectors were also one of the first models in the domain of unsupervised learning-based generic sentence encoders. In their proposed paper, ‘Skip-Thought Vectors’, using the continuity of text from books, they have trained an encoder-decoder model that tries to reconstruct the surrounding sentences of an encoded passage. Sentences that share semantic and syntactic properties are mapped to similar vector representations." }, { "code": null, "e": 9424, "s": 9288, "text": "This is just like the Skip-gram model, but for sentences, where we try to predict the surrounding sentences of a given source sentence." }, { "code": null, "e": 9834, "s": 9424, "text": "Quick Thought Vectors is a more recent unupervised approach towards learning sentence emebddings. Details are mentioned in the paper ‘An efficient framework for learning sentence representations’. Interestingly, they reformulate the problem of predicting the context in which a sentence appears as a classification problem by replacing the decoder with a classfier in the regular encoder-decoder architecture." }, { "code": null, "e": 10360, "s": 9834, "text": "Thus, given a sentence and the context in which it appears, a classifier distinguishes context sentences from other contrastive sentences based on their embedding representations. Given an input sentence, it is first encoded by using some function. But instead of generating the target sentence, the model chooses the correct target sentence from a set of candidate sentences. Viewing generation as choosing a sentence from all possible sentences, this can be seen as a discriminative approximation to the generation problem." }, { "code": null, "e": 11192, "s": 10360, "text": "InferSent is interestingly a supervised learning approach to learning universal sentence embeddings using natural language inference data. This is hardcore supervised transfer learning, where just like we get pre-trained models trained on the ImageNet dataset for computer vision, they have universal sentence representations trained using supervised data from the Stanford Natural Language Inference datasets. Details are mentioned in their paper, ‘Supervised Learning of Universal Sentence Representations from Natural Language Inference Data’. The dataset used by this model is the SNLI dataset that comprises 570k human-generated English sentence pairs, manually labeled with one of the three categories: entailment, contradiction and neutral. It captures natural language inference useful for understanding sentence semantics." }, { "code": null, "e": 11479, "s": 11192, "text": "Based on the architecture depicted in the above figure, we can see that it uses a shared sentence encoder that outputs a representation for the premise u and the hypothesis v. Once the sentence vectors are generated, 3 matching methods are applied to extract relations between u and v :" }, { "code": null, "e": 11500, "s": 11479, "text": "Concatenation (u, v)" }, { "code": null, "e": 11527, "s": 11500, "text": "Element-wise product u ∗ v" }, { "code": null, "e": 11568, "s": 11527, "text": "Absolute element-wise difference |u − v|" }, { "code": null, "e": 11705, "s": 11568, "text": "The resulting vector is then fed into a 3-class classifier consisting of multiple fully connected layers culminating in a softmax layer." }, { "code": null, "e": 12304, "s": 11705, "text": "Universal Sentence Encoder from Google is one of the latest and best universal sentence embedding models which was published in early 2018! The Universal Sentence Encoder encodes any body of text into 512-dimensional embeddings that can be used for a wide variety of NLP tasks including text classification, semantic similarity and clustering. It is trained on a variety of data sources and a variety of tasks with the aim of dynamically accommodating a wide variety of natural language understanding tasks which require modeling the meaning of sequences of words rather than just individual words." }, { "code": null, "e": 12976, "s": 12304, "text": "Their key finding is that, transfer learning using sentence embeddings tends to outperform word embedding level transfer. Do check out their paper, ‘Universal Sentence Encoder’ for further details. Essentially, they have two versions of their model available in TF-Hub as universal-sentence-encoder. Version 1 makes use of the transformer-network based sentence encoding model and Version 2 makes use of a Deep Averaging Network (DAN) where input embeddings for words and bi-grams are first averaged together and then passed through a feed-forward deep neural network (DNN) to produce sentence embeddings. We will be using Version 2 in our hands-on demonstration shortly." }, { "code": null, "e": 13404, "s": 12976, "text": "It’s time for putting some of these universal sentence encoders into action with a hands-on demonstration! Like the article mentions, the premise of our demonstration today will focus on a very popular NLP task, text classification — in the context of sentiment analysis. We will be working with the benchmark IMDB Large Movie Review Dataset. Feel free to download it here or you can even download it from my GitHub repository." }, { "code": null, "e": 13786, "s": 13404, "text": "This dataset comprises a total of 50,000 movie reviews, where 25K have positive sentiment and 25K have negative sentiment. We will be training our models on a total of 30,000 reviews as our training dataset, validate on 5,000 reviews and use 15,000 reviews as our test dataset. The main objective is to correctly predict the sentiment of each review as either positive or negative." }, { "code": null, "e": 14216, "s": 13786, "text": "Now that we have our main objective cleared up, let’s put universal sentence encoders into action! The entire tutorial is available in my GitHub repository as a Jupyter Notebook. Feel free to download it and play around with it. I recommend using a GPU-based instance for playing around with this. I love using Paperspace where you can spin up notebooks in the cloud without needing to worry about configuring instances manually." }, { "code": null, "e": 14235, "s": 14216, "text": "www.paperspace.com" }, { "code": null, "e": 14378, "s": 14235, "text": "My setup was an 8 CPU, 30 GB, 250 GB SSD and an NVIDIA Quadro P4000 which is usually cheaper than most AWS GPU instances (I love AWS though!)." }, { "code": null, "e": 14812, "s": 14378, "text": "Note: This tutorial is built using TensorFlow entirely given that they provide an easy access to the sentence encoders. However I’m not a big fan of their old APIs and I’m looking for someone to assist me on re-implementing the code using the tf.keras APIs instead of tf.estimator. Do reach out to me if you are interested in contributing and we can even feature your work on the same! (contact links in my profile and in the footer)" }, { "code": null, "e": 14906, "s": 14812, "text": "We start by installing tensorflow-hub which enables us to use these sentence encoders easily." }, { "code": null, "e": 14970, "s": 14906, "text": "Let’s now load up our essential dependencies for this tutorial!" }, { "code": null, "e": 15059, "s": 14970, "text": "import tensorflow as tfimport tensorflow_hub as hubimport numpy as npimport pandas as pd" }, { "code": null, "e": 15165, "s": 15059, "text": "The following commands help you check if tensorflow will be using a GPU (if you have one set up already!)" }, { "code": null, "e": 15272, "s": 15165, "text": "In [12]: tf.test.is_gpu_available()Out[12]: TrueIn [13]: tf.test.gpu_device_name()Out[13]: '/device:GPU:0'" }, { "code": null, "e": 15422, "s": 15272, "text": "We can now load up out dataset and view it using pandas. I provide a compressed version of the dataset in my repository which you can use as follows." }, { "code": null, "e": 15636, "s": 15422, "text": "<class 'pandas.core.frame.DataFrame'>RangeIndex: 50000 entries, 0 to 49999Data columns (total 2 columns):review 50000 non-null objectsentiment 50000 non-null objectdtypes: object(2)memory usage: 781.3+ KB" }, { "code": null, "e": 15757, "s": 15636, "text": "We encode the sentiment column as 1s and 0s just to make things easier for us during model development (label encoding)." }, { "code": null, "e": 16079, "s": 15757, "text": "We will now create train, validation and test datasets before we start modeling. We will use 30,000 reviews for train, 5,000 for validation and 15,000 for test. You can use a train-test splitting function also like train_test_split() from scikit-learn. I was just lazy and subsetted the dataset using simple list slicing." }, { "code": null, "e": 16109, "s": 16079, "text": "((30000,), (5000,), (15000,))" }, { "code": null, "e": 16429, "s": 16109, "text": "There is some basic text wrangling and pre-processing we need to do to remove some noise from our text like contractions, unnecessary special characters, HTML tags and so on. The following code helps us build a simple, yet effective text wrangling system. Do install the following libraries in case you don’t have them." }, { "code": null, "e": 16494, "s": 16429, "text": "The following functions help us build our text wrangling system." }, { "code": null, "e": 16570, "s": 16494, "text": "Let’s now pre-process our datasets using the function we implemented above." }, { "code": null, "e": 16923, "s": 16570, "text": "Since we will be implementing our models in tensorflow using the tf.estimator API, we need to define some functions to build data and feature engineering pipelines to enable data flowing into our models during training. The following functions will help us. We leverage the numpy_input_fn() which helps in feeding a dict of numpy arrays into the model." }, { "code": null, "e": 16961, "s": 16923, "text": "We are now ready to build our models!" }, { "code": null, "e": 17131, "s": 16961, "text": "We need to first define the sentence embedding feature which leverages the universal sentence encoder before building the model. We can do that using the following code." }, { "code": null, "e": 17190, "s": 17131, "text": "INFO:tensorflow:Using /tmp/tfhub_modules to cache modules." }, { "code": null, "e": 17735, "s": 17190, "text": "Like we discussed, we use the Universal Sentence Encoder Version 2 and it works on the sentence attribute in our input dictionary which will be a numpy array of our reviews. We will build a simple feed-forward DNN now with two hidden layers. Just a standard model, nothing too sophisticated since we want to see how well these embeddings perform even on a simple model. Here we are leveraging transfer learning in the form of pre-trained embeddings. We are not fine-tuning here by keeping the embedding weights fixed by setting trainable=False." }, { "code": null, "e": 17882, "s": 17735, "text": "We had set our batch_size to 256 and we will be flowing in data in batches of 256 records for 1500 steps which translates to roughly 12–13 epochs." }, { "code": null, "e": 18000, "s": 17882, "text": "Let’s train our model now on our training dataset and evaluate on both train and validation datasets at steps of 100." }, { "code": null, "e": 20914, "s": 18000, "text": "--------------------------------------------------------------------Training for step = 0Train Time (s): 78.62789511680603Eval Metrics (Train): {'accuracy': 0.84863335, 'accuracy_baseline': 0.5005, 'auc': 0.9279859, 'auc_precision_recall': 0.92819566, 'average_loss': 0.34581015, 'label/mean': 0.5005, 'loss': 44.145977, 'precision': 0.86890674, 'prediction/mean': 0.47957155, 'recall': 0.8215118, 'global_step': 100}Eval Metrics (Validation): {'accuracy': 0.8454, 'accuracy_baseline': 0.505, 'auc': 0.92413086, 'auc_precision_recall': 0.9200026, 'average_loss': 0.35258815, 'label/mean': 0.495, 'loss': 44.073517, 'precision': 0.8522351, 'prediction/mean': 0.48447067, 'recall': 0.8319192, 'global_step': 100}--------------------------------------------------------------------Training for step = 100Train Time (s): 76.1651611328125Eval Metrics (Train): {'accuracy': 0.85436666, 'accuracy_baseline': 0.5005, 'auc': 0.9321357, 'auc_precision_recall': 0.93224275, 'average_loss': 0.3330773, 'label/mean': 0.5005, 'loss': 42.520508, 'precision': 0.8501513, 'prediction/mean': 0.5098621, 'recall': 0.86073923, 'global_step': 200}Eval Metrics (Validation): {'accuracy': 0.8494, 'accuracy_baseline': 0.505, 'auc': 0.92772096, 'auc_precision_recall': 0.92323804, 'average_loss': 0.34418356, 'label/mean': 0.495, 'loss': 43.022945, 'precision': 0.83501947, 'prediction/mean': 0.5149463, 'recall': 0.86707073, 'global_step': 200}--------------------------------------------------------------------.........--------------------------------------------------------------------Training for step = 1400Train Time (s): 85.99037742614746Eval Metrics (Train): {'accuracy': 0.8783, 'accuracy_baseline': 0.5005, 'auc': 0.9500882, 'auc_precision_recall': 0.94986326, 'average_loss': 0.28882334, 'label/mean': 0.5005, 'loss': 36.871063, 'precision': 0.865308, 'prediction/mean': 0.5196238, 'recall': 0.8963703, 'global_step': 1500}Eval Metrics (Validation): {'accuracy': 0.8626, 'accuracy_baseline': 0.505, 'auc': 0.93708724, 'auc_precision_recall': 0.9336051, 'average_loss': 0.32389137, 'label/mean': 0.495, 'loss': 40.486423, 'precision': 0.84044176, 'prediction/mean': 0.5226699, 'recall': 0.8917172, 'global_step': 1500}--------------------------------------------------------------------Training for step = 1500Train Time (s): 86.91469407081604Eval Metrics (Train): {'accuracy': 0.8802, 'accuracy_baseline': 0.5005, 'auc': 0.95115364, 'auc_precision_recall': 0.950775, 'average_loss': 0.2844779, 'label/mean': 0.5005, 'loss': 36.316326, 'precision': 0.8735527, 'prediction/mean': 0.51057553, 'recall': 0.8893773, 'global_step': 1600}Eval Metrics (Validation): {'accuracy': 0.8626, 'accuracy_baseline': 0.505, 'auc': 0.9373224, 'auc_precision_recall': 0.9336302, 'average_loss': 0.32108024, 'label/mean': 0.495, 'loss': 40.135033, 'precision': 0.8478599, 'prediction/mean': 0.5134171, 'recall': 0.88040406, 'global_step': 1600}" }, { "code": null, "e": 21133, "s": 20914, "text": "I have highlighted the metrics of interest in the output logs above and as you can see, we get an overall accuracy of close to 87% on our validation dataset and an AUC of 94% which is quite good on such a simple model!" }, { "code": null, "e": 21228, "s": 21133, "text": "Let’s now evaluate our model and check the overall performance on the train and test datasets." }, { "code": null, "e": 21560, "s": 21228, "text": "We get an overall accuracy of close to 87% on the test data giving us consistent results based on what we observed on our validation dataset earlier! Thus, this should give you an idea of how easy it is to leverage pre-trained universal sentence embeddings and not worry about the hassle of feature engineering or complex modeling." }, { "code": null, "e": 21686, "s": 21560, "text": "Let’s now try building different deep learning classifiers based on different sentence embeddings. We will try the following:" }, { "code": null, "e": 21695, "s": 21686, "text": "NNLM-128" }, { "code": null, "e": 21703, "s": 21695, "text": "USE-512" }, { "code": null, "e": 21787, "s": 21703, "text": "We will also cover the two most prominent methodologies for transfer learning here." }, { "code": null, "e": 21847, "s": 21787, "text": "Build a model using freezed pre-trained sentence embeddings" }, { "code": null, "e": 21943, "s": 21847, "text": "Build a model where we fine-tune and update the pre-trained sentence embeddings during training" }, { "code": null, "e": 22051, "s": 21943, "text": "The following generic function can plug and play different universal sentence encoders from tensorflow-hub!" }, { "code": null, "e": 22115, "s": 22051, "text": "We can now train our models using the above-defined approaches." }, { "code": null, "e": 25956, "s": 22115, "text": "====================================================================Training with https://tfhub.dev/google/nnlm-en-dim128/1Trainable is: False====================================================================--------------------------------------------------------------------Training for step = 0Train Time (s): 30.525171756744385Eval Metrics (Train): {'accuracy': 0.8480667, 'auc': 0.9287864, 'precision': 0.8288572, 'recall': 0.8776557}Eval Metrics (Validation): {'accuracy': 0.8288, 'auc': 0.91452694, 'precision': 0.7999259, 'recall': 0.8723232}--------------------------------------------------------------------......--------------------------------------------------------------------Training for step = 1500Train Time (s): 28.242169618606567Eval Metrics (Train): {'accuracy': 0.8616, 'auc': 0.9385461, 'precision': 0.8443543, 'recall': 0.8869797}Eval Metrics (Validation): {'accuracy': 0.828, 'auc': 0.91572505, 'precision': 0.80322945, 'recall': 0.86424243}====================================================================Training with https://tfhub.dev/google/nnlm-en-dim128/1Trainable is: True====================================================================--------------------------------------------------------------------Training for step = 0Train Time (s): 45.97756814956665Eval Metrics (Train): {'accuracy': 0.9997, 'auc': 0.9998141, 'precision': 0.99980015, 'recall': 0.9996004}Eval Metrics (Validation): {'accuracy': 0.877, 'auc': 0.9225529, 'precision': 0.86671925, 'recall': 0.88808084}--------------------------------------------------------------------......--------------------------------------------------------------------Training for step = 1500Train Time (s): 44.654765605926514Eval Metrics (Train): {'accuracy': 1.0, 'auc': 1.0, 'precision': 1.0, 'recall': 1.0}Eval Metrics (Validation): {'accuracy': 0.875, 'auc': 0.91479605, 'precision': 0.8661916, 'recall': 0.8840404}====================================================================Training with https://tfhub.dev/google/universal-sentence-encoder/2Trainable is: False====================================================================--------------------------------------------------------------------Training for step = 0Train Time (s): 261.7671597003937Eval Metrics (Train): {'accuracy': 0.8591, 'auc': 0.9373971, 'precision': 0.8820655, 'recall': 0.8293706}Eval Metrics (Validation): {'accuracy': 0.8522, 'auc': 0.93081224, 'precision': 0.8631799, 'recall': 0.8335354}--------------------------------------------------------------------......--------------------------------------------------------------------Training for step = 1500Train Time (s): 258.4421606063843Eval Metrics (Train): {'accuracy': 0.88733333, 'auc': 0.9558296, 'precision': 0.8979955, 'recall': 0.8741925}Eval Metrics (Validation): {'accuracy': 0.864, 'auc': 0.938815, 'precision': 0.864393, 'recall': 0.860202}====================================================================Training with https://tfhub.dev/google/universal-sentence-encoder/2Trainable is: True====================================================================--------------------------------------------------------------------Training for step = 0Train Time (s): 313.1993100643158Eval Metrics (Train): {'accuracy': 0.99916667, 'auc': 0.9996535, 'precision': 0.9989349, 'recall': 0.9994006}Eval Metrics (Validation): {'accuracy': 0.9056, 'auc': 0.95068294, 'precision': 0.9020474, 'recall': 0.9078788}--------------------------------------------------------------------......--------------------------------------------------------------------Training for step = 1500Train Time (s): 305.9913341999054Eval Metrics (Train): {'accuracy': 1.0, 'auc': 1.0, 'precision': 1.0, 'recall': 1.0}Eval Metrics (Validation): {'accuracy': 0.9032, 'auc': 0.929281, 'precision': 0.8986784, 'recall': 0.9066667}" }, { "code": null, "e": 26170, "s": 25956, "text": "I’ve depicted the evaluation metrics of importance in the above outputs, and you can see we definitely get some good results with our models. The following table summarizes these comparative results in a nice way." }, { "code": null, "e": 26348, "s": 26170, "text": "Looks like Google’s Universal Sentence Encoder with fine-tuning gave us the best results on the test data. Let’s load up this saved model and run an evaluation on the test data." }, { "code": null, "e": 26379, "s": 26348, "text": "[0, 1, 0, 1, 1, 0, 1, 1, 1, 1]" }, { "code": null, "e": 26507, "s": 26379, "text": "One of the best ways to evaluate our model performance is to visualize the model predictions in the form of a confusion matrix." }, { "code": null, "e": 26707, "s": 26507, "text": "We can also print out the model’s classification report using scikit-learn to show the other important metrics which can be derived from the confusion matrix including precision, recall and f1-score." }, { "code": null, "e": 26889, "s": 26707, "text": "We obtain an overall model accuracy and f1-score of 90% on the test data which is really good! Go ahead and try this out and maybe get an even better score and let me know about it!" }, { "code": null, "e": 27363, "s": 26889, "text": "Universal Sentence Embeddings are definitely a huge step forward in enabling transfer learning for diverse NLP tasks. In fact, we have seen models like ELMo, Universal Sentence Encoder, ULMFiT have indeed made headlines by showcasing that pre-trained models can be used to achieve state-of-the-art results on NLP tasks. Famed Research Scientist and Blogger Sebastian Ruder, mentioned the same in his recent tweet based on a very interesting article which he wrote recently." }, { "code": null, "e": 27499, "s": 27363, "text": "I’m definitely excited about what the future holds for generalizing NLP even further, and enabling us to solve complex tasks with ease!" }, { "code": null, "e": 27648, "s": 27499, "text": "The code used for hands-on demonstrations in this article is available in my GitHub repository as a Jupyter Notebook which you can play around with!" }, { "code": null, "e": 27817, "s": 27648, "text": "Help Needed: Like I mentioned, I’m looking for someone to help me convert this code to use the newer tf.keras APIs instead of tf.estimator. Interested? Reach out to me!" }, { "code": null, "e": 27998, "s": 27817, "text": "Have feedback for me? Or interested in working with me on research, data science, artificial intelligence or even publishing an article on TDS? You can reach out to me on LinkedIn." }, { "code": null, "e": 28014, "s": 27998, "text": "www.linkedin.co" } ]
synchronized Keyword in Java
When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file. So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement − synchronized(objectidentifier) { // Access shared variables and other shared resources } Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where we will print a counter using two different threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads. Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces a different result based on CPU availability to a thread. Live Demo class PrintDemo { public void printCount() { try { for(int i = 5; i > 0; i--) { System.out.println("Counter --- " + i ); } } catch (Exception e) { System.out.println("Thread interrupted."); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; PrintDemo PD; ThreadDemo( String name, PrintDemo pd) { threadName = name; PD = pd; } public void run() { PD.printCount(); System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { PrintDemo PD = new PrintDemo(); ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD ); ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD ); T1.start(); T2.start(); // wait for threads to end try { T1.join(); T2.join(); } catch ( Exception e) { System.out.println("Interrupted"); } } } This produces a different result every time you run this program − Starting Thread - 1 Starting Thread - 2 Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 5 Counter --- 2 Counter --- 1 Counter --- 4 Thread Thread - 1 exiting. Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 2 exiting. Here is the same example which prints counter value in sequence and every time we run it, it produces the same result. Live Demo class PrintDemo { public void printCount() { try { for(int i = 5; i > 0; i--) { System.out.println("Counter --- " + i ); } } catch (Exception e) { System.out.println("Thread interrupted."); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; PrintDemo PD; ThreadDemo( String name, PrintDemo pd) { threadName = name; PD = pd; } public void run() { synchronized(PD) { PD.printCount(); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { PrintDemo PD = new PrintDemo(); ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD ); ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD ); T1.start(); T2.start(); // wait for threads to end try { T1.join(); T2.join(); } catch ( Exception e) { System.out.println("Interrupted"); } } } This produces the same result every time you run this program − Starting Thread - 1 Starting Thread - 2 Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 1 exiting. Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 2 exiting.
[ { "code": null, "e": 1517, "s": 1062, "text": "When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file." }, { "code": null, "e": 1861, "s": 1517, "text": "So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor." }, { "code": null, "e": 2099, "s": 1861, "text": "Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement −" }, { "code": null, "e": 2191, "s": 2099, "text": "synchronized(objectidentifier) {\n // Access shared variables and other shared resources\n}" }, { "code": null, "e": 2645, "s": 2191, "text": "Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where we will print a counter using two different threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads." }, { "code": null, "e": 2819, "s": 2645, "text": "Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces a different result based on CPU availability to a thread." }, { "code": null, "e": 2829, "s": 2819, "text": "Live Demo" }, { "code": null, "e": 4020, "s": 2829, "text": "class PrintDemo {\n public void printCount() {\n try {\n for(int i = 5; i > 0; i--) {\n System.out.println(\"Counter --- \" + i );\n }\n } catch (Exception e) {\n System.out.println(\"Thread interrupted.\");\n }\n }\n}\nclass ThreadDemo extends Thread {\n private Thread t;\n private String threadName;\n PrintDemo PD;\n\n ThreadDemo( String name, PrintDemo pd) {\n threadName = name;\n PD = pd;\n }\n\n public void run() {\n PD.printCount();\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n\n public void start () {\n System.out.println(\"Starting \" + threadName );\n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\n\npublic class TestThread {\n public static void main(String args[]) {\n PrintDemo PD = new PrintDemo();\n\n ThreadDemo T1 = new ThreadDemo( \"Thread - 1 \", PD );\n ThreadDemo T2 = new ThreadDemo( \"Thread - 2 \", PD );\n\n T1.start();\n T2.start();\n\n // wait for threads to end\n try {\n T1.join();\n T2.join();\n } catch ( Exception e) {\n System.out.println(\"Interrupted\");\n }\n }\n}" }, { "code": null, "e": 4087, "s": 4020, "text": "This produces a different result every time you run this program −" }, { "code": null, "e": 4321, "s": 4087, "text": "Starting Thread - 1\nStarting Thread - 2\nCounter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 5\nCounter --- 2\nCounter --- 1\nCounter --- 4\nThread Thread - 1 exiting.\nCounter --- 3\nCounter --- 2\nCounter --- 1\nThread Thread - 2 exiting." }, { "code": null, "e": 4440, "s": 4321, "text": "Here is the same example which prints counter value in sequence and every time we run it, it produces the same result." }, { "code": null, "e": 4450, "s": 4440, "text": "Live Demo" }, { "code": null, "e": 5679, "s": 4450, "text": "class PrintDemo {\n public void printCount() {\n try {\n for(int i = 5; i > 0; i--) {\n System.out.println(\"Counter --- \" + i );\n }\n } catch (Exception e) {\n System.out.println(\"Thread interrupted.\");\n }\n }\n}\n\nclass ThreadDemo extends Thread {\n private Thread t;\n private String threadName;\n PrintDemo PD;\n\n ThreadDemo( String name, PrintDemo pd) {\n threadName = name;\n PD = pd;\n }\n\n public void run() {\n synchronized(PD) {\n PD.printCount();\n }\n System.out.println(\"Thread \" + threadName + \" exiting.\");\n }\n\n public void start () {\n System.out.println(\"Starting \" + threadName );\n\n if (t == null) {\n t = new Thread (this, threadName);\n t.start ();\n }\n }\n}\n\npublic class TestThread {\n public static void main(String args[]) {\n PrintDemo PD = new PrintDemo();\n\n ThreadDemo T1 = new ThreadDemo( \"Thread - 1 \", PD );\n ThreadDemo T2 = new ThreadDemo( \"Thread - 2 \", PD );\n\n T1.start();\n T2.start();\n\n // wait for threads to end\n try {\n T1.join();\n T2.join();\n } catch ( Exception e) {\n System.out.println(\"Interrupted\");\n }\n }\n}" }, { "code": null, "e": 5743, "s": 5679, "text": "This produces the same result every time you run this program −" }, { "code": null, "e": 5977, "s": 5743, "text": "Starting Thread - 1\nStarting Thread - 2\nCounter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 2\nCounter --- 1\nThread Thread - 1 exiting.\nCounter --- 5\nCounter --- 4\nCounter --- 3\nCounter --- 2\nCounter --- 1\nThread Thread - 2 exiting." } ]
PyQt5 - Create a digital clock - GeeksforGeeks
22 Apr, 2020 In this article we will see how to create a digital clock using PyQt5, this digital clock will basically tells the current time in the 24 hour format. In order to create a digital clock we have to do the following: 1. Create a vertical layout2. Create label to show the current time and put it in the layout and align it to the center.3. Create a QTimer object4. Add action to the QTimer object such that after every 1sec action method get called.5. Inside the action method get the current time and show that time with the help of label. Below is the implementation – # importing required librarieimport sysfrom PyQt5.QtWidgets import QApplication, QWidgetfrom PyQt5.QtWidgets import QVBoxLayout, QLabelfrom PyQt5.QtGui import QFontfrom PyQt5.QtCore import QTimer, QTime, Qt class Window(QWidget): def __init__(self): super().__init__() # setting geometry of main window self.setGeometry(100, 100, 800, 400) # creating a vertical layout layout = QVBoxLayout() # creating font object font = QFont('Arial', 120, QFont.Bold) # creating a label object self.label = QLabel() # setting centre alignment to the label self.label.setAlignment(Qt.AlignCenter) # setting font to the label self.label.setFont(font) # adding label to the layout layout.addWidget(self.label) # setting the layout to main window self.setLayout(layout) # creating a timer object timer = QTimer(self) # adding action to timer timer.timeout.connect(self.showTime) # update the timer every second timer.start(1000) # method called by timer def showTime(self): # getting current time current_time = QTime.currentTime() # converting QTime object to string label_time = current_time.toString('hh:mm:ss') # showing it to the label self.label.setText(label_time) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # showing all the widgetswindow.show() # start the appApp.exit(App.exec_()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23753, "s": 23725, "text": "\n22 Apr, 2020" }, { "code": null, "e": 23904, "s": 23753, "text": "In this article we will see how to create a digital clock using PyQt5, this digital clock will basically tells the current time in the 24 hour format." }, { "code": null, "e": 23968, "s": 23904, "text": "In order to create a digital clock we have to do the following:" }, { "code": null, "e": 24292, "s": 23968, "text": "1. Create a vertical layout2. Create label to show the current time and put it in the layout and align it to the center.3. Create a QTimer object4. Add action to the QTimer object such that after every 1sec action method get called.5. Inside the action method get the current time and show that time with the help of label." }, { "code": null, "e": 24322, "s": 24292, "text": "Below is the implementation –" }, { "code": "# importing required librarieimport sysfrom PyQt5.QtWidgets import QApplication, QWidgetfrom PyQt5.QtWidgets import QVBoxLayout, QLabelfrom PyQt5.QtGui import QFontfrom PyQt5.QtCore import QTimer, QTime, Qt class Window(QWidget): def __init__(self): super().__init__() # setting geometry of main window self.setGeometry(100, 100, 800, 400) # creating a vertical layout layout = QVBoxLayout() # creating font object font = QFont('Arial', 120, QFont.Bold) # creating a label object self.label = QLabel() # setting centre alignment to the label self.label.setAlignment(Qt.AlignCenter) # setting font to the label self.label.setFont(font) # adding label to the layout layout.addWidget(self.label) # setting the layout to main window self.setLayout(layout) # creating a timer object timer = QTimer(self) # adding action to timer timer.timeout.connect(self.showTime) # update the timer every second timer.start(1000) # method called by timer def showTime(self): # getting current time current_time = QTime.currentTime() # converting QTime object to string label_time = current_time.toString('hh:mm:ss') # showing it to the label self.label.setText(label_time) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # showing all the widgetswindow.show() # start the appApp.exit(App.exec_())", "e": 25905, "s": 24322, "text": null }, { "code": null, "e": 25914, "s": 25905, "text": "Output :" }, { "code": null, "e": 25925, "s": 25914, "text": "Python-gui" }, { "code": null, "e": 25937, "s": 25925, "text": "Python-PyQt" }, { "code": null, "e": 25944, "s": 25937, "text": "Python" }, { "code": null, "e": 26042, "s": 25944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26051, "s": 26042, "text": "Comments" }, { "code": null, "e": 26064, "s": 26051, "text": "Old Comments" }, { "code": null, "e": 26082, "s": 26064, "text": "Python Dictionary" }, { "code": null, "e": 26117, "s": 26082, "text": "Read a file line by line in Python" }, { "code": null, "e": 26139, "s": 26117, "text": "Enumerate() in Python" }, { "code": null, "e": 26171, "s": 26139, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26201, "s": 26171, "text": "Iterate over a list in Python" }, { "code": null, "e": 26243, "s": 26201, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26286, "s": 26243, "text": "Python program to convert a list to string" }, { "code": null, "e": 26312, "s": 26286, "text": "Python String | replace()" }, { "code": null, "e": 26356, "s": 26312, "text": "Reading and Writing to text files in Python" } ]
Check whether HTML element has scrollbars using JavaScript - GeeksforGeeks
20 Sep, 2019 Given an HTML document and the task is to identify whether a particular element has scrollBars or not. There are two approaches to solve this problem which are discussed below: Approach 1: Select the particular element. Get the element.scrollWidth and .clientWidth property for horizontal scrollbar. Calculate the scrollWidth>clientWidth. If the value comes true then horizontal scrollbar is present else not. Do the same process to check vertical scrollbar. Example 1: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> Check whether HTML element has scrollbars using JavaScript </title> <style> #div { width:200px; height:150px; overflow:auto; text-align:justify; } #GFG { font-size: 24px; font-weight: bold; color: green; } </style></head> <body> <center> <h1 style = "color:green;" > GeeksforGeeks </h1> <h3> Click on the button to check for the scrollBars </h3> <div id="div"> This course is for all those people who want to learn Data Structures and Algorithm from basic to advance level. We don't expect you to have any prior knowledge on Data Structure and Algorithm, but a basic prior knowledge of any programming language ( C++ / Java) will be helpful. This course gives you the flexibility of learning, under this program you can study your course whenever you feel like, you need not hurry or puzzle yourself. </div> <br> <button onclick = "GFG_Fun()"> Click Here! </button> <div id = "GFG"></div> <script> function GFG_Fun() { var div = document.getElementById('div'); var hs = div.scrollWidth > div.clientWidth; var vs = div.scrollHeight > div.clientHeight; document.getElementById('GFG').innerHTML = "Horizontal Scrollbar - " + hs +"<br>Vertical Scrollbar - " + vs; } </script> </center></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Select the particular element. Use the scrollTop and scrollLeft properties. If these are greater than 0, scrollbars are present. If these are 0, then first set them to 1, and test again to know if getting a result of 1. Finally, set them back to 0. Example 2: This example using the approach discussed above. <!DOCTYPE HTML> <html> <head> <title> Check whether HTML element has scrollbars using JavaScript </title> <style> #div { width:200px; height:200px; overflow:none; text-align:justify; } #GFG { font-size: 24px; font-weight: bold; color: green; } </style></head> <body> <center> <h1 style = "color:green;" > GeeksforGeeks </h1> <h3> Click on the button to check for the scrollBars </h3> <div id="div"> This course is for all those people who want to learn Data Structures and Algorithm from basic to advance level. We don't expect you to have any prior knowledge on Data Structure and Algorithm, but a basic prior knowledge of any programming language ( C++ / Java) will be helpful. </div> <br> <button onclick = "GFG_Fun()"> Click Here! </button> <div id = "GFG"></div> <script> function checkScrollBar(element, dir) { dir = (dir === 'vertical') ? 'scrollTop' : 'scrollLeft'; var res = !! element[dir]; if (!res) { element[dir] = 1; res = !!element[dir]; element[dir] = 0; } return res; } function GFG_Fun() { var div = document.getElementById('div'); var hs = checkScrollBar(div, 'horizontal'); var vs = checkScrollBar(div, 'vertical'); document.getElementById('GFG').innerHTML = "Horizontal Scrollbar - " + hs +"<br>Vertical Scrollbar - " + vs; } </script> </center></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24705, "s": 24677, "text": "\n20 Sep, 2019" }, { "code": null, "e": 24882, "s": 24705, "text": "Given an HTML document and the task is to identify whether a particular element has scrollBars or not. There are two approaches to solve this problem which are discussed below:" }, { "code": null, "e": 24894, "s": 24882, "text": "Approach 1:" }, { "code": null, "e": 24925, "s": 24894, "text": "Select the particular element." }, { "code": null, "e": 25005, "s": 24925, "text": "Get the element.scrollWidth and .clientWidth property for horizontal scrollbar." }, { "code": null, "e": 25044, "s": 25005, "text": "Calculate the scrollWidth>clientWidth." }, { "code": null, "e": 25115, "s": 25044, "text": "If the value comes true then horizontal scrollbar is present else not." }, { "code": null, "e": 25164, "s": 25115, "text": "Do the same process to check vertical scrollbar." }, { "code": null, "e": 25219, "s": 25164, "text": "Example 1: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Check whether HTML element has scrollbars using JavaScript </title> <style> #div { width:200px; height:150px; overflow:auto; text-align:justify; } #GFG { font-size: 24px; font-weight: bold; color: green; } </style></head> <body> <center> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <h3> Click on the button to check for the scrollBars </h3> <div id=\"div\"> This course is for all those people who want to learn Data Structures and Algorithm from basic to advance level. We don't expect you to have any prior knowledge on Data Structure and Algorithm, but a basic prior knowledge of any programming language ( C++ / Java) will be helpful. This course gives you the flexibility of learning, under this program you can study your course whenever you feel like, you need not hurry or puzzle yourself. </div> <br> <button onclick = \"GFG_Fun()\"> Click Here! </button> <div id = \"GFG\"></div> <script> function GFG_Fun() { var div = document.getElementById('div'); var hs = div.scrollWidth > div.clientWidth; var vs = div.scrollHeight > div.clientHeight; document.getElementById('GFG').innerHTML = \"Horizontal Scrollbar - \" + hs +\"<br>Vertical Scrollbar - \" + vs; } </script> </center></body> </html>", "e": 27056, "s": 25219, "text": null }, { "code": null, "e": 27064, "s": 27056, "text": "Output:" }, { "code": null, "e": 27095, "s": 27064, "text": "Before clicking on the button:" }, { "code": null, "e": 27125, "s": 27095, "text": "After clicking on the button:" }, { "code": null, "e": 27137, "s": 27125, "text": "Approach 2:" }, { "code": null, "e": 27168, "s": 27137, "text": "Select the particular element." }, { "code": null, "e": 27213, "s": 27168, "text": "Use the scrollTop and scrollLeft properties." }, { "code": null, "e": 27266, "s": 27213, "text": "If these are greater than 0, scrollbars are present." }, { "code": null, "e": 27357, "s": 27266, "text": "If these are 0, then first set them to 1, and test again to know if getting a result of 1." }, { "code": null, "e": 27386, "s": 27357, "text": "Finally, set them back to 0." }, { "code": null, "e": 27446, "s": 27386, "text": "Example 2: This example using the approach discussed above." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Check whether HTML element has scrollbars using JavaScript </title> <style> #div { width:200px; height:200px; overflow:none; text-align:justify; } #GFG { font-size: 24px; font-weight: bold; color: green; } </style></head> <body> <center> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <h3> Click on the button to check for the scrollBars </h3> <div id=\"div\"> This course is for all those people who want to learn Data Structures and Algorithm from basic to advance level. We don't expect you to have any prior knowledge on Data Structure and Algorithm, but a basic prior knowledge of any programming language ( C++ / Java) will be helpful. </div> <br> <button onclick = \"GFG_Fun()\"> Click Here! </button> <div id = \"GFG\"></div> <script> function checkScrollBar(element, dir) { dir = (dir === 'vertical') ? 'scrollTop' : 'scrollLeft'; var res = !! element[dir]; if (!res) { element[dir] = 1; res = !!element[dir]; element[dir] = 0; } return res; } function GFG_Fun() { var div = document.getElementById('div'); var hs = checkScrollBar(div, 'horizontal'); var vs = checkScrollBar(div, 'vertical'); document.getElementById('GFG').innerHTML = \"Horizontal Scrollbar - \" + hs +\"<br>Vertical Scrollbar - \" + vs; } </script> </center></body> </html>", "e": 29528, "s": 27446, "text": null }, { "code": null, "e": 29536, "s": 29528, "text": "Output:" }, { "code": null, "e": 29567, "s": 29536, "text": "Before clicking on the button:" }, { "code": null, "e": 29597, "s": 29567, "text": "After clicking on the button:" }, { "code": null, "e": 29608, "s": 29597, "text": "JavaScript" }, { "code": null, "e": 29625, "s": 29608, "text": "Web Technologies" }, { "code": null, "e": 29652, "s": 29625, "text": "Web technologies Questions" }, { "code": null, "e": 29750, "s": 29652, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29759, "s": 29750, "text": "Comments" }, { "code": null, "e": 29772, "s": 29759, "text": "Old Comments" }, { "code": null, "e": 29833, "s": 29772, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29878, "s": 29833, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29950, "s": 29878, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30002, "s": 29950, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 30048, "s": 30002, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 30104, "s": 30048, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 30137, "s": 30104, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30199, "s": 30137, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30242, "s": 30199, "text": "How to fetch data from an API in ReactJS ?" } ]
Email OTP Verification using PHP in Live Server
07 Apr, 2022 The task is to create and design a sign-up and login form. In the sign-up form, the user will sign-up with a custom username and password and a valid email then the user will receive an OTP through the email, and after successful verification of OTP user account will be created and data will be stored in MySQL database, and then the user will be redirected to the home page. In the login form, the user can login with the username and password that the user entered while creating the new account. Note: We will implement this whole thing in a live server, anyone can implement this to their own local server like XAMPP, but the email verification part will not work in the local server. Approach for Sign-up Form: The first task is to create a MySQL server Database and a Table according to our requirements. We connect our MySQL server Database using PHP mysqli_connect() function that takes four arguments, i.e. our “servername”, “username”, “password” and “database”. After entering all the details of the user, we will generate a 6 digit random number using PHP rand() function and store it to the local session variable then send it to the user email using PHP mailer function. When the user enters the OTP, we will verify it with the OTP stored in session if these match then store redirect the user to the home page. Create a new table with the name as username the user provided to store the email and password of that user. Approach for Log-in Form: Connect to the database as described above, then check the credential provided by the user, if they match with the data stored in the database then redirect the user to the home page else show the related error. PHP code for registration form: register.php PHP <!DOCTYPE html><html lang="en"> <?php session_start(); $otp=$_SESSION["OTP"]; if(isset($_SESSION["logged-in"])){ header("Location:profile.php"); } $username="sign up"; $login_btn="Login"; if(isset($_SESSION["username"])){ $username=$_SESSION["username"]; $login_btn="Logout"; } if($_SERVER["REQUEST_METHOD"]=="POST"){ $con=mysqli_connect('localhost', 'database_username', 'database_pass','database_name'); if(!$con) echo ("failed to connect to database"); $username1=$_POST['username']; $prefix="_"; $username=$prefix.$username1; $password=$_POST['Password']; $repassword=$_POST['RePassword']; $email1=$_POST['Email']; $email=strval($email1); if($password!=$repassword){ echo("<script>alert('password not matches')</script>"); } else{ if(strlen($password)<8){ echo( "<script>alert('password length must be atleast 8')</script>"); } else{ $query="insert into 1_user(username,email,password) values('$username','$email','$password')"; $sql = "SELECT id,username, password FROM 1_user"; $result = $con->query($sql); $username_already_exist=false; $email_already_exist=false; // Checking if user already exist if(($result->num_rows)> 0){ while($row = $result->fetch_assoc()) { // echo "<br> id: " . $row["id"] . " - username= " . $row["username"] . " password= " . $row["password"] . "<br>"; if($row["username"]==$username){ $username_already_exist=true; break; } if($row["email"]==$email){ $email_already_exist=true; break; } } } // echo($ok); if($username_already_exist==false){ // This is my hosting mail $from ="[email protected]"; $to=$email; $subject="verify-account-otp"; // Generating otp with php rand variable $otp=rand(100000,999999); $message=strval($otp); $headers="From:" .$from; if(mail($to,$subject,$message,$headers)){ $_SESSION["username"]=$username; $_SESSION["OTP"]=$otp; $_SESSION["Email"]=$email; $_SESSION["Password"]=$password; $_SESSION["registration-going-on"]="1"; header("Location:verify-otp.php"); } else echo("mail send faild"); } else{ echo( "<script>alert('username already taken')</script>"); } } } }?> <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>Document</title> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <!-- adding bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> <div class="nav-bar"> <div class="title"> <h3>welcome to my website</h3> </div> </div></head> <body> <form class="form-register" action="register.php" method="POST"> <div class="form-group"> <label>username</label> <input type="text" class="form-control" name="username" id="username" aria-describedby="emailHelp" placeholder="username" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" name="Email" id="Email" placeholder="Email" required> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control" name="Password" id="Password" placeholder="Password" required> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control" name="RePassword" id="RePassword" placeholder="RePassword" required> </div> <button type="submit" class="btn btn-primary btn-lg"> Register </button> <button type="button" class="btn btn-warning btn-lg" id="login-button"> Already Registered </button> </form> <script> $("#login-button").click(function () { window.location.replace("index.php"); }); </script></body> </html> PHP code to send and verify OTP: verify-otp.php PHP <!DOCTYPE html><html lang="en"> <?php session_start(); // Retrieving otp with session variable $otp=$_SESSION["OTP"]; ?> <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>Document</title> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <!-- Adding bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> <div class="nav-bar"> <div class="title"> <h3>welcome to my website</h3> </div> </div></head> <body> <form class="form-login"> <div class="form-group"> <input type="text" class="form-control" name="otp" id="OTP" aria-describedby="emailHelp" placeholder="Enter OTP" required> </div> <button type="button" class="btn btn-primary btn-lg" id="verify-otp"> verify otp </button> </form> <script> $("#resend-otp").click(function () { window.location.replace("resend-otp.php"); }); $("#verify-otp").click(function () { // window.location.replace("index.php"); var otp1 = document.getElementById("OTP").value; // alert(otp1); var otp2 = ("<?php echo($otp)?>"); // alert(otp2); if (otp1 == otp2) { window.location.replace("logged-in.php"); } else { alert("otp not matches") } }); </script></body> </html> PHP code to resend OTP in case of OTP not received: resend-otp.php PHP <!DOCTYPE html><html lang="en"> <?php session_start(); // ini_set('dispaly_errors',1); // error_reporting(E_ALL); $from ="[email protected]"; $to=$_SESSION["Email"]; $subject="verify-account-otp"; $otp=rand(100000,999999); $message=strval($otp); $headers="From:" .$from; if(mail($to,$subject,$message,$headers)){ $_SESSION["OTP"]=$otp; header("Location:verify-otp.php"); } else echo("mail send faild");?> <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>Document</title> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <!-- Adding bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> <div class="nav-bar"> <div class="title"> <h3>welcome to coer library</h3> </div> </div></head> <body> <div class="form"> <form action="register.php" method="POST"> <label><b>Register To MY website</b></label> <hr class="first"> <label><b>Coer-ID</b></label> <input type="text" name="Coer-ID" placeholder="Coer-ID" required id="Coer-ID" class="float-left1"> <br><br> <label><b>Email</b></label> <input type="email" name="Email" placeholder="Email" required id="Email" class="float-left1"> <br><br> <label><b>Password </b> </label> <input type="Password" name="Password" placeholder="Password" required id="Password" class="float-left1"> <br><br> <label><b>RePassword </b> </label> <input type="Password" name="RePassword" placeholder=" Re Type Password" required id="Repassword" class="float-left1"> <br><br> <button type="submit" name="login" value="login" id="register-button"> create account </button> <br><br> </form> </div></body> </html> After successful OTP verification inserting user data to table 1_user: Table schema, each row has these 4 columns: id (int data type as primary key) username (text data type) email (text data type) password (text data type) PHP code for login form also the default page: index.php PHP <!DOCTYPE html><html lang="en"><?php $message= "logged in successfully...redirecting to home page"; session_start(); if(isset($_SESSION["logged_in"])){ header("Location:profile.php"); } if($_SERVER["REQUEST_METHOD"]=="POST"){ $con=mysqli_connect('localhost', 'database_username', 'database_pass','database_name'); if($con); else echo "failed to connect to database"; $username1=$_POST['username']; $prefix="_"; $username=$prefix.$username1; $password=$_POST['Password']; $sql = "SELECT id,username, password FROM 1_user"; $result = $con->query($sql); if ($result->num_rows > 0) { $fnd=0; while($row = $result->fetch_assoc()) { /* echo "<br> id: ". $row["id"]. " - username= ". $row["username"]. " password= " . $row["password"] . "<br>"; */ if($row["username"]==$username and $row["password"]==$password) { $_SESSION["username"] = $username; $_SESSION["registration-going-on"]="0"; $fnd=1; $_SESSION["logged_in"]="1"; echo '<div class="alert alert-success" role="alert">'.$message.'</div>'; echo"<script>setTimeout(\"location.href = 'profile.php';\",3000);</script>"; } } if($fnd==0) echo("<script>alert('username password not matches')</script>"); } else { echo("<script>alert('username password not matches')</script>"); } $con->close(); }?> <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>Document</title> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <!-- Adding bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> <div class="nav-bar"> <div class="title"> <h3>welcome to my website</h3> </div> </div></head> <body> <form class="form-login" action="index.php" method="POST"> <div class="form-group"> <label>username</label> <input type="text" class="form-control" name="username" id="username" aria-describedby="emailHelp" placeholder="username" required> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control" name="Password" id="Password" placeholder="Password" required> </div> <button type="submit" class="btn btn-primary btn-lg">Login </button> <button type="button" class="btn btn-warning btn-lg" id="register-button"> Create Account </button> </form> <script> $("#register-button").click(function () { window.location.replace("register.php"); }); </script></body> </html> PHP code of profile page: profile.php PHP <!DOCTYPE html><html lang="en"><?php session_start();?> <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>Document</title> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <!-- Adding bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> <div class="nav-bar"> <div class="title"> <h3>welcome to my website</h3> </div> </div></head> <body> <h1>welcome you are loggend in successfully</h1></body> </html> Output: ruhelaa48 adnanirshad158 anikakapoor anikaseth98 gabaa406 surindertarika1234 simmytarika5 avtarkumar719 sagartomar9927 PHP-function PHP-MySQL PHP-Questions PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2022" }, { "code": null, "e": 529, "s": 28, "text": "The task is to create and design a sign-up and login form. In the sign-up form, the user will sign-up with a custom username and password and a valid email then the user will receive an OTP through the email, and after successful verification of OTP user account will be created and data will be stored in MySQL database, and then the user will be redirected to the home page. In the login form, the user can login with the username and password that the user entered while creating the new account. " }, { "code": null, "e": 719, "s": 529, "text": "Note: We will implement this whole thing in a live server, anyone can implement this to their own local server like XAMPP, but the email verification part will not work in the local server." }, { "code": null, "e": 746, "s": 719, "text": "Approach for Sign-up Form:" }, { "code": null, "e": 841, "s": 746, "text": "The first task is to create a MySQL server Database and a Table according to our requirements." }, { "code": null, "e": 1003, "s": 841, "text": "We connect our MySQL server Database using PHP mysqli_connect() function that takes four arguments, i.e. our “servername”, “username”, “password” and “database”." }, { "code": null, "e": 1215, "s": 1003, "text": "After entering all the details of the user, we will generate a 6 digit random number using PHP rand() function and store it to the local session variable then send it to the user email using PHP mailer function." }, { "code": null, "e": 1356, "s": 1215, "text": "When the user enters the OTP, we will verify it with the OTP stored in session if these match then store redirect the user to the home page." }, { "code": null, "e": 1465, "s": 1356, "text": "Create a new table with the name as username the user provided to store the email and password of that user." }, { "code": null, "e": 1491, "s": 1465, "text": "Approach for Log-in Form:" }, { "code": null, "e": 1703, "s": 1491, "text": "Connect to the database as described above, then check the credential provided by the user, if they match with the data stored in the database then redirect the user to the home page else show the related error." }, { "code": null, "e": 1749, "s": 1703, "text": "PHP code for registration form: register.php " }, { "code": null, "e": 1753, "s": 1749, "text": "PHP" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <?php session_start(); $otp=$_SESSION[\"OTP\"]; if(isset($_SESSION[\"logged-in\"])){ header(\"Location:profile.php\"); } $username=\"sign up\"; $login_btn=\"Login\"; if(isset($_SESSION[\"username\"])){ $username=$_SESSION[\"username\"]; $login_btn=\"Logout\"; } if($_SERVER[\"REQUEST_METHOD\"]==\"POST\"){ $con=mysqli_connect('localhost', 'database_username', 'database_pass','database_name'); if(!$con) echo (\"failed to connect to database\"); $username1=$_POST['username']; $prefix=\"_\"; $username=$prefix.$username1; $password=$_POST['Password']; $repassword=$_POST['RePassword']; $email1=$_POST['Email']; $email=strval($email1); if($password!=$repassword){ echo(\"<script>alert('password not matches')</script>\"); } else{ if(strlen($password)<8){ echo( \"<script>alert('password length must be atleast 8')</script>\"); } else{ $query=\"insert into 1_user(username,email,password) values('$username','$email','$password')\"; $sql = \"SELECT id,username, password FROM 1_user\"; $result = $con->query($sql); $username_already_exist=false; $email_already_exist=false; // Checking if user already exist if(($result->num_rows)> 0){ while($row = $result->fetch_assoc()) { // echo \"<br> id: \" . $row[\"id\"] . \" - username= \" . $row[\"username\"] . \" password= \" . $row[\"password\"] . \"<br>\"; if($row[\"username\"]==$username){ $username_already_exist=true; break; } if($row[\"email\"]==$email){ $email_already_exist=true; break; } } } // echo($ok); if($username_already_exist==false){ // This is my hosting mail $from =\"[email protected]\"; $to=$email; $subject=\"verify-account-otp\"; // Generating otp with php rand variable $otp=rand(100000,999999); $message=strval($otp); $headers=\"From:\" .$from; if(mail($to,$subject,$message,$headers)){ $_SESSION[\"username\"]=$username; $_SESSION[\"OTP\"]=$otp; $_SESSION[\"Email\"]=$email; $_SESSION[\"Password\"]=$password; $_SESSION[\"registration-going-on\"]=\"1\"; header(\"Location:verify-otp.php\"); } else echo(\"mail send faild\"); } else{ echo( \"<script>alert('username already taken')</script>\"); } } } }?> <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>Document</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\" media=\"screen\" /> <!-- adding bootstrap --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> <div class=\"nav-bar\"> <div class=\"title\"> <h3>welcome to my website</h3> </div> </div></head> <body> <form class=\"form-register\" action=\"register.php\" method=\"POST\"> <div class=\"form-group\"> <label>username</label> <input type=\"text\" class=\"form-control\" name=\"username\" id=\"username\" aria-describedby=\"emailHelp\" placeholder=\"username\" required> </div> <div class=\"form-group\"> <label>Email</label> <input type=\"email\" class=\"form-control\" name=\"Email\" id=\"Email\" placeholder=\"Email\" required> </div> <div class=\"form-group\"> <label>Password</label> <input type=\"password\" class=\"form-control\" name=\"Password\" id=\"Password\" placeholder=\"Password\" required> </div> <div class=\"form-group\"> <label>Password</label> <input type=\"password\" class=\"form-control\" name=\"RePassword\" id=\"RePassword\" placeholder=\"RePassword\" required> </div> <button type=\"submit\" class=\"btn btn-primary btn-lg\"> Register </button> <button type=\"button\" class=\"btn btn-warning btn-lg\" id=\"login-button\"> Already Registered </button> </form> <script> $(\"#login-button\").click(function () { window.location.replace(\"index.php\"); }); </script></body> </html>", "e": 7780, "s": 1753, "text": null }, { "code": null, "e": 7828, "s": 7780, "text": "PHP code to send and verify OTP: verify-otp.php" }, { "code": null, "e": 7832, "s": 7828, "text": "PHP" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <?php session_start(); // Retrieving otp with session variable $otp=$_SESSION[\"OTP\"]; ?> <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>Document</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\" media=\"screen\" /> <!-- Adding bootstrap --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> <div class=\"nav-bar\"> <div class=\"title\"> <h3>welcome to my website</h3> </div> </div></head> <body> <form class=\"form-login\"> <div class=\"form-group\"> <input type=\"text\" class=\"form-control\" name=\"otp\" id=\"OTP\" aria-describedby=\"emailHelp\" placeholder=\"Enter OTP\" required> </div> <button type=\"button\" class=\"btn btn-primary btn-lg\" id=\"verify-otp\"> verify otp </button> </form> <script> $(\"#resend-otp\").click(function () { window.location.replace(\"resend-otp.php\"); }); $(\"#verify-otp\").click(function () { // window.location.replace(\"index.php\"); var otp1 = document.getElementById(\"OTP\").value; // alert(otp1); var otp2 = (\"<?php echo($otp)?>\"); // alert(otp2); if (otp1 == otp2) { window.location.replace(\"logged-in.php\"); } else { alert(\"otp not matches\") } }); </script></body> </html>", "e": 10336, "s": 7832, "text": null }, { "code": null, "e": 10403, "s": 10336, "text": "PHP code to resend OTP in case of OTP not received: resend-otp.php" }, { "code": null, "e": 10407, "s": 10403, "text": "PHP" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <?php session_start(); // ini_set('dispaly_errors',1); // error_reporting(E_ALL); $from =\"[email protected]\"; $to=$_SESSION[\"Email\"]; $subject=\"verify-account-otp\"; $otp=rand(100000,999999); $message=strval($otp); $headers=\"From:\" .$from; if(mail($to,$subject,$message,$headers)){ $_SESSION[\"OTP\"]=$otp; header(\"Location:verify-otp.php\"); } else echo(\"mail send faild\");?> <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>Document</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\" media=\"screen\" /> <!-- Adding bootstrap --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> <div class=\"nav-bar\"> <div class=\"title\"> <h3>welcome to coer library</h3> </div> </div></head> <body> <div class=\"form\"> <form action=\"register.php\" method=\"POST\"> <label><b>Register To MY website</b></label> <hr class=\"first\"> <label><b>Coer-ID</b></label> <input type=\"text\" name=\"Coer-ID\" placeholder=\"Coer-ID\" required id=\"Coer-ID\" class=\"float-left1\"> <br><br> <label><b>Email</b></label> <input type=\"email\" name=\"Email\" placeholder=\"Email\" required id=\"Email\" class=\"float-left1\"> <br><br> <label><b>Password </b> </label> <input type=\"Password\" name=\"Password\" placeholder=\"Password\" required id=\"Password\" class=\"float-left1\"> <br><br> <label><b>RePassword </b> </label> <input type=\"Password\" name=\"RePassword\" placeholder=\" Re Type Password\" required id=\"Repassword\" class=\"float-left1\"> <br><br> <button type=\"submit\" name=\"login\" value=\"login\" id=\"register-button\"> create account </button> <br><br> </form> </div></body> </html>", "e": 13453, "s": 10407, "text": null }, { "code": null, "e": 13524, "s": 13453, "text": "After successful OTP verification inserting user data to table 1_user:" }, { "code": null, "e": 13569, "s": 13524, "text": "Table schema, each row has these 4 columns: " }, { "code": null, "e": 13603, "s": 13569, "text": "id (int data type as primary key)" }, { "code": null, "e": 13629, "s": 13603, "text": "username (text data type)" }, { "code": null, "e": 13652, "s": 13629, "text": "email (text data type)" }, { "code": null, "e": 13679, "s": 13652, "text": "password (text data type) " }, { "code": null, "e": 13737, "s": 13679, "text": " PHP code for login form also the default page: index.php" }, { "code": null, "e": 13741, "s": 13737, "text": "PHP" }, { "code": "<!DOCTYPE html><html lang=\"en\"><?php $message= \"logged in successfully...redirecting to home page\"; session_start(); if(isset($_SESSION[\"logged_in\"])){ header(\"Location:profile.php\"); } if($_SERVER[\"REQUEST_METHOD\"]==\"POST\"){ $con=mysqli_connect('localhost', 'database_username', 'database_pass','database_name'); if($con); else echo \"failed to connect to database\"; $username1=$_POST['username']; $prefix=\"_\"; $username=$prefix.$username1; $password=$_POST['Password']; $sql = \"SELECT id,username, password FROM 1_user\"; $result = $con->query($sql); if ($result->num_rows > 0) { $fnd=0; while($row = $result->fetch_assoc()) { /* echo \"<br> id: \". $row[\"id\"]. \" - username= \". $row[\"username\"]. \" password= \" . $row[\"password\"] . \"<br>\"; */ if($row[\"username\"]==$username and $row[\"password\"]==$password) { $_SESSION[\"username\"] = $username; $_SESSION[\"registration-going-on\"]=\"0\"; $fnd=1; $_SESSION[\"logged_in\"]=\"1\"; echo '<div class=\"alert alert-success\" role=\"alert\">'.$message.'</div>'; echo\"<script>setTimeout(\\\"location.href = 'profile.php';\\\",3000);</script>\"; } } if($fnd==0) echo(\"<script>alert('username password not matches')</script>\"); } else { echo(\"<script>alert('username password not matches')</script>\"); } $con->close(); }?> <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>Document</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\" media=\"screen\" /> <!-- Adding bootstrap --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> <div class=\"nav-bar\"> <div class=\"title\"> <h3>welcome to my website</h3> </div> </div></head> <body> <form class=\"form-login\" action=\"index.php\" method=\"POST\"> <div class=\"form-group\"> <label>username</label> <input type=\"text\" class=\"form-control\" name=\"username\" id=\"username\" aria-describedby=\"emailHelp\" placeholder=\"username\" required> </div> <div class=\"form-group\"> <label>Password</label> <input type=\"password\" class=\"form-control\" name=\"Password\" id=\"Password\" placeholder=\"Password\" required> </div> <button type=\"submit\" class=\"btn btn-primary btn-lg\">Login </button> <button type=\"button\" class=\"btn btn-warning btn-lg\" id=\"register-button\"> Create Account </button> </form> <script> $(\"#register-button\").click(function () { window.location.replace(\"register.php\"); }); </script></body> </html>", "e": 17814, "s": 13741, "text": null }, { "code": null, "e": 17853, "s": 17814, "text": "PHP code of profile page: profile.php " }, { "code": null, "e": 17857, "s": 17853, "text": "PHP" }, { "code": "<!DOCTYPE html><html lang=\"en\"><?php session_start();?> <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>Document</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\" media=\"screen\" /> <!-- Adding bootstrap --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> <div class=\"nav-bar\"> <div class=\"title\"> <h3>welcome to my website</h3> </div> </div></head> <body> <h1>welcome you are loggend in successfully</h1></body> </html>", "e": 19325, "s": 17857, "text": null }, { "code": null, "e": 19333, "s": 19325, "text": "Output:" }, { "code": null, "e": 19343, "s": 19333, "text": "ruhelaa48" }, { "code": null, "e": 19358, "s": 19343, "text": "adnanirshad158" }, { "code": null, "e": 19370, "s": 19358, "text": "anikakapoor" }, { "code": null, "e": 19382, "s": 19370, "text": "anikaseth98" }, { "code": null, "e": 19391, "s": 19382, "text": "gabaa406" }, { "code": null, "e": 19410, "s": 19391, "text": "surindertarika1234" }, { "code": null, "e": 19423, "s": 19410, "text": "simmytarika5" }, { "code": null, "e": 19437, "s": 19423, "text": "avtarkumar719" }, { "code": null, "e": 19452, "s": 19437, "text": "sagartomar9927" }, { "code": null, "e": 19465, "s": 19452, "text": "PHP-function" }, { "code": null, "e": 19475, "s": 19465, "text": "PHP-MySQL" }, { "code": null, "e": 19489, "s": 19475, "text": "PHP-Questions" }, { "code": null, "e": 19493, "s": 19489, "text": "PHP" }, { "code": null, "e": 19510, "s": 19493, "text": "Web Technologies" }, { "code": null, "e": 19514, "s": 19510, "text": "PHP" } ]
How to write Regular Expressions?
08 Jul, 2016 A regular expression (sometimes called a rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace”-like operations.(Wikipedia). Regular expressions are a generalized way to match patterns with sequences of characters. It is used in every programming language like C++, Java and Python. What is a regular expression and what makes it so important?Regex are used in Google analytics in URL matching in supporting search and replace in most popular editors like Sublime, Notepad++, Brackets, Google Docs and Microsoft word. Example : Regular expression for an email address : ^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$ The above regular expression can be used for checking if a given set of characters is an email address or not. How to write regular expression? Repeaters : * , + and { } :These symbols act as repeaters and tell the computer that the preceding character is to be used for more than just one time. The asterisk symbol ( * ):It tells the computer to match the preceding character (or set of characters) for 0 or more times (upto infinite).Example : The regular expression ab*c will give ac, abc, abbc, abbbc....ans so on Example : The regular expression ab*c will give ac, abc, abbc, abbbc....ans so on The Plus symbol ( + ):It tells the computer to repeat the preceding character (or set of characters) for atleast one or more times(upto infinite).Example : The regular expression ab+c will give abc, abbc, abbc, ... and so on. Example : The regular expression ab+c will give abc, abbc, abbc, ... and so on. The curly braces {...}:It tells the computer to repeat the preceding character (or set of characters) for as many times as the value inside this bracket.Example : {2} means that the preceding character is to be repeated 2 times, {min,} means the preceding character is matches min or more times. {min,max} means that the preceding character is repeated at least min & at most max times. Example : {2} means that the preceding character is to be repeated 2 times, {min,} means the preceding character is matches min or more times. {min,max} means that the preceding character is repeated at least min & at most max times. Wildcard – ( . )The dot symbol can take place of any other symbol, that is why itis called the wildcard character.Example : The Regular expression .* will tell the computer that any character can be used any number of times. Example : The Regular expression .* will tell the computer that any character can be used any number of times. Optional character – ( ? )This symbol tells the computer that the preceding character mayor may not be present in the string to be matched.Example : We may write the format for document file as – “docx?” The ‘?’ tells the computer that x may or may not be present in the name of file format. Example : We may write the format for document file as – “docx?” The ‘?’ tells the computer that x may or may not be present in the name of file format. The caret ( ^ ) symbol: Setting position for match :tells the computer that the match must start at the beginning of the string or line.Example : ^\d{3} will match with patterns like "901" in "901-333-". Example : ^\d{3} will match with patterns like "901" in "901-333-". The dollar ( $ ) symbolIt tells the computer that the match must occur at the end of the string or before \n at the end of the line or string.Example : -\d{3}$ will match with patterns like "-333" in "-901-333". Example : -\d{3}$ will match with patterns like "-333" in "-901-333". Character ClassesA character class matches any one of a set of characters. It is used to match the most basic element of a language like a letter, a digit, space, a symbol etc./s : matches any whitespace characters such as space and tab/S : matches any non-whitespace characters/d : matches any digit character/D : matches any non-digit characters/w : matches any word character (basically alpha-numeric)/W : matches any non-word character/b : matches any word boundary (this would include spaces, dashes, commas, semi-colons, etc)[set_of_characters] – Matches any single character in set_of_characters. By default, the match is case-sensitive.Example : [abc] will match characters a,b and c in any string.[^set_of_characters] – Negation: Matches any single character that is not in set_of_characters. By default, the match is case sensitive.Example : [^abc] will match any character except a,b,c .[first-last] – Character range: Matches any single character in the range from first to last.Example : [a-zA-z] will match any character from a to z or A to Z. /s : matches any whitespace characters such as space and tab/S : matches any non-whitespace characters/d : matches any digit character/D : matches any non-digit characters/w : matches any word character (basically alpha-numeric)/W : matches any non-word character/b : matches any word boundary (this would include spaces, dashes, commas, semi-colons, etc) [set_of_characters] – Matches any single character in set_of_characters. By default, the match is case-sensitive. Example : [abc] will match characters a,b and c in any string. [^set_of_characters] – Negation: Matches any single character that is not in set_of_characters. By default, the match is case sensitive. Example : [^abc] will match any character except a,b,c . [first-last] – Character range: Matches any single character in the range from first to last. Example : [a-zA-z] will match any character from a to z or A to Z. The Escape Symbol : \If you want to match for the actual ‘+’, ‘.’ etc characters, add a backslash( \ ) before that character. This will tell the computer to treat the following character as a search character and consider it for matching pattern.Example : \d+[\+-x\*]\d+ will match patterns like "2+2" and "3*9" in "(2+2) * 3*9". If you want to match for the actual ‘+’, ‘.’ etc characters, add a backslash( \ ) before that character. This will tell the computer to treat the following character as a search character and consider it for matching pattern. Example : \d+[\+-x\*]\d+ will match patterns like "2+2" and "3*9" in "(2+2) * 3*9". Grouping Characters ( )A set of different symbols of a regular expression can be grouped together to act as a single unit and behave as a block, for this, you need to wrap the regular expression in the parenthesis( ).Example : ([A-Z]\w+) contains two different elements of the regular expression combined together. This expression will match any pattern containing uppercase letter followed by any character. A set of different symbols of a regular expression can be grouped together to act as a single unit and behave as a block, for this, you need to wrap the regular expression in the parenthesis( ). Example : ([A-Z]\w+) contains two different elements of the regular expression combined together. This expression will match any pattern containing uppercase letter followed by any character. Vertical Bar ( | ) :Matches any one element separated by the vertical bar (|) character.Example : th(e|is|at) will match words - the, this and that. Vertical Bar ( | ) :Matches any one element separated by the vertical bar (|) character. Example : th(e|is|at) will match words - the, this and that. \number :Backreference: allows a previously matched sub-expression(expression captured or enclosed within circular brackets ) to be identified subsequently in the same regular expression. \n means that group enclosed within the n-th bracket will be repeated at current position.Example : ([a-z])\1 will match “ee” in Geek because the character at second position is same as character at position 1 of the match. Example : ([a-z])\1 will match “ee” in Geek because the character at second position is same as character at position 1 of the match. Comment : (?# comment) –Inline comment: The comment ends at the first closing parenthesis.Example : \bA(?#This is an inline comment)\w+\b# [to end of line] : X-mode comment. The comment starts at an unescaped # and continues to the end of the line.Example : (?x)\bA\w+\b#Matches words starting with A Example : \bA(?#This is an inline comment)\w+\b # [to end of line] : X-mode comment. The comment starts at an unescaped # and continues to the end of the line. Example : (?x)\bA\w+\b#Matches words starting with A This article is contributed by Abhinav Tiwari .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. Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2016" }, { "code": null, "e": 296, "s": 54, "text": "A regular expression (sometimes called a rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace”-like operations.(Wikipedia)." }, { "code": null, "e": 454, "s": 296, "text": "Regular expressions are a generalized way to match patterns with sequences of characters. It is used in every programming language like C++, Java and Python." }, { "code": null, "e": 689, "s": 454, "text": "What is a regular expression and what makes it so important?Regex are used in Google analytics in URL matching in supporting search and replace in most popular editors like Sublime, Notepad++, Brackets, Google Docs and Microsoft word." }, { "code": null, "e": 803, "s": 689, "text": "Example : Regular expression for an email address :\n^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$ \n" }, { "code": null, "e": 914, "s": 803, "text": "The above regular expression can be used for checking if a given set of characters is an email address or not." }, { "code": null, "e": 947, "s": 914, "text": "How to write regular expression?" }, { "code": null, "e": 1099, "s": 947, "text": "Repeaters : * , + and { } :These symbols act as repeaters and tell the computer that the preceding character is to be used for more than just one time." }, { "code": null, "e": 1323, "s": 1099, "text": "The asterisk symbol ( * ):It tells the computer to match the preceding character (or set of characters) for 0 or more times (upto infinite).Example : The regular expression ab*c will give ac, abc, abbc, \nabbbc....ans so on " }, { "code": null, "e": 1407, "s": 1323, "text": "Example : The regular expression ab*c will give ac, abc, abbc, \nabbbc....ans so on " }, { "code": null, "e": 1633, "s": 1407, "text": "The Plus symbol ( + ):It tells the computer to repeat the preceding character (or set of characters) for atleast one or more times(upto infinite).Example : The regular expression ab+c will give abc, abbc,\nabbc, ... and so on." }, { "code": null, "e": 1713, "s": 1633, "text": "Example : The regular expression ab+c will give abc, abbc,\nabbc, ... and so on." }, { "code": null, "e": 2104, "s": 1713, "text": "The curly braces {...}:It tells the computer to repeat the preceding character (or set of characters) for as many times as the value inside this bracket.Example : {2} means that the preceding character is to be repeated 2 \ntimes, {min,} means the preceding character is matches min or more \ntimes. {min,max} means that the preceding character is repeated at\nleast min & at most max times.\n" }, { "code": null, "e": 2342, "s": 2104, "text": "Example : {2} means that the preceding character is to be repeated 2 \ntimes, {min,} means the preceding character is matches min or more \ntimes. {min,max} means that the preceding character is repeated at\nleast min & at most max times.\n" }, { "code": null, "e": 2568, "s": 2342, "text": "Wildcard – ( . )The dot symbol can take place of any other symbol, that is why itis called the wildcard character.Example : \nThe Regular expression .* will tell the computer that any character\ncan be used any number of times." }, { "code": null, "e": 2680, "s": 2568, "text": "Example : \nThe Regular expression .* will tell the computer that any character\ncan be used any number of times." }, { "code": null, "e": 2974, "s": 2680, "text": "Optional character – ( ? )This symbol tells the computer that the preceding character mayor may not be present in the string to be matched.Example : \nWe may write the format for document file as – “docx?”\nThe ‘?’ tells the computer that x may or may not be \npresent in the name of file format." }, { "code": null, "e": 3129, "s": 2974, "text": "Example : \nWe may write the format for document file as – “docx?”\nThe ‘?’ tells the computer that x may or may not be \npresent in the name of file format." }, { "code": null, "e": 3333, "s": 3129, "text": "The caret ( ^ ) symbol: Setting position for match :tells the computer that the match must start at the beginning of the string or line.Example : ^\\d{3} will match with patterns like \"901\" in \"901-333-\"." }, { "code": null, "e": 3401, "s": 3333, "text": "Example : ^\\d{3} will match with patterns like \"901\" in \"901-333-\"." }, { "code": null, "e": 3614, "s": 3401, "text": "The dollar ( $ ) symbolIt tells the computer that the match must occur at the end of the string or before \\n at the end of the line or string.Example : -\\d{3}$ will match with patterns like \"-333\" in \"-901-333\"." }, { "code": null, "e": 3685, "s": 3614, "text": "Example : -\\d{3}$ will match with patterns like \"-333\" in \"-901-333\"." }, { "code": null, "e": 4743, "s": 3685, "text": "Character ClassesA character class matches any one of a set of characters. It is used to match the most basic element of a language like a letter, a digit, space, a symbol etc./s : matches any whitespace characters such as space and tab/S : matches any non-whitespace characters/d : matches any digit character/D : matches any non-digit characters/w : matches any word character (basically alpha-numeric)/W : matches any non-word character/b : matches any word boundary (this would include spaces, dashes, commas, semi-colons, etc)[set_of_characters] – Matches any single character in set_of_characters. By default, the match is case-sensitive.Example : [abc] will match characters a,b and c in any string.[^set_of_characters] – Negation: Matches any single character that is not in set_of_characters. By default, the match is case sensitive.Example : [^abc] will match any character except a,b,c .[first-last] – Character range: Matches any single character in the range from first to last.Example : [a-zA-z] will match any character from a to z or A to Z." }, { "code": null, "e": 5099, "s": 4743, "text": "/s : matches any whitespace characters such as space and tab/S : matches any non-whitespace characters/d : matches any digit character/D : matches any non-digit characters/w : matches any word character (basically alpha-numeric)/W : matches any non-word character/b : matches any word boundary (this would include spaces, dashes, commas, semi-colons, etc)" }, { "code": null, "e": 5213, "s": 5099, "text": "[set_of_characters] – Matches any single character in set_of_characters. By default, the match is case-sensitive." }, { "code": null, "e": 5276, "s": 5213, "text": "Example : [abc] will match characters a,b and c in any string." }, { "code": null, "e": 5413, "s": 5276, "text": "[^set_of_characters] – Negation: Matches any single character that is not in set_of_characters. By default, the match is case sensitive." }, { "code": null, "e": 5470, "s": 5413, "text": "Example : [^abc] will match any character except a,b,c ." }, { "code": null, "e": 5564, "s": 5470, "text": "[first-last] – Character range: Matches any single character in the range from first to last." }, { "code": null, "e": 5631, "s": 5564, "text": "Example : [a-zA-z] will match any character from a to z or A to Z." }, { "code": null, "e": 5961, "s": 5631, "text": "The Escape Symbol : \\If you want to match for the actual ‘+’, ‘.’ etc characters, add a backslash( \\ ) before that character. This will tell the computer to treat the following character as a search character and consider it for matching pattern.Example : \\d+[\\+-x\\*]\\d+ will match patterns like \"2+2\"\nand \"3*9\" in \"(2+2) * 3*9\"." }, { "code": null, "e": 6187, "s": 5961, "text": "If you want to match for the actual ‘+’, ‘.’ etc characters, add a backslash( \\ ) before that character. This will tell the computer to treat the following character as a search character and consider it for matching pattern." }, { "code": null, "e": 6271, "s": 6187, "text": "Example : \\d+[\\+-x\\*]\\d+ will match patterns like \"2+2\"\nand \"3*9\" in \"(2+2) * 3*9\"." }, { "code": null, "e": 6682, "s": 6271, "text": "Grouping Characters ( )A set of different symbols of a regular expression can be grouped together to act as a single unit and behave as a block, for this, you need to wrap the regular expression in the parenthesis( ).Example : ([A-Z]\\w+) contains two different elements of the regular \nexpression combined together. This expression will match any pattern \ncontaining uppercase letter followed by any character." }, { "code": null, "e": 6877, "s": 6682, "text": "A set of different symbols of a regular expression can be grouped together to act as a single unit and behave as a block, for this, you need to wrap the regular expression in the parenthesis( )." }, { "code": null, "e": 7071, "s": 6877, "text": "Example : ([A-Z]\\w+) contains two different elements of the regular \nexpression combined together. This expression will match any pattern \ncontaining uppercase letter followed by any character." }, { "code": null, "e": 7221, "s": 7071, "text": "Vertical Bar ( | ) :Matches any one element separated by the vertical bar (|) character.Example : th(e|is|at) will match words - the, this and that." }, { "code": null, "e": 7310, "s": 7221, "text": "Vertical Bar ( | ) :Matches any one element separated by the vertical bar (|) character." }, { "code": null, "e": 7372, "s": 7310, "text": "Example : th(e|is|at) will match words - the, this and that." }, { "code": null, "e": 7785, "s": 7372, "text": "\\number :Backreference: allows a previously matched sub-expression(expression captured or enclosed within circular brackets ) to be identified subsequently in the same regular expression. \\n means that group enclosed within the n-th bracket will be repeated at current position.Example : ([a-z])\\1 will match “ee” in Geek because the character \nat second position is same as character at position 1 of the match." }, { "code": null, "e": 7920, "s": 7785, "text": "Example : ([a-z])\\1 will match “ee” in Geek because the character \nat second position is same as character at position 1 of the match." }, { "code": null, "e": 8222, "s": 7920, "text": "Comment : (?# comment) –Inline comment: The comment ends at the first closing parenthesis.Example : \\bA(?#This is an inline comment)\\w+\\b# [to end of line] : X-mode comment. The comment starts at an unescaped # and continues to the end of the line.Example : (?x)\\bA\\w+\\b#Matches words starting with A" }, { "code": null, "e": 8270, "s": 8222, "text": "Example : \\bA(?#This is an inline comment)\\w+\\b" }, { "code": null, "e": 8382, "s": 8270, "text": "# [to end of line] : X-mode comment. The comment starts at an unescaped # and continues to the end of the line." }, { "code": null, "e": 8436, "s": 8382, "text": "Example : (?x)\\bA\\w+\\b#Matches words starting with A" }, { "code": null, "e": 8738, "s": 8436, "text": "This article is contributed by Abhinav Tiwari .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": 8863, "s": 8738, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8868, "s": 8863, "text": "Misc" }, { "code": null, "e": 8873, "s": 8868, "text": "Misc" }, { "code": null, "e": 8878, "s": 8873, "text": "Misc" } ]
Virtual LAN (VLAN)
21 Oct, 2021 Virtual LAN (VLAN) is a concept in which we can divide the devices logically on layer 2 (data link layer). Generally, layer 3 devices divide broadcast domain but broadcast domain can be divided by switches using the concept of VLAN. A broadcast domain is a network segment in which if a device broadcast a packet then all the devices in the same broadcast domain will receive it. The devices in the same broadcast domain will receive all the broadcast packets but it is limited to switches only as routers don’t forward out the broadcast packet. To forward out the packets to different VLAN (from one VLAN to another) or broadcast domain, inter Vlan routing is needed. Through VLAN, different small-size sub-networks are created which are comparatively easy to handle. VLAN ranges – VLAN 0, 4095: These are reserved VLAN which cannot be seen or used. VLAN 1: It is the default VLAN of switches. By default, all switch ports are in VLAN. This VLAN can’t be deleted or edit but can be used. VLAN 2-1001: This is a normal VLAN range. We can create, edit and delete these VLAN. VLAN 1002-1005: These are CISCO defaults for fddi and token rings. These VLAN can’t be deleted. Vlan 1006-4094: This is the extended range of Vlan. Configuration – We can simply create VLANs by simply assigning the vlan-id and Vlan name. #switch1(config)#vlan 2 #switch1(config-vlan)#vlan accounts Here, 2 is the Vlan I’d and accounts is the Vlan name. Now, we assign Vlan to the switch ports.e.g- Switch(config)#int fa0/0 Switch(config-if)#switchport mode access Switch(config-if)#switchport access Vlan 2 Also, switchport range can be assigned to required vlans. Switch(config)#int range fa0/0-2 Switch(config-if)#switchport mode access Switch(config-if) #switchport access Vlan 2 By this, switchport fa0/0, fa0/1, fa0-2 will be assigned Vlan 2. Example – Assigning IP address 192.168.1.1/24, 192.168.1.2/24 and 192.168.2.1/24 to the PC’s. Now, we will create Vlan 2 and 3 on switch. Switch(config)#vlan 2 Switch(config)#vlan 3 We have made VLANs but the most important part is to assign switch ports to the VLANs. Switch(config)#int fa0/0 Switch(config-if)#switchport mode access Switch(config-if) #switchport access Vlan 2 Switch(config)#int fa0/1 Switch(config-if)#switchport mode access Switch(config-if) #switchport access Vlan 3 Switch(config)#int fa0/2 Switch(config-if)#switchport mode access Switch(config-if) #switchport access Vlan 2 As seen, we have assigned Vlan 2 to fa0/0, fa0/2, and Vlan 3 to fa0/1. Types of connections in VLAN – There are three ways to connect devices on a VLAN, the type of connections are based on the connected devices i.e. whether they are VLAN-aware(A device that understands VLAN formats and VLAN membership) or VLAN-unaware(A device that doesn’t understand VLAN format and VLAN membership). Trunk Link –All connected devices to a trunk link must be VLAN-aware. All frames on this should have a special header attached to it called tagged frames.Access link –It connects VLAN-unaware devices to a VLAN-aware bridge. All frames on the access link must be untagged.Hybrid link –It is a combination of the Trunk link and Access link. Here both VLAN-unaware and VLAN-aware devices are attached and it can have both tagged and untagged frames. Trunk Link –All connected devices to a trunk link must be VLAN-aware. All frames on this should have a special header attached to it called tagged frames. Access link –It connects VLAN-unaware devices to a VLAN-aware bridge. All frames on the access link must be untagged. Hybrid link –It is a combination of the Trunk link and Access link. Here both VLAN-unaware and VLAN-aware devices are attached and it can have both tagged and untagged frames. Advantages – Performance –The network traffic is full of broadcast and multicast. VLAN reduces the need to send such traffic to unnecessary destinations. e.g.-If the traffic is intended for 2 users but as 10 devices are present in the same broadcast domain, therefore, all will receive the traffic i.e. wastage of bandwidth but if we make VLANs, then the broadcast or multicast packet will go to the intended users only. Formation of virtual groups –As there are different departments in every organization namely sales, finance etc., VLANs can be very useful in order to group the devices logically according to their departments. Security – In the same network, sensitive data can be broadcast which can be accessed by the outsider but by creating VLAN, we can control broadcast domains, set up firewalls, restrict access. Also, VLANs can be used to inform the network manager of an intrusion. Hence, VLANs greatly enhance network security. Flexibility –VLAN provide flexibility to add, remove the number of host we want. Cost reduction –VLANs can be used to create broadcast domains which eliminate the need for expensive routers.By using Vlan, the number of small size broadcast domain can be increased which are easy to handle as compared to a bigger broadcast domain. saurabhsharma56 vivekpal23123451254 23620uday2021 kmbh Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) User Datagram Protocol (UDP) Introduction of Mobile Ad hoc Network (MANET) Advanced Encryption Standard (AES) Bluetooth Types of area networks - LAN, MAN and WAN
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Oct, 2021" }, { "code": null, "e": 286, "s": 52, "text": "Virtual LAN (VLAN) is a concept in which we can divide the devices logically on layer 2 (data link layer). Generally, layer 3 devices divide broadcast domain but broadcast domain can be divided by switches using the concept of VLAN. " }, { "code": null, "e": 823, "s": 286, "text": "A broadcast domain is a network segment in which if a device broadcast a packet then all the devices in the same broadcast domain will receive it. The devices in the same broadcast domain will receive all the broadcast packets but it is limited to switches only as routers don’t forward out the broadcast packet. To forward out the packets to different VLAN (from one VLAN to another) or broadcast domain, inter Vlan routing is needed. Through VLAN, different small-size sub-networks are created which are comparatively easy to handle. " }, { "code": null, "e": 838, "s": 823, "text": "VLAN ranges – " }, { "code": null, "e": 906, "s": 838, "text": "VLAN 0, 4095: These are reserved VLAN which cannot be seen or used." }, { "code": null, "e": 1044, "s": 906, "text": "VLAN 1: It is the default VLAN of switches. By default, all switch ports are in VLAN. This VLAN can’t be deleted or edit but can be used." }, { "code": null, "e": 1129, "s": 1044, "text": "VLAN 2-1001: This is a normal VLAN range. We can create, edit and delete these VLAN." }, { "code": null, "e": 1225, "s": 1129, "text": "VLAN 1002-1005: These are CISCO defaults for fddi and token rings. These VLAN can’t be deleted." }, { "code": null, "e": 1277, "s": 1225, "text": "Vlan 1006-4094: This is the extended range of Vlan." }, { "code": null, "e": 1368, "s": 1277, "text": "Configuration – We can simply create VLANs by simply assigning the vlan-id and Vlan name. " }, { "code": null, "e": 1428, "s": 1368, "text": "#switch1(config)#vlan 2\n#switch1(config-vlan)#vlan accounts" }, { "code": null, "e": 1529, "s": 1428, "text": "Here, 2 is the Vlan I’d and accounts is the Vlan name. Now, we assign Vlan to the switch ports.e.g- " }, { "code": null, "e": 1638, "s": 1529, "text": "Switch(config)#int fa0/0\nSwitch(config-if)#switchport mode access\nSwitch(config-if)#switchport access Vlan 2" }, { "code": null, "e": 1698, "s": 1638, "text": "Also, switchport range can be assigned to required vlans. " }, { "code": null, "e": 1816, "s": 1698, "text": "Switch(config)#int range fa0/0-2\nSwitch(config-if)#switchport mode access\nSwitch(config-if) #switchport access Vlan 2" }, { "code": null, "e": 1882, "s": 1816, "text": "By this, switchport fa0/0, fa0/1, fa0-2 will be assigned Vlan 2. " }, { "code": null, "e": 1893, "s": 1882, "text": "Example – " }, { "code": null, "e": 2022, "s": 1893, "text": "Assigning IP address 192.168.1.1/24, 192.168.1.2/24 and 192.168.2.1/24 to the PC’s. Now, we will create Vlan 2 and 3 on switch. " }, { "code": null, "e": 2066, "s": 2022, "text": "Switch(config)#vlan 2\nSwitch(config)#vlan 3" }, { "code": null, "e": 2155, "s": 2066, "text": "We have made VLANs but the most important part is to assign switch ports to the VLANs. " }, { "code": null, "e": 2488, "s": 2155, "text": "Switch(config)#int fa0/0\nSwitch(config-if)#switchport mode access\nSwitch(config-if) #switchport access Vlan 2\n\nSwitch(config)#int fa0/1\nSwitch(config-if)#switchport mode access\nSwitch(config-if) #switchport access Vlan 3\n\nSwitch(config)#int fa0/2\nSwitch(config-if)#switchport mode access\nSwitch(config-if) #switchport access Vlan 2 " }, { "code": null, "e": 2560, "s": 2488, "text": "As seen, we have assigned Vlan 2 to fa0/0, fa0/2, and Vlan 3 to fa0/1. " }, { "code": null, "e": 2591, "s": 2560, "text": "Types of connections in VLAN –" }, { "code": null, "e": 2877, "s": 2591, "text": "There are three ways to connect devices on a VLAN, the type of connections are based on the connected devices i.e. whether they are VLAN-aware(A device that understands VLAN formats and VLAN membership) or VLAN-unaware(A device that doesn’t understand VLAN format and VLAN membership)." }, { "code": null, "e": 3324, "s": 2877, "text": "Trunk Link –All connected devices to a trunk link must be VLAN-aware. All frames on this should have a special header attached to it called tagged frames.Access link –It connects VLAN-unaware devices to a VLAN-aware bridge. All frames on the access link must be untagged.Hybrid link –It is a combination of the Trunk link and Access link. Here both VLAN-unaware and VLAN-aware devices are attached and it can have both tagged and untagged frames." }, { "code": null, "e": 3479, "s": 3324, "text": "Trunk Link –All connected devices to a trunk link must be VLAN-aware. All frames on this should have a special header attached to it called tagged frames." }, { "code": null, "e": 3597, "s": 3479, "text": "Access link –It connects VLAN-unaware devices to a VLAN-aware bridge. All frames on the access link must be untagged." }, { "code": null, "e": 3773, "s": 3597, "text": "Hybrid link –It is a combination of the Trunk link and Access link. Here both VLAN-unaware and VLAN-aware devices are attached and it can have both tagged and untagged frames." }, { "code": null, "e": 3787, "s": 3773, "text": "Advantages – " }, { "code": null, "e": 4195, "s": 3787, "text": "Performance –The network traffic is full of broadcast and multicast. VLAN reduces the need to send such traffic to unnecessary destinations. e.g.-If the traffic is intended for 2 users but as 10 devices are present in the same broadcast domain, therefore, all will receive the traffic i.e. wastage of bandwidth but if we make VLANs, then the broadcast or multicast packet will go to the intended users only." }, { "code": null, "e": 4406, "s": 4195, "text": "Formation of virtual groups –As there are different departments in every organization namely sales, finance etc., VLANs can be very useful in order to group the devices logically according to their departments." }, { "code": null, "e": 4717, "s": 4406, "text": "Security – In the same network, sensitive data can be broadcast which can be accessed by the outsider but by creating VLAN, we can control broadcast domains, set up firewalls, restrict access. Also, VLANs can be used to inform the network manager of an intrusion. Hence, VLANs greatly enhance network security." }, { "code": null, "e": 4798, "s": 4717, "text": "Flexibility –VLAN provide flexibility to add, remove the number of host we want." }, { "code": null, "e": 5048, "s": 4798, "text": "Cost reduction –VLANs can be used to create broadcast domains which eliminate the need for expensive routers.By using Vlan, the number of small size broadcast domain can be increased which are easy to handle as compared to a bigger broadcast domain." }, { "code": null, "e": 5066, "s": 5050, "text": "saurabhsharma56" }, { "code": null, "e": 5086, "s": 5066, "text": "vivekpal23123451254" }, { "code": null, "e": 5100, "s": 5086, "text": "23620uday2021" }, { "code": null, "e": 5105, "s": 5100, "text": "kmbh" }, { "code": null, "e": 5123, "s": 5105, "text": "Computer Networks" }, { "code": null, "e": 5141, "s": 5123, "text": "Computer Networks" }, { "code": null, "e": 5239, "s": 5141, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5269, "s": 5239, "text": "GSM in Wireless Communication" }, { "code": null, "e": 5303, "s": 5269, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 5329, "s": 5303, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 5359, "s": 5329, "text": "Wireless Application Protocol" }, { "code": null, "e": 5399, "s": 5359, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 5428, "s": 5399, "text": "User Datagram Protocol (UDP)" }, { "code": null, "e": 5474, "s": 5428, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 5509, "s": 5474, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 5519, "s": 5509, "text": "Bluetooth" } ]
Min flips of continuous characters to make all characters same in a string
05 Nov, 2021 Given a string consisting only of 1’s and 0’s. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: Input : 00011110001110 Output : 2 We need to convert 1's sequence so string consist of all 0's. Input : 010101100011 Output : 4 We need to find the min flips in string so all characters are equal. All we have to find numbers of sequence which consisting of 0’s or 1’s only. Then number of flips required will be half of this number as we can change all 0’s or all 1’s. C++ Java Python 3 C# PHP Javascript // CPP program to find min flips in binary// string to make all characters equal#include <bits/stdc++.h>using namespace std; // To find min number of flips in binary stringint findFlips(char str[], int n){ char last = ' '; int res = 0; for (int i = 0; i < n; i++) { // If last character is not equal // to str[i] increase res if (last != str[i]) res++; last = str[i]; } // To return min flips return res / 2;} // Driver program to check findFlips()int main(){ char str[] = "00011110001110"; int n = strlen(str); cout << findFlips(str, n); return 0;} // Java program to find min flips in binary// string to make all characters equalpublic class minFlips { // To find min number of flips in binary string static int findFlips(String str, int n) { char last = ' '; int res = 0; for (int i = 0; i < n; i++) { // If last character is not equal // to str[i] increase res if (last != str.charAt(i)) res++; last = str.charAt(i); } // To return min flips return res / 2; } // Driver program to check findFlips() public static void main(String[] args) { String str = "00011110001110"; int n = str.length(); System.out.println(findFlips(str, n)); }} # Python 3 program to find min flips in# binary string to make all characters equal # To find min number of flips in# binary stringdef findFlips(str, n): last = ' ' res = 0 for i in range( n) : # If last character is not equal # to str[i] increase res if (last != str[i]): res += 1 last = str[i] # To return min flips return res // 2 # Driver Codeif __name__ == "__main__": str = "00011110001110" n = len(str) print(findFlips(str, n)) # This code is contributed by ita_c // C# program to find min flips in// binary string to make all// characters equalusing System; public class GFG { // To find min number of flips // in binary string static int findFlips(String str, int n) { char last = ' '; int res = 0; for (int i = 0; i < n; i++) { // If last character is not // equal to str[i] increase // res if (last != str[i]) res++; last = str[i]; } // To return min flips return res / 2; } // Driver program to check findFlips() public static void Main() { String str = "00011110001110"; int n = str.Length; Console.Write(findFlips(str, n)); }} // This code is contributed by nitin mittal <?php// PHP program to find min flips in binary// string to make all characters equal // To find min number of// flips in binary stringfunction findFlips($str, $n){ $last = ' '; $res = 0; for ($i = 0; $i < $n; $i++) { // If last character is not equal // to str[i] increase res if ($last != $str[$i]) $res++; $last = $str[$i]; } // To return min flips return intval($res / 2);} // Driver Code $str = "00011110001110"; $n = strlen($str); echo findFlips($str, $n); // This code is contributed by Sam007?> <script> // JavaScript program to find min flips in binary// string to make all characters equal // To find min number of flips in binary string function findFlips( str , n) { var last = ' '; var res = 0; for (i = 0; i < n; i++) { // If last character is not equal // to str[i] increase res if (last != str.charAt(i)) res++; last = str.charAt(i); } // To return min flips return parseInt(res / 2); } // Driver program to check findFlips() var str = "00011110001110"; var n = str.length; document.write(findFlips(str, n)); // This code contributed by aashish1995 </script> Time Complexity: O(n) Auxiliary Space: O(1) Output: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. 2 Minimum flips of continuous characters to make all same in a binary string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMinimum flips of continuous characters to make all same in a binary string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ZYqT5pDnQt8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Sam007 ukasp aashish1995 rohitsingh07052 binary-string Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Length of the longest substring without repeating characters Convert string to char array in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Nov, 2021" }, { "code": null, "e": 257, "s": 52, "text": "Given a string consisting only of 1’s and 0’s. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: " }, { "code": null, "e": 386, "s": 257, "text": "Input : 00011110001110\nOutput : 2\nWe need to convert 1's sequence\nso string consist of all 0's.\n\nInput : 010101100011\nOutput : 4" }, { "code": null, "e": 630, "s": 388, "text": "We need to find the min flips in string so all characters are equal. All we have to find numbers of sequence which consisting of 0’s or 1’s only. Then number of flips required will be half of this number as we can change all 0’s or all 1’s. " }, { "code": null, "e": 634, "s": 630, "text": "C++" }, { "code": null, "e": 639, "s": 634, "text": "Java" }, { "code": null, "e": 648, "s": 639, "text": "Python 3" }, { "code": null, "e": 651, "s": 648, "text": "C#" }, { "code": null, "e": 655, "s": 651, "text": "PHP" }, { "code": null, "e": 666, "s": 655, "text": "Javascript" }, { "code": "// CPP program to find min flips in binary// string to make all characters equal#include <bits/stdc++.h>using namespace std; // To find min number of flips in binary stringint findFlips(char str[], int n){ char last = ' '; int res = 0; for (int i = 0; i < n; i++) { // If last character is not equal // to str[i] increase res if (last != str[i]) res++; last = str[i]; } // To return min flips return res / 2;} // Driver program to check findFlips()int main(){ char str[] = \"00011110001110\"; int n = strlen(str); cout << findFlips(str, n); return 0;}", "e": 1287, "s": 666, "text": null }, { "code": "// Java program to find min flips in binary// string to make all characters equalpublic class minFlips { // To find min number of flips in binary string static int findFlips(String str, int n) { char last = ' '; int res = 0; for (int i = 0; i < n; i++) { // If last character is not equal // to str[i] increase res if (last != str.charAt(i)) res++; last = str.charAt(i); } // To return min flips return res / 2; } // Driver program to check findFlips() public static void main(String[] args) { String str = \"00011110001110\"; int n = str.length(); System.out.println(findFlips(str, n)); }}", "e": 2021, "s": 1287, "text": null }, { "code": "# Python 3 program to find min flips in# binary string to make all characters equal # To find min number of flips in# binary stringdef findFlips(str, n): last = ' ' res = 0 for i in range( n) : # If last character is not equal # to str[i] increase res if (last != str[i]): res += 1 last = str[i] # To return min flips return res // 2 # Driver Codeif __name__ == \"__main__\": str = \"00011110001110\" n = len(str) print(findFlips(str, n)) # This code is contributed by ita_c", "e": 2565, "s": 2021, "text": null }, { "code": "// C# program to find min flips in// binary string to make all// characters equalusing System; public class GFG { // To find min number of flips // in binary string static int findFlips(String str, int n) { char last = ' '; int res = 0; for (int i = 0; i < n; i++) { // If last character is not // equal to str[i] increase // res if (last != str[i]) res++; last = str[i]; } // To return min flips return res / 2; } // Driver program to check findFlips() public static void Main() { String str = \"00011110001110\"; int n = str.Length; Console.Write(findFlips(str, n)); }} // This code is contributed by nitin mittal", "e": 3338, "s": 2565, "text": null }, { "code": "<?php// PHP program to find min flips in binary// string to make all characters equal // To find min number of// flips in binary stringfunction findFlips($str, $n){ $last = ' '; $res = 0; for ($i = 0; $i < $n; $i++) { // If last character is not equal // to str[i] increase res if ($last != $str[$i]) $res++; $last = $str[$i]; } // To return min flips return intval($res / 2);} // Driver Code $str = \"00011110001110\"; $n = strlen($str); echo findFlips($str, $n); // This code is contributed by Sam007?>", "e": 3922, "s": 3338, "text": null }, { "code": "<script> // JavaScript program to find min flips in binary// string to make all characters equal // To find min number of flips in binary string function findFlips( str , n) { var last = ' '; var res = 0; for (i = 0; i < n; i++) { // If last character is not equal // to str[i] increase res if (last != str.charAt(i)) res++; last = str.charAt(i); } // To return min flips return parseInt(res / 2); } // Driver program to check findFlips() var str = \"00011110001110\"; var n = str.length; document.write(findFlips(str, n)); // This code contributed by aashish1995 </script>", "e": 4641, "s": 3922, "text": null }, { "code": null, "e": 4685, "s": 4641, "text": "Time Complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 4694, "s": 4685, "text": "Output: " }, { "code": null, "e": 4703, "s": 4694, "text": "Chapters" }, { "code": null, "e": 4730, "s": 4703, "text": "descriptions off, selected" }, { "code": null, "e": 4780, "s": 4730, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 4803, "s": 4780, "text": "captions off, selected" }, { "code": null, "e": 4811, "s": 4803, "text": "English" }, { "code": null, "e": 4829, "s": 4811, "text": "default, selected" }, { "code": null, "e": 4853, "s": 4829, "text": "This is a modal window." }, { "code": null, "e": 4922, "s": 4853, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 4944, "s": 4922, "text": "End of dialog window." }, { "code": null, "e": 4946, "s": 4944, "text": "2" }, { "code": null, "e": 5914, "s": 4948, "text": "Minimum flips of continuous characters to make all same in a binary string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMinimum flips of continuous characters to make all same in a binary string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ZYqT5pDnQt8\" 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": 6330, "s": 5914, "text": "This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 6343, "s": 6330, "text": "nitin mittal" }, { "code": null, "e": 6350, "s": 6343, "text": "Sam007" }, { "code": null, "e": 6356, "s": 6350, "text": "ukasp" }, { "code": null, "e": 6368, "s": 6356, "text": "aashish1995" }, { "code": null, "e": 6384, "s": 6368, "text": "rohitsingh07052" }, { "code": null, "e": 6398, "s": 6384, "text": "binary-string" }, { "code": null, "e": 6406, "s": 6398, "text": "Strings" }, { "code": null, "e": 6414, "s": 6406, "text": "Strings" }, { "code": null, "e": 6512, "s": 6414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6558, "s": 6512, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6583, "s": 6558, "text": "Reverse a string in Java" }, { "code": null, "e": 6643, "s": 6583, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6658, "s": 6643, "text": "C++ Data Types" }, { "code": null, "e": 6703, "s": 6658, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 6760, "s": 6703, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 6794, "s": 6760, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 6869, "s": 6794, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 6930, "s": 6869, "text": "Length of the longest substring without repeating characters" } ]
Difference between OpenSUSE and Fedora
28 Jun, 2022 1. OpenSUSE : OpenSUSE is a Linux distribution developed by The openSUSE Project. It was initially released on October 2005. It was developed for creating usable open-source tools for software developers and system administrators and it also provides a user-friendly environment and feature-rich server environment. 2. Fedora : Fedora OS is a Linux based open-source operating system developed by Red Hat. It is open-source and it is freely available for use. It uses the DNF package manager and gnome environment along with anaconda installer. It supports 3 platforms, which are Workstation Fedora designed for Personal Computers, Fedora Server designed for servers and Fedora Atomic designed for cloud computing. Difference between OpenSUSE and Fedora : raj2002 Difference Between Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2022" }, { "code": null, "e": 345, "s": 28, "text": "1. OpenSUSE : OpenSUSE is a Linux distribution developed by The openSUSE Project. It was initially released on October 2005. It was developed for creating usable open-source tools for software developers and system administrators and it also provides a user-friendly environment and feature-rich server environment. " }, { "code": null, "e": 746, "s": 345, "text": "2. Fedora : Fedora OS is a Linux based open-source operating system developed by Red Hat. It is open-source and it is freely available for use. It uses the DNF package manager and gnome environment along with anaconda installer. It supports 3 platforms, which are Workstation Fedora designed for Personal Computers, Fedora Server designed for servers and Fedora Atomic designed for cloud computing. " }, { "code": null, "e": 787, "s": 746, "text": "Difference between OpenSUSE and Fedora :" }, { "code": null, "e": 795, "s": 787, "text": "raj2002" }, { "code": null, "e": 814, "s": 795, "text": "Difference Between" }, { "code": null, "e": 832, "s": 814, "text": "Operating Systems" }, { "code": null, "e": 850, "s": 832, "text": "Operating Systems" } ]
Find the position of the given row in a 2-D array
26 May, 2021 Given a matrix mat[][] of size m * n which is sorted in row-wise fashion and an array row[], the task is to check if any row in the matrix is equal to the given array row[].Examples: Input: mat[][] = { {1, 1, 2, 3, 1}, {2, 1, 3, 3, 2}, {2, 4, 5, 8, 3}, {4, 5, 5, 8, 3}, {8, 7, 10, 13, 6}}row[] = {4, 5, 5, 8, 3} Output: 4 4th row is equal to the given array.Input: mat[][] = { {0, 0, 1, 0}, {10, 9, 22, 23}, {40, 40, 40, 40}, {43, 44, 55, 68}, {81, 73, 100, 132}, {100, 75, 125, 133}}row[] = {10, 9, 22, 23} Output: 2 Naive approach: Similar to a linear search on a 1-D array, perform the linear search on the matrix and compare every row of the matrix with the given array. If some row matches with the array, print its row number else print -1.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int m = 6, n = 4; // Function to find a row in the// given matrix using linear searchint linearCheck(int ar[][n], int arr[]){ for (int i = 0; i < m; i++) { // Assume that the current row matched // with the given array bool matched = true; for (int j = 0; j < n; j++) { // If any element of the current row doesn't // match with the corresponding element // of the given array if (ar[i][j] != arr[j]) { // Set matched to false and break; matched = false; break; } } // If matched then return the row number if (matched) return i + 1; } // No row matched with the given array return -1;} // Driver codeint main(){ int mat[m][n] = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int row[n] = { 10, 9, 22, 23 }; cout << linearCheck(mat, row); return 0;} // Java implementation of the approachimport java.io.*; class GFG{ static int m = 6, n = 4; // Function to find a row in the// given matrix using linear searchstatic int linearCheck(int ar[][], int arr[]){ for (int i = 0; i < m; i++) { // Assume that the current row matched // with the given array boolean matched = true; for (int j = 0; j < n; j++) { // If any element of the current row doesn't // match with the corresponding element // of the given array if (ar[i][j] != arr[j]) { // Set matched to false and break; matched = false; break; } } // If matched then return the row number if (matched) return i + 1; } // No row matched with the given array return -1;} // Driver codepublic static void main (String[] args){ int mat[][] = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int row[] = { 10, 9, 22, 23 }; System.out.println (linearCheck(mat, row));}} // This code is contributed BY @Tushil.. # Python implementation of the approach m, n = 6, 4; # Function to find a row in the# given matrix using linear searchdef linearCheck(ar, arr): for i in range(m): # Assume that the current row matched # with the given array matched = True; for j in range(n): # If any element of the current row doesn't # match with the corresponding element # of the given array if (ar[i][j] != arr[j]): # Set matched to false and break; matched = False; break; # If matched then return the row number if (matched): return i + 1; # No row matched with the given array return -1; # Driver codeif __name__ == "__main__" : mat = [ [ 0, 0, 1, 0 ], [ 10, 9, 22, 23 ], [ 40, 40, 40, 40 ], [ 43, 44, 55, 68 ], [ 81, 73, 100, 132 ], [ 100, 75, 125, 133 ] ]; row = [ 10, 9, 22, 23 ]; print(linearCheck(mat, row)); # This code is contributed by Princi Singh // C# implementation of the approachusing System; class GFG{ static int m = 6;static int n = 4; // Function to find a row in the// given matrix using linear searchstatic int linearCheck(int [,]ar, int []arr){ for (int i = 0; i < m; i++) { // Assume that the current row matched // with the given array bool matched = true; for (int j = 0; j < n; j++) { // If any element of the current row doesn't // match with the corresponding element // of the given array if (ar[i,j] != arr[j]) { // Set matched to false and break; matched = false; break; } } // If matched then return the row number if (matched) return i + 1; } // No row matched with the given array return -1;} // Driver codestatic public void Main (){ int [,]mat = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int []row = { 10, 9, 22, 23 }; Console.Write(linearCheck(mat, row));}} // This code is contributed BY ajit.. <script> // Javascript implementation of the approach let m = 6, n = 4; // Function to find a row in the // given matrix using linear search function linearCheck(ar, arr) { for (let i = 0; i < m; i++) { // Assume that the current row matched // with the given array let matched = true; for (let j = 0; j < n; j++) { // If any element of the current row doesn't // match with the corresponding element // of the given array if (ar[i][j] != arr[j]) { // Set matched to false and break; matched = false; break; } } // If matched then return the row number if (matched) return i + 1; } // No row matched with the given array return -1; } let mat = [ [ 0, 0, 1, 0 ], [ 10, 9, 22, 23 ], [ 40, 40, 40, 40 ], [ 43, 44, 55, 68 ], [ 81, 73, 100, 132 ], [ 100, 75, 125, 133 ] ]; let row = [ 10, 9, 22, 23 ]; document.write(linearCheck(mat, row)); </script> 2 Time Complexity: O(m * n)Efficient approach: Since the matrix is sorted in a row-wise fashion, we can use binary search similar to what we do in a 1-D array. It is necessary for the array to be sorted in a row-wise fashion. Below are the steps to find a row in the matrix using binary search, Compare arr[] with the middle row.If arr[] matches entirely with the middle row, we return the mid index.Else If arr[] is greater than the mid-row(there exists at least one j, 0<=j<n such that ar[mid][j]<arr[j]), then arr[] can only lie in right half subarray after the mid-row. So we check in the bottom half.Else (arr[] is smaller), we check in the upper half. Compare arr[] with the middle row. If arr[] matches entirely with the middle row, we return the mid index. Else If arr[] is greater than the mid-row(there exists at least one j, 0<=j<n such that ar[mid][j]<arr[j]), then arr[] can only lie in right half subarray after the mid-row. So we check in the bottom half. Else (arr[] is smaller), we check in the upper half. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int m = 6, n = 4; // Function that compares both the arrays// and returns -1, 0 and 1 accordinglyint compareRow(int a1[], int a2[]){ for (int i = 0; i < n; i++) { // Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) return 1; // Return 1 if mid row is greater than arr[] else if (a1[i] > a2[i]) return -1; } // Both the arrays are equal return 0;} // Function to find a row in the// given matrix using binary searchint binaryCheck(int ar[][n], int arr[]){ int l = 0, r = m - 1; while (l <= r) { int mid = (l + r) / 2; int temp = compareRow(ar[mid], arr); // If current row is equal to the given // array then return the row number if (temp == 0) return mid + 1; // If arr[] is greater, ignore left half else if (temp == 1) l = mid + 1; // If arr[] is smaller, ignore right half else r = mid - 1; } // No valid row found return -1;} // Driver codeint main(){ int mat[m][n] = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int row[n] = { 10, 9, 22, 23 }; cout << binaryCheck(mat, row); return 0;} // Java implementation of the approachclass GFG{ static int m = 6, n = 4; // Function that compares both the arrays// and returns -1, 0 and 1 accordinglystatic int compareRow(int a1[], int a2[]){ for (int i = 0; i < n; i++) { // Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) return 1; // Return 1 if mid row is greater than arr[] else if (a1[i] > a2[i]) return -1; } // Both the arrays are equal return 0;} // Function to find a row in the// given matrix using binary searchstatic int binaryCheck(int ar[][], int arr[]){ int l = 0, r = m - 1; while (l <= r) { int mid = (l + r) / 2; int temp = compareRow(ar[mid], arr); // If current row is equal to the given // array then return the row number if (temp == 0) return mid + 1; // If arr[] is greater, ignore left half else if (temp == 1) l = mid + 1; // If arr[] is smaller, ignore right half else r = mid - 1; } // No valid row found return -1;} // Driver codepublic static void main(String[] args){ int mat[][] = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int row[] = { 10, 9, 22, 23 }; System.out.println(binaryCheck(mat, row));}} // This code is contributed by 29AjayKumar # Python3 implementation of the approach m = 6;n = 4; # Function that compares both the arrays# and returns -1, 0 and 1 accordinglydef compareRow(a1, a2) : for i in range(n) : # Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) : return 1; # Return 1 if mid row is greater than arr[] elif (a1[i] > a2[i]) : return -1; # Both the arrays are equal return 0; # Function to find a row in the# given matrix using binary searchdef binaryCheck(ar, arr) : l = 0; r = m - 1; while (l <= r) : mid = (l + r) // 2; temp = compareRow(ar[mid], arr); # If current row is equal to the given # array then return the row number if (temp == 0) : return mid + 1; # If arr[] is greater, ignore left half elif (temp == 1) : l = mid + 1; # If arr[] is smaller, ignore right half else : r = mid - 1; # No valid row found return -1; # Driver codeif __name__ == "__main__" : mat = [ [ 0, 0, 1, 0 ], [ 10, 9, 22, 23 ], [ 40, 40, 40, 40 ], [ 43, 44, 55, 68 ], [ 81, 73, 100, 132 ], [ 100, 75, 125, 133 ] ]; row = [ 10, 9, 22, 23 ]; print(binaryCheck(mat, row)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ static int m = 6, n = 4; // Function that compares both the arrays// and returns -1, 0 and 1 accordinglystatic int compareRow(int []a1, int []a2){ for (int i = 0; i < n; i++) { // Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) return 1; // Return 1 if mid row is greater than arr[] else if (a1[i] > a2[i]) return -1; } // Both the arrays are equal return 0;} // Function to find a row in the// given matrix using binary searchstatic int binaryCheck(int [,]ar, int []arr){ int l = 0, r = m - 1; while (l <= r) { int mid = (l + r) / 2; int temp = compareRow(GetRow(ar, mid), arr); // If current row is equal to the given // array then return the row number if (temp == 0) return mid + 1; // If arr[] is greater, ignore left half else if (temp == 1) l = mid + 1; // If arr[] is smaller, ignore right half else r = mid - 1; } // No valid row found return -1;} public static int[] GetRow(int[,] matrix, int row){ var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector;} // Driver codepublic static void Main(String[] args){ int [,]mat = {{ 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 }}; int []row = { 10, 9, 22, 23 }; Console.WriteLine(binaryCheck(mat, row));}} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of the approachvar m = 6, n = 4; // Function that compares both the arrays// and returns -1, 0 and 1 accordinglyfunction compareRow(a1, a2){ for (var i = 0; i < n; i++) { // Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) return 1; // Return 1 if mid row is greater than arr[] else if (a1[i] > a2[i]) return -1; } // Both the arrays are equal return 0;} // Function to find a row in the// given matrix using binary searchfunction binaryCheck(ar, arr){ var l = 0, r = m - 1; while (l <= r) { var mid = parseInt((l + r) / 2); var temp = compareRow(ar[mid], arr); // If current row is equal to the given // array then return the row number if (temp == 0) return mid + 1; // If arr[] is greater, ignore left half else if (temp == 1) l = mid + 1; // If arr[] is smaller, ignore right half else r = mid - 1; } // No valid row found return -1;} // Driver codevar mat = [ [ 0, 0, 1, 0 ], [ 10, 9, 22, 23 ], [ 40, 40, 40, 40 ], [ 43, 44, 55, 68 ], [ 81, 73, 100, 132 ], [ 100, 75, 125, 133 ] ];var row = [10, 9, 22, 23];document.write( binaryCheck(mat, row)); </script> 2 Time Complexity: O(n * log(m)) 29AjayKumar ankthon jit_t Rajput-Ji princi singh divyeshrabadiya07 rrrtnx Binary Search Arrays Matrix Searching Arrays Searching Matrix Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 The Celebrity Problem
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2021" }, { "code": null, "e": 239, "s": 54, "text": "Given a matrix mat[][] of size m * n which is sorted in row-wise fashion and an array row[], the task is to check if any row in the matrix is equal to the given array row[].Examples: " }, { "code": null, "e": 576, "s": 239, "text": "Input: mat[][] = { {1, 1, 2, 3, 1}, {2, 1, 3, 3, 2}, {2, 4, 5, 8, 3}, {4, 5, 5, 8, 3}, {8, 7, 10, 13, 6}}row[] = {4, 5, 5, 8, 3} Output: 4 4th row is equal to the given array.Input: mat[][] = { {0, 0, 1, 0}, {10, 9, 22, 23}, {40, 40, 40, 40}, {43, 44, 55, 68}, {81, 73, 100, 132}, {100, 75, 125, 133}}row[] = {10, 9, 22, 23} Output: 2 " }, { "code": null, "e": 859, "s": 578, "text": "Naive approach: Similar to a linear search on a 1-D array, perform the linear search on the matrix and compare every row of the matrix with the given array. If some row matches with the array, print its row number else print -1.Below is the implementation of the above approach: " }, { "code": null, "e": 863, "s": 859, "text": "C++" }, { "code": null, "e": 868, "s": 863, "text": "Java" }, { "code": null, "e": 876, "s": 868, "text": "Python3" }, { "code": null, "e": 879, "s": 876, "text": "C#" }, { "code": null, "e": 890, "s": 879, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int m = 6, n = 4; // Function to find a row in the// given matrix using linear searchint linearCheck(int ar[][n], int arr[]){ for (int i = 0; i < m; i++) { // Assume that the current row matched // with the given array bool matched = true; for (int j = 0; j < n; j++) { // If any element of the current row doesn't // match with the corresponding element // of the given array if (ar[i][j] != arr[j]) { // Set matched to false and break; matched = false; break; } } // If matched then return the row number if (matched) return i + 1; } // No row matched with the given array return -1;} // Driver codeint main(){ int mat[m][n] = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int row[n] = { 10, 9, 22, 23 }; cout << linearCheck(mat, row); return 0;}", "e": 2101, "s": 890, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG{ static int m = 6, n = 4; // Function to find a row in the// given matrix using linear searchstatic int linearCheck(int ar[][], int arr[]){ for (int i = 0; i < m; i++) { // Assume that the current row matched // with the given array boolean matched = true; for (int j = 0; j < n; j++) { // If any element of the current row doesn't // match with the corresponding element // of the given array if (ar[i][j] != arr[j]) { // Set matched to false and break; matched = false; break; } } // If matched then return the row number if (matched) return i + 1; } // No row matched with the given array return -1;} // Driver codepublic static void main (String[] args){ int mat[][] = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int row[] = { 10, 9, 22, 23 }; System.out.println (linearCheck(mat, row));}} // This code is contributed BY @Tushil..", "e": 3366, "s": 2101, "text": null }, { "code": "# Python implementation of the approach m, n = 6, 4; # Function to find a row in the# given matrix using linear searchdef linearCheck(ar, arr): for i in range(m): # Assume that the current row matched # with the given array matched = True; for j in range(n): # If any element of the current row doesn't # match with the corresponding element # of the given array if (ar[i][j] != arr[j]): # Set matched to false and break; matched = False; break; # If matched then return the row number if (matched): return i + 1; # No row matched with the given array return -1; # Driver codeif __name__ == \"__main__\" : mat = [ [ 0, 0, 1, 0 ], [ 10, 9, 22, 23 ], [ 40, 40, 40, 40 ], [ 43, 44, 55, 68 ], [ 81, 73, 100, 132 ], [ 100, 75, 125, 133 ] ]; row = [ 10, 9, 22, 23 ]; print(linearCheck(mat, row)); # This code is contributed by Princi Singh", "e": 4430, "s": 3366, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int m = 6;static int n = 4; // Function to find a row in the// given matrix using linear searchstatic int linearCheck(int [,]ar, int []arr){ for (int i = 0; i < m; i++) { // Assume that the current row matched // with the given array bool matched = true; for (int j = 0; j < n; j++) { // If any element of the current row doesn't // match with the corresponding element // of the given array if (ar[i,j] != arr[j]) { // Set matched to false and break; matched = false; break; } } // If matched then return the row number if (matched) return i + 1; } // No row matched with the given array return -1;} // Driver codestatic public void Main (){ int [,]mat = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int []row = { 10, 9, 22, 23 }; Console.Write(linearCheck(mat, row));}} // This code is contributed BY ajit..", "e": 5671, "s": 4430, "text": null }, { "code": "<script> // Javascript implementation of the approach let m = 6, n = 4; // Function to find a row in the // given matrix using linear search function linearCheck(ar, arr) { for (let i = 0; i < m; i++) { // Assume that the current row matched // with the given array let matched = true; for (let j = 0; j < n; j++) { // If any element of the current row doesn't // match with the corresponding element // of the given array if (ar[i][j] != arr[j]) { // Set matched to false and break; matched = false; break; } } // If matched then return the row number if (matched) return i + 1; } // No row matched with the given array return -1; } let mat = [ [ 0, 0, 1, 0 ], [ 10, 9, 22, 23 ], [ 40, 40, 40, 40 ], [ 43, 44, 55, 68 ], [ 81, 73, 100, 132 ], [ 100, 75, 125, 133 ] ]; let row = [ 10, 9, 22, 23 ]; document.write(linearCheck(mat, row)); </script>", "e": 6929, "s": 5671, "text": null }, { "code": null, "e": 6931, "s": 6929, "text": "2" }, { "code": null, "e": 7228, "s": 6933, "text": "Time Complexity: O(m * n)Efficient approach: Since the matrix is sorted in a row-wise fashion, we can use binary search similar to what we do in a 1-D array. It is necessary for the array to be sorted in a row-wise fashion. Below are the steps to find a row in the matrix using binary search, " }, { "code": null, "e": 7591, "s": 7228, "text": "Compare arr[] with the middle row.If arr[] matches entirely with the middle row, we return the mid index.Else If arr[] is greater than the mid-row(there exists at least one j, 0<=j<n such that ar[mid][j]<arr[j]), then arr[] can only lie in right half subarray after the mid-row. So we check in the bottom half.Else (arr[] is smaller), we check in the upper half." }, { "code": null, "e": 7626, "s": 7591, "text": "Compare arr[] with the middle row." }, { "code": null, "e": 7698, "s": 7626, "text": "If arr[] matches entirely with the middle row, we return the mid index." }, { "code": null, "e": 7904, "s": 7698, "text": "Else If arr[] is greater than the mid-row(there exists at least one j, 0<=j<n such that ar[mid][j]<arr[j]), then arr[] can only lie in right half subarray after the mid-row. So we check in the bottom half." }, { "code": null, "e": 7957, "s": 7904, "text": "Else (arr[] is smaller), we check in the upper half." }, { "code": null, "e": 8010, "s": 7957, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 8014, "s": 8010, "text": "C++" }, { "code": null, "e": 8019, "s": 8014, "text": "Java" }, { "code": null, "e": 8027, "s": 8019, "text": "Python3" }, { "code": null, "e": 8030, "s": 8027, "text": "C#" }, { "code": null, "e": 8041, "s": 8030, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int m = 6, n = 4; // Function that compares both the arrays// and returns -1, 0 and 1 accordinglyint compareRow(int a1[], int a2[]){ for (int i = 0; i < n; i++) { // Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) return 1; // Return 1 if mid row is greater than arr[] else if (a1[i] > a2[i]) return -1; } // Both the arrays are equal return 0;} // Function to find a row in the// given matrix using binary searchint binaryCheck(int ar[][n], int arr[]){ int l = 0, r = m - 1; while (l <= r) { int mid = (l + r) / 2; int temp = compareRow(ar[mid], arr); // If current row is equal to the given // array then return the row number if (temp == 0) return mid + 1; // If arr[] is greater, ignore left half else if (temp == 1) l = mid + 1; // If arr[] is smaller, ignore right half else r = mid - 1; } // No valid row found return -1;} // Driver codeint main(){ int mat[m][n] = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int row[n] = { 10, 9, 22, 23 }; cout << binaryCheck(mat, row); return 0;}", "e": 9507, "s": 8041, "text": null }, { "code": "// Java implementation of the approachclass GFG{ static int m = 6, n = 4; // Function that compares both the arrays// and returns -1, 0 and 1 accordinglystatic int compareRow(int a1[], int a2[]){ for (int i = 0; i < n; i++) { // Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) return 1; // Return 1 if mid row is greater than arr[] else if (a1[i] > a2[i]) return -1; } // Both the arrays are equal return 0;} // Function to find a row in the// given matrix using binary searchstatic int binaryCheck(int ar[][], int arr[]){ int l = 0, r = m - 1; while (l <= r) { int mid = (l + r) / 2; int temp = compareRow(ar[mid], arr); // If current row is equal to the given // array then return the row number if (temp == 0) return mid + 1; // If arr[] is greater, ignore left half else if (temp == 1) l = mid + 1; // If arr[] is smaller, ignore right half else r = mid - 1; } // No valid row found return -1;} // Driver codepublic static void main(String[] args){ int mat[][] = { { 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 } }; int row[] = { 10, 9, 22, 23 }; System.out.println(binaryCheck(mat, row));}} // This code is contributed by 29AjayKumar", "e": 11018, "s": 9507, "text": null }, { "code": "# Python3 implementation of the approach m = 6;n = 4; # Function that compares both the arrays# and returns -1, 0 and 1 accordinglydef compareRow(a1, a2) : for i in range(n) : # Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) : return 1; # Return 1 if mid row is greater than arr[] elif (a1[i] > a2[i]) : return -1; # Both the arrays are equal return 0; # Function to find a row in the# given matrix using binary searchdef binaryCheck(ar, arr) : l = 0; r = m - 1; while (l <= r) : mid = (l + r) // 2; temp = compareRow(ar[mid], arr); # If current row is equal to the given # array then return the row number if (temp == 0) : return mid + 1; # If arr[] is greater, ignore left half elif (temp == 1) : l = mid + 1; # If arr[] is smaller, ignore right half else : r = mid - 1; # No valid row found return -1; # Driver codeif __name__ == \"__main__\" : mat = [ [ 0, 0, 1, 0 ], [ 10, 9, 22, 23 ], [ 40, 40, 40, 40 ], [ 43, 44, 55, 68 ], [ 81, 73, 100, 132 ], [ 100, 75, 125, 133 ] ]; row = [ 10, 9, 22, 23 ]; print(binaryCheck(mat, row)); # This code is contributed by AnkitRai01", "e": 12370, "s": 11018, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int m = 6, n = 4; // Function that compares both the arrays// and returns -1, 0 and 1 accordinglystatic int compareRow(int []a1, int []a2){ for (int i = 0; i < n; i++) { // Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) return 1; // Return 1 if mid row is greater than arr[] else if (a1[i] > a2[i]) return -1; } // Both the arrays are equal return 0;} // Function to find a row in the// given matrix using binary searchstatic int binaryCheck(int [,]ar, int []arr){ int l = 0, r = m - 1; while (l <= r) { int mid = (l + r) / 2; int temp = compareRow(GetRow(ar, mid), arr); // If current row is equal to the given // array then return the row number if (temp == 0) return mid + 1; // If arr[] is greater, ignore left half else if (temp == 1) l = mid + 1; // If arr[] is smaller, ignore right half else r = mid - 1; } // No valid row found return -1;} public static int[] GetRow(int[,] matrix, int row){ var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector;} // Driver codepublic static void Main(String[] args){ int [,]mat = {{ 0, 0, 1, 0 }, { 10, 9, 22, 23 }, { 40, 40, 40, 40 }, { 43, 44, 55, 68 }, { 81, 73, 100, 132 }, { 100, 75, 125, 133 }}; int []row = { 10, 9, 22, 23 }; Console.WriteLine(binaryCheck(mat, row));}} // This code is contributed by Rajput-Ji", "e": 14112, "s": 12370, "text": null }, { "code": "<script> // JavaScript implementation of the approachvar m = 6, n = 4; // Function that compares both the arrays// and returns -1, 0 and 1 accordinglyfunction compareRow(a1, a2){ for (var i = 0; i < n; i++) { // Return 1 if mid row is less than arr[] if (a1[i] < a2[i]) return 1; // Return 1 if mid row is greater than arr[] else if (a1[i] > a2[i]) return -1; } // Both the arrays are equal return 0;} // Function to find a row in the// given matrix using binary searchfunction binaryCheck(ar, arr){ var l = 0, r = m - 1; while (l <= r) { var mid = parseInt((l + r) / 2); var temp = compareRow(ar[mid], arr); // If current row is equal to the given // array then return the row number if (temp == 0) return mid + 1; // If arr[] is greater, ignore left half else if (temp == 1) l = mid + 1; // If arr[] is smaller, ignore right half else r = mid - 1; } // No valid row found return -1;} // Driver codevar mat = [ [ 0, 0, 1, 0 ], [ 10, 9, 22, 23 ], [ 40, 40, 40, 40 ], [ 43, 44, 55, 68 ], [ 81, 73, 100, 132 ], [ 100, 75, 125, 133 ] ];var row = [10, 9, 22, 23];document.write( binaryCheck(mat, row)); </script>", "e": 15486, "s": 14112, "text": null }, { "code": null, "e": 15488, "s": 15486, "text": "2" }, { "code": null, "e": 15522, "s": 15490, "text": "Time Complexity: O(n * log(m)) " }, { "code": null, "e": 15534, "s": 15522, "text": "29AjayKumar" }, { "code": null, "e": 15542, "s": 15534, "text": "ankthon" }, { "code": null, "e": 15548, "s": 15542, "text": "jit_t" }, { "code": null, "e": 15558, "s": 15548, "text": "Rajput-Ji" }, { "code": null, "e": 15571, "s": 15558, "text": "princi singh" }, { "code": null, "e": 15589, "s": 15571, "text": "divyeshrabadiya07" }, { "code": null, "e": 15596, "s": 15589, "text": "rrrtnx" }, { "code": null, "e": 15610, "s": 15596, "text": "Binary Search" }, { "code": null, "e": 15617, "s": 15610, "text": "Arrays" }, { "code": null, "e": 15624, "s": 15617, "text": "Matrix" }, { "code": null, "e": 15634, "s": 15624, "text": "Searching" }, { "code": null, "e": 15641, "s": 15634, "text": "Arrays" }, { "code": null, "e": 15651, "s": 15641, "text": "Searching" }, { "code": null, "e": 15658, "s": 15651, "text": "Matrix" }, { "code": null, "e": 15672, "s": 15658, "text": "Binary Search" }, { "code": null, "e": 15770, "s": 15672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15838, "s": 15770, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 15882, "s": 15838, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 15914, "s": 15882, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 15962, "s": 15914, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 15976, "s": 15962, "text": "Linear Search" }, { "code": null, "e": 16011, "s": 15976, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 16055, "s": 16011, "text": "Program to find largest element in an array" }, { "code": null, "e": 16086, "s": 16055, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 16110, "s": 16086, "text": "Sudoku | Backtracking-7" } ]
Types of Antialiasing Techniques
10 Jul, 2020 At some point when you watch video or play game on your screen you may experience blocky or pixelated edges on your screen, this impact is known as Aliasing or normally called as “jaggies”. This can be simply killed by raising your screen resolution, however as not every person has a high-end PC, there are a few techniques that can be used to reduce impact of jaggies on your screen. Antialiasing :It is technique that would assist you with eliminating impact of jaggies on your screen. There are various types of Antialiasing techniques and each having it’s different usage and limitations. You can usually change your game’s graphic setting including Antialiasing in game’s settings.Additionally, in some GPUs you can modify your PC’s Antialiasing setting from GPU’s control board. What are Jaggies ?The pictures that are shown on your PC screen are made out of similarly measured squares known as pixels which have their own single colour. At the point when pictures that are being shown have vertical or horizontal lines then these pixels are adjusted side to side but when a bend or corner to corner picture must be shown these pixels must be adjusted point to point which reveals their barbed edges, this impact is called “jaggies”. A better quality equipment don’t experience this issue as it is equipped for showing picture in a higher resolution which thus has enough pixels which don’t prompts edges being appeared. Types of Antialiasing Techniques :Generally all Antialiasing methods can be classified into two classifications: 1. Spatial Antialiasing 2. Post Process Antialiasing Both, in general accomplish a similar work however in different manners.These are explained as following below. 1. Spatial Antialiasing :Before knowing about Antialiasing one must know about monitor resolution. Resolution is amount of pixels that a screen uses to show your picture. A decent screen must has a resolution of 1920×1080 (1920 pixels horizontally and 1080 pixels vertically) or higher. Spatial Antialiasing is performed using following steps – A low resolution picture that has jaggies is taken.Picture is rendered into it’s high resolution structure.At high resolution, colour samples are taken from extra pixels that were absent in low resolution image.At low resolution, every pixel gets another colour which has been arrived at average of out from extra pixels. A low resolution picture that has jaggies is taken. Picture is rendered into it’s high resolution structure. At high resolution, colour samples are taken from extra pixels that were absent in low resolution image. At low resolution, every pixel gets another colour which has been arrived at average of out from extra pixels. New colour helps pixels to mix together more effectively and jaggies turns out to be less noticeable. Spatial Antialiasing is likewise further sub-divided as follows – Super Sampling Antialiasing –It is also called as Full Scene Antialiasing (FSAA) is one of most effective Antialiasing strategies. It utilizes a similar method as portrayed above to arrive at it’s objective. Yet, there are drawback too of this method as it necessitates that whole picture must be handled before jaggies can be fixed and as gaming screens needs fixing in real time, SSAA needs a high registering capacity to work at such speed.Multi Sample Antialiasing (MSAA) –When GPU is rendering any picture it does it in two sections – polygon (shape of picture) and texture. First polygon of picture is rendered and afterward rendered texture is applied over it.Multi sample Antialiasing (MSAA) just fixes jaggies on polygon and texture is forgotten about. Because of this factor it requires less processing power. It is very famous among games. Super Sampling Antialiasing –It is also called as Full Scene Antialiasing (FSAA) is one of most effective Antialiasing strategies. It utilizes a similar method as portrayed above to arrive at it’s objective. Yet, there are drawback too of this method as it necessitates that whole picture must be handled before jaggies can be fixed and as gaming screens needs fixing in real time, SSAA needs a high registering capacity to work at such speed. Multi Sample Antialiasing (MSAA) –When GPU is rendering any picture it does it in two sections – polygon (shape of picture) and texture. First polygon of picture is rendered and afterward rendered texture is applied over it.Multi sample Antialiasing (MSAA) just fixes jaggies on polygon and texture is forgotten about. Because of this factor it requires less processing power. It is very famous among games. Multi sample Antialiasing (MSAA) just fixes jaggies on polygon and texture is forgotten about. Because of this factor it requires less processing power. It is very famous among games. CSAA and EQAA – GPU producing organizations Nvidia and AMD planned these new spatial Antialiasing methods. Coverage Sampling Antialiasing was developed by Nvidia. Enhanced Quality Antialiasing was developed by AMD. They have different names but work in same way. Through these methods GPU examines polygon present in picture and which portions of this polygon are probably going to have jaggies. At that point it super samples just those parts. Since it doesn’t super sample entire picture, they require less capacity to run. 2. Post Process Antialiasing :In Post Process Antialiasing (PPAA), every pixel is somewhat blurred in process of rendering. GPU decides a pixel is of different polygon if there is a distinction in their texture( two comparative pixels show that they are of same polygon). These pixels are blurred with respect to their difference. Blurring edges is a viable technique for decreasing jaggies as edges turns out to be less observable. Post-process Antialiasing is quick and requires considerably less handling power than spatial technique. Types of Post Process Antialiasing – Temporal Antialiasing –It is an extremely complicated technique that uses both Super sampling and blurring to make sharp illustrations and smooth movement.You’ll see signs of better pictures with TAA than you will with MLAA or FXAA, yet TAA requires much additionally computing power.Enhanced subpixel morphological Antialiasing (SMAA) –It is created by Jorge Jimenez. It joins both Spatial and Post process Antialiasing procedures. It smooths pixels utilizing equivalent blurring technique that MLAA and FXAA use, yet it likewise utilizes Super sampling to hone whole picture. Temporal Antialiasing –It is an extremely complicated technique that uses both Super sampling and blurring to make sharp illustrations and smooth movement.You’ll see signs of better pictures with TAA than you will with MLAA or FXAA, yet TAA requires much additionally computing power. You’ll see signs of better pictures with TAA than you will with MLAA or FXAA, yet TAA requires much additionally computing power. Enhanced subpixel morphological Antialiasing (SMAA) –It is created by Jorge Jimenez. It joins both Spatial and Post process Antialiasing procedures. It smooths pixels utilizing equivalent blurring technique that MLAA and FXAA use, yet it likewise utilizes Super sampling to hone whole picture. MLAA and FXAA : MLAA and FXAA are two Post Process Antialiasing methods made by Nvidia and AMD. Morphological Antialiasing (MLAA) is created by AMD. Fast Approximate Antialiasing (FXAA) is created by Nvidia. Two strategies works similarly as depicted previously. These are most well known of all Anti associating strategies but it make picture a little blurry. They require less computing power. Which is best Antialiasing Technique ?Well there is no best method for Antialiasing. Best technique to keep away from jaggies is that you utilize a very good quality equipment.In any case, on off chance that you are thinking about what methods to pick and when at that point – In the event that you are utilizing Low-end equipment, at that point you should think about SMAA or CSAA. In the event that you are utilizing Medium-end equipment, at that point you should think about SMAA/MSAA or MLAA/FXAA. In the event that you are utilizing High-end equipment, at that point you should seriously about TAA/SSAA or MSAA. computer-graphics Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 414, "s": 28, "text": "At some point when you watch video or play game on your screen you may experience blocky or pixelated edges on your screen, this impact is known as Aliasing or normally called as “jaggies”. This can be simply killed by raising your screen resolution, however as not every person has a high-end PC, there are a few techniques that can be used to reduce impact of jaggies on your screen." }, { "code": null, "e": 622, "s": 414, "text": "Antialiasing :It is technique that would assist you with eliminating impact of jaggies on your screen. There are various types of Antialiasing techniques and each having it’s different usage and limitations." }, { "code": null, "e": 814, "s": 622, "text": "You can usually change your game’s graphic setting including Antialiasing in game’s settings.Additionally, in some GPUs you can modify your PC’s Antialiasing setting from GPU’s control board." }, { "code": null, "e": 1269, "s": 814, "text": "What are Jaggies ?The pictures that are shown on your PC screen are made out of similarly measured squares known as pixels which have their own single colour. At the point when pictures that are being shown have vertical or horizontal lines then these pixels are adjusted side to side but when a bend or corner to corner picture must be shown these pixels must be adjusted point to point which reveals their barbed edges, this impact is called “jaggies”." }, { "code": null, "e": 1456, "s": 1269, "text": "A better quality equipment don’t experience this issue as it is equipped for showing picture in a higher resolution which thus has enough pixels which don’t prompts edges being appeared." }, { "code": null, "e": 1569, "s": 1456, "text": "Types of Antialiasing Techniques :Generally all Antialiasing methods can be classified into two classifications:" }, { "code": null, "e": 1623, "s": 1569, "text": "1. Spatial Antialiasing\n2. Post Process Antialiasing " }, { "code": null, "e": 1735, "s": 1623, "text": "Both, in general accomplish a similar work however in different manners.These are explained as following below." }, { "code": null, "e": 2022, "s": 1735, "text": "1. Spatial Antialiasing :Before knowing about Antialiasing one must know about monitor resolution. Resolution is amount of pixels that a screen uses to show your picture. A decent screen must has a resolution of 1920×1080 (1920 pixels horizontally and 1080 pixels vertically) or higher." }, { "code": null, "e": 2080, "s": 2022, "text": "Spatial Antialiasing is performed using following steps –" }, { "code": null, "e": 2402, "s": 2080, "text": "A low resolution picture that has jaggies is taken.Picture is rendered into it’s high resolution structure.At high resolution, colour samples are taken from extra pixels that were absent in low resolution image.At low resolution, every pixel gets another colour which has been arrived at average of out from extra pixels." }, { "code": null, "e": 2454, "s": 2402, "text": "A low resolution picture that has jaggies is taken." }, { "code": null, "e": 2511, "s": 2454, "text": "Picture is rendered into it’s high resolution structure." }, { "code": null, "e": 2616, "s": 2511, "text": "At high resolution, colour samples are taken from extra pixels that were absent in low resolution image." }, { "code": null, "e": 2727, "s": 2616, "text": "At low resolution, every pixel gets another colour which has been arrived at average of out from extra pixels." }, { "code": null, "e": 2829, "s": 2727, "text": "New colour helps pixels to mix together more effectively and jaggies turns out to be less noticeable." }, { "code": null, "e": 2895, "s": 2829, "text": "Spatial Antialiasing is likewise further sub-divided as follows –" }, { "code": null, "e": 3746, "s": 2895, "text": "Super Sampling Antialiasing –It is also called as Full Scene Antialiasing (FSAA) is one of most effective Antialiasing strategies. It utilizes a similar method as portrayed above to arrive at it’s objective. Yet, there are drawback too of this method as it necessitates that whole picture must be handled before jaggies can be fixed and as gaming screens needs fixing in real time, SSAA needs a high registering capacity to work at such speed.Multi Sample Antialiasing (MSAA) –When GPU is rendering any picture it does it in two sections – polygon (shape of picture) and texture. First polygon of picture is rendered and afterward rendered texture is applied over it.Multi sample Antialiasing (MSAA) just fixes jaggies on polygon and texture is forgotten about. Because of this factor it requires less processing power. It is very famous among games." }, { "code": null, "e": 4190, "s": 3746, "text": "Super Sampling Antialiasing –It is also called as Full Scene Antialiasing (FSAA) is one of most effective Antialiasing strategies. It utilizes a similar method as portrayed above to arrive at it’s objective. Yet, there are drawback too of this method as it necessitates that whole picture must be handled before jaggies can be fixed and as gaming screens needs fixing in real time, SSAA needs a high registering capacity to work at such speed." }, { "code": null, "e": 4598, "s": 4190, "text": "Multi Sample Antialiasing (MSAA) –When GPU is rendering any picture it does it in two sections – polygon (shape of picture) and texture. First polygon of picture is rendered and afterward rendered texture is applied over it.Multi sample Antialiasing (MSAA) just fixes jaggies on polygon and texture is forgotten about. Because of this factor it requires less processing power. It is very famous among games." }, { "code": null, "e": 4782, "s": 4598, "text": "Multi sample Antialiasing (MSAA) just fixes jaggies on polygon and texture is forgotten about. Because of this factor it requires less processing power. It is very famous among games." }, { "code": null, "e": 4798, "s": 4782, "text": "CSAA and EQAA –" }, { "code": null, "e": 4889, "s": 4798, "text": "GPU producing organizations Nvidia and AMD planned these new spatial Antialiasing methods." }, { "code": null, "e": 4945, "s": 4889, "text": "Coverage Sampling Antialiasing was developed by Nvidia." }, { "code": null, "e": 4997, "s": 4945, "text": "Enhanced Quality Antialiasing was developed by AMD." }, { "code": null, "e": 5045, "s": 4997, "text": "They have different names but work in same way." }, { "code": null, "e": 5308, "s": 5045, "text": "Through these methods GPU examines polygon present in picture and which portions of this polygon are probably going to have jaggies. At that point it super samples just those parts. Since it doesn’t super sample entire picture, they require less capacity to run." }, { "code": null, "e": 5639, "s": 5308, "text": "2. Post Process Antialiasing :In Post Process Antialiasing (PPAA), every pixel is somewhat blurred in process of rendering. GPU decides a pixel is of different polygon if there is a distinction in their texture( two comparative pixels show that they are of same polygon). These pixels are blurred with respect to their difference." }, { "code": null, "e": 5846, "s": 5639, "text": "Blurring edges is a viable technique for decreasing jaggies as edges turns out to be less observable. Post-process Antialiasing is quick and requires considerably less handling power than spatial technique." }, { "code": null, "e": 5883, "s": 5846, "text": "Types of Post Process Antialiasing –" }, { "code": null, "e": 6461, "s": 5883, "text": "Temporal Antialiasing –It is an extremely complicated technique that uses both Super sampling and blurring to make sharp illustrations and smooth movement.You’ll see signs of better pictures with TAA than you will with MLAA or FXAA, yet TAA requires much additionally computing power.Enhanced subpixel morphological Antialiasing (SMAA) –It is created by Jorge Jimenez. It joins both Spatial and Post process Antialiasing procedures. It smooths pixels utilizing equivalent blurring technique that MLAA and FXAA use, yet it likewise utilizes Super sampling to hone whole picture." }, { "code": null, "e": 6746, "s": 6461, "text": "Temporal Antialiasing –It is an extremely complicated technique that uses both Super sampling and blurring to make sharp illustrations and smooth movement.You’ll see signs of better pictures with TAA than you will with MLAA or FXAA, yet TAA requires much additionally computing power." }, { "code": null, "e": 6876, "s": 6746, "text": "You’ll see signs of better pictures with TAA than you will with MLAA or FXAA, yet TAA requires much additionally computing power." }, { "code": null, "e": 7170, "s": 6876, "text": "Enhanced subpixel morphological Antialiasing (SMAA) –It is created by Jorge Jimenez. It joins both Spatial and Post process Antialiasing procedures. It smooths pixels utilizing equivalent blurring technique that MLAA and FXAA use, yet it likewise utilizes Super sampling to hone whole picture." }, { "code": null, "e": 7186, "s": 7170, "text": "MLAA and FXAA :" }, { "code": null, "e": 7266, "s": 7186, "text": "MLAA and FXAA are two Post Process Antialiasing methods made by Nvidia and AMD." }, { "code": null, "e": 7319, "s": 7266, "text": "Morphological Antialiasing (MLAA) is created by AMD." }, { "code": null, "e": 7378, "s": 7319, "text": "Fast Approximate Antialiasing (FXAA) is created by Nvidia." }, { "code": null, "e": 7566, "s": 7378, "text": "Two strategies works similarly as depicted previously. These are most well known of all Anti associating strategies but it make picture a little blurry. They require less computing power." }, { "code": null, "e": 7843, "s": 7566, "text": "Which is best Antialiasing Technique ?Well there is no best method for Antialiasing. Best technique to keep away from jaggies is that you utilize a very good quality equipment.In any case, on off chance that you are thinking about what methods to pick and when at that point –" }, { "code": null, "e": 7949, "s": 7843, "text": "In the event that you are utilizing Low-end equipment, at that point you should think about SMAA or CSAA." }, { "code": null, "e": 8068, "s": 7949, "text": "In the event that you are utilizing Medium-end equipment, at that point you should think about SMAA/MSAA or MLAA/FXAA." }, { "code": null, "e": 8183, "s": 8068, "text": "In the event that you are utilizing High-end equipment, at that point you should seriously about TAA/SSAA or MSAA." }, { "code": null, "e": 8201, "s": 8183, "text": "computer-graphics" }, { "code": null, "e": 8206, "s": 8201, "text": "Misc" }, { "code": null, "e": 8211, "s": 8206, "text": "Misc" }, { "code": null, "e": 8216, "s": 8211, "text": "Misc" } ]
GATE | GATE CS 2020 | Question 23
26 May, 2021 Consider a relational database containing the following schemas. The primary key of each table is indicated by underlining the constituent fields. SELECT s.sno, s.sname FROM Suppliers s, Catalogue c WHERE s.sno=c.sno AND cost > (SELECT AVG (cost) FROM Catalogue WHERE pno = ‘P4’ GROUP BY pno) ; The number of rows returned by the above SQL query is(A) 4(B) 5(C) 0(D) 2Answer: (A)Explanation: The resultant table after the execution of the above query will be: Result of the inner query will be 225(avg(200,250)) and subsequently every such tuple which has s.sno=c.sno and cost>225 will get selected from the Cartesian product of supplier and catalogue table. Option (A) is correct.Quiz of this Question parthbanathia GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 May, 2021" }, { "code": null, "e": 118, "s": 53, "text": "Consider a relational database containing the following schemas." }, { "code": null, "e": 200, "s": 118, "text": "The primary key of each table is indicated by underlining the constituent fields." }, { "code": null, "e": 389, "s": 200, "text": "SELECT s.sno, s.sname\nFROM Suppliers s, Catalogue c\nWHERE s.sno=c.sno AND\n cost > (SELECT AVG (cost)\n FROM Catalogue\n WHERE pno = ‘P4’\n GROUP BY pno) ; " }, { "code": null, "e": 554, "s": 389, "text": "The number of rows returned by the above SQL query is(A) 4(B) 5(C) 0(D) 2Answer: (A)Explanation: The resultant table after the execution of the above query will be:" }, { "code": null, "e": 753, "s": 554, "text": "Result of the inner query will be 225(avg(200,250)) and subsequently every such tuple which has s.sno=c.sno and cost>225 will get selected from the Cartesian product of supplier and catalogue table." }, { "code": null, "e": 797, "s": 753, "text": "Option (A) is correct.Quiz of this Question" }, { "code": null, "e": 811, "s": 797, "text": "parthbanathia" }, { "code": null, "e": 816, "s": 811, "text": "GATE" } ]
Object Model in Java
28 Jan, 2022 The object model is a system or interface which is basically used to visualize elements in terms of objects in a software application. It is modeled using object-oriented techniques and before any programming or development is done, the object model is used to create a system model or an architecture. It defines object-oriented features of a system like inheritance, encapsulation, and many other object-oriented interfaces. Let us learn some of those object-oriented terminologies in-depth: These form the basis of the Object-Oriented Paradigm in Java or any other Object-Oriented Programming Languages. They are explained in detail here: In an object-oriented environment, an object is a physical or conceptual real-world element. Features: Unique and distinct from other objects in the system.State that indicates certain properties and values belonging to the particular object.Behavior that indicates its interaction with other objects or its externally visible activities. Unique and distinct from other objects in the system. State that indicates certain properties and values belonging to the particular object. Behavior that indicates its interaction with other objects or its externally visible activities. An example of a physical object is a dog or a person whereas an example of a conceptual one is a process or a product. A class is a blueprint or prototype for an object and represents a set of objects that are created from the same. Objects are basically instances of these classes. A class consists of – Objects of the same class can be different from each other in terms of values in their attributes. These attributes are known as class data. The operations which identify and display the behavior of these objects are known as functions and methods. Example: Suppose, there is a class called Student. The attributes of this class can be – Marks of the student Department in which the student studies An academic year of study Personal Identity i.e name, roll number, date of birth, etc. Some of the operations to be performed can be indicated using the following functions – averageMarks() – calculates the average marks of the student. totalMarks() – calculates the total marks of the student. libraryFine() – calculates the fine that the student needs to pay for returning books late to the library. This is demonstrated in the code below: Java // package whatever import java.io.*; public class Student { public static void main (String[] args) { // passing parameters to functions int tot = total_marks(93,99); double avg = avg_marks(tot, 2); // printing the output System.out.println("The total marks is = "+tot+". Th average is = "+avg+"."); } // function to calculate total public static int total_marks(int math, int science) { int total = math + science; return total; } // function to calculate average marks public static double avg_marks(int total, int num_subs) { double avg = total/num_subs; return avg; }} Output: The total marks is = 192. Th average is = 96.0. To protect our data from being accessed and exploited by outside usage, we need to perform encapsulation. This is explained in detail below – The process of binding methods and attributes together in a class is called encapsulation. If an interface is provided by a class, only then encapsulation allows external access to internal details or class attributes. The process by which an object is protected from direct access by external methods is called data hiding. Example: setStudentValues() – assigns values to department, academic, and all personal identities of the student. getStudentValues() – to get these values stored in the respective attributes. Message Passing A number of objects are required to make an application interactive. The message is passed between objects using the following features – In message passing, objects from different processes can be involved. Class methods need to be invoked in message passing. Between two objects, message passing is usually unidirectional. Interaction between two objects is enabled in message passing. The above example is demonstrated in the code below – Java // package whatever import java.io.*; public class Student { private int rollNo; private String name; private String dep; // default constructor public Student() {} public Student(int rollNo, String name, String dep) { this.rollNo = rollNo; this.name = name; this.dep = dep; } // Methods to get and set the student properties public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDep() { return dep; } public void setDep(String dep) { this.dep = dep; } // function to calculate total public static int totalMarks(int math, int science) { int total = math + science; return total; } // function to calculate average marks public static double avgMarks(int total, int num_subs) { double avg = total / num_subs; return avg; } public static void main(String[] args) { // setting student attributes Student s1 = new Student(23, "Deepthi", "CSE"); // setRollNo(23); // setName("Deepthi"); // setDep("CSE"); // printing student attributes System.out.println( "Roll number of student : " + s1.getRollNo() + ". The name of student : " + s1.getName() + ". Department of the student : " + s1.getDep() + "."); // passing parameters to functions int tot = totalMarks(93, 99); double avg = avgMarks(tot, 2); // printing the output System.out.println("The total marks is = " + tot + ". The average is = " + avg + "."); }} Output: Roll number of student : 23. The name of student : Deepthi. Department of the student : CSE. The total marks is = 192. The average is = 96.0. The process by which new classes are generated from existing classes by maintaining some or all of its properties is called inheritance. The original classes through which other classes can be generated are classed parent class or superclass or base class whereas the generated classes are known as derived classes or subclasses. Example: For a class Vehicle, derived classes can be a Car, Bike, Bus, etc. In this example, these derived classes are passed down the properties of their parent class Vehicle along with their own properties like the number of wheels, seats, etc. The above example is demonstrated in the following code – Java class Vehicle { String belongsTo = "automobiles";}public class Car extends Vehicle { int wheels = 4; public static void main(String args[]) { Car c = new Car(); System.out.println("Car belongs to- " + c.belongsTo); System.out.println("Car has " + c.wheels + " wheels."); }} Output: Car belongs to- automobiles Car has 4 wheels. Single inheritance – One derived class generated out of a single base class.Multiple inheritance – One derived class generated out of two or more base classes.Multilevel inheritance – One derived class is generated out of a base class which is also generated out of another base class.Hierarchical inheritance – A group of derived classes generated out of a base class which in turn might have derived classes of their own.Hybrid inheritance – A lattice structure out of a combination of multilevel and multiple inheritances. Single inheritance – One derived class generated out of a single base class. Multiple inheritance – One derived class generated out of two or more base classes. Multilevel inheritance – One derived class is generated out of a base class which is also generated out of another base class. Hierarchical inheritance – A group of derived classes generated out of a base class which in turn might have derived classes of their own. Hybrid inheritance – A lattice structure out of a combination of multilevel and multiple inheritances. The ability in which objects can have a common external interface with different internal structures. While inheritance is implemented, Polymorphism is particularly effective. In polymorphism, functions can have the same names but different parameter lists. Example: A Car and a Bus class both can have wheels() method but the number of wheels for both is different so since the internal implementation is different, no conflict arises. The representation of the hierarchy of different classes where derived classes are generated out of base classes – Generalization The combination of common characteristics from derived classes in order to form a generalized base class. Example – “A cow is a land animal”. Specialization The distinction of objects from existing classes into specialized groups is specialization. This is almost like a reverse process of generalization. The following diagram demonstrates generalization vs specialization – Link: The representation of a connection in which an object collaborates with other objects i.e the relationship between objects is called a link. Association: A set of links that identify and demonstrated the behavior between objects is called association. The instances of associations are called links. There are three types of Association: Unary relationship: Objects of the same class get connected. Binary relationship: Objects of two classes are connected. Ternary relationship: Objects of three or more classes are connected. One-to-One: One object of class A associated with an object of B. One-to-Many: One object of class A associated with more than one object of class B. Many-to-Many: More than one object of class A associated with more than one object from class B. A class can generally be made using a combination of other classes and objects. This is class composition or aggregation. The “has-a” or “part-of” of a relationship is generally the aggregate. If an object consists of other objects then this object is called an aggregate object. Example: In a student-books relationship, the student “has-a” book and the book is a “part-of” the student’s curriculum. Here the student is the complete object. An aggregate includes – Physical containment – For example, a bag consists of zips and a bottle holder. Conceptual containment – For example, a student has marks. Enable DRY (Don’t repeat yourself) way of writing code. While integrating complex systems, reduces development risks. Enables quick software development. Enables upgrades quite easily. Makes software easier to maintain. germanshephered48 Java-Object Oriented Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2022" }, { "code": null, "e": 522, "s": 28, "text": "The object model is a system or interface which is basically used to visualize elements in terms of objects in a software application. It is modeled using object-oriented techniques and before any programming or development is done, the object model is used to create a system model or an architecture. It defines object-oriented features of a system like inheritance, encapsulation, and many other object-oriented interfaces. Let us learn some of those object-oriented terminologies in-depth:" }, { "code": null, "e": 670, "s": 522, "text": "These form the basis of the Object-Oriented Paradigm in Java or any other Object-Oriented Programming Languages. They are explained in detail here:" }, { "code": null, "e": 763, "s": 670, "text": "In an object-oriented environment, an object is a physical or conceptual real-world element." }, { "code": null, "e": 773, "s": 763, "text": "Features:" }, { "code": null, "e": 1009, "s": 773, "text": "Unique and distinct from other objects in the system.State that indicates certain properties and values belonging to the particular object.Behavior that indicates its interaction with other objects or its externally visible activities." }, { "code": null, "e": 1063, "s": 1009, "text": "Unique and distinct from other objects in the system." }, { "code": null, "e": 1150, "s": 1063, "text": "State that indicates certain properties and values belonging to the particular object." }, { "code": null, "e": 1247, "s": 1150, "text": "Behavior that indicates its interaction with other objects or its externally visible activities." }, { "code": null, "e": 1366, "s": 1247, "text": "An example of a physical object is a dog or a person whereas an example of a conceptual one is a process or a product." }, { "code": null, "e": 1552, "s": 1366, "text": "A class is a blueprint or prototype for an object and represents a set of objects that are created from the same. Objects are basically instances of these classes. A class consists of –" }, { "code": null, "e": 1693, "s": 1552, "text": "Objects of the same class can be different from each other in terms of values in their attributes. These attributes are known as class data." }, { "code": null, "e": 1801, "s": 1693, "text": "The operations which identify and display the behavior of these objects are known as functions and methods." }, { "code": null, "e": 1810, "s": 1801, "text": "Example:" }, { "code": null, "e": 1890, "s": 1810, "text": "Suppose, there is a class called Student. The attributes of this class can be –" }, { "code": null, "e": 1911, "s": 1890, "text": "Marks of the student" }, { "code": null, "e": 1951, "s": 1911, "text": "Department in which the student studies" }, { "code": null, "e": 1977, "s": 1951, "text": "An academic year of study" }, { "code": null, "e": 2038, "s": 1977, "text": "Personal Identity i.e name, roll number, date of birth, etc." }, { "code": null, "e": 2126, "s": 2038, "text": "Some of the operations to be performed can be indicated using the following functions –" }, { "code": null, "e": 2188, "s": 2126, "text": "averageMarks() – calculates the average marks of the student." }, { "code": null, "e": 2246, "s": 2188, "text": "totalMarks() – calculates the total marks of the student." }, { "code": null, "e": 2353, "s": 2246, "text": "libraryFine() – calculates the fine that the student needs to pay for returning books late to the library." }, { "code": null, "e": 2393, "s": 2353, "text": "This is demonstrated in the code below:" }, { "code": null, "e": 2398, "s": 2393, "text": "Java" }, { "code": "// package whatever import java.io.*; public class Student { public static void main (String[] args) { // passing parameters to functions int tot = total_marks(93,99); double avg = avg_marks(tot, 2); // printing the output System.out.println(\"The total marks is = \"+tot+\". Th average is = \"+avg+\".\"); } // function to calculate total public static int total_marks(int math, int science) { int total = math + science; return total; } // function to calculate average marks public static double avg_marks(int total, int num_subs) { double avg = total/num_subs; return avg; }}", "e": 3041, "s": 2398, "text": null }, { "code": null, "e": 3049, "s": 3041, "text": "Output:" }, { "code": null, "e": 3097, "s": 3049, "text": "The total marks is = 192. Th average is = 96.0." }, { "code": null, "e": 3239, "s": 3097, "text": "To protect our data from being accessed and exploited by outside usage, we need to perform encapsulation. This is explained in detail below –" }, { "code": null, "e": 3459, "s": 3239, "text": "The process of binding methods and attributes together in a class is called encapsulation. If an interface is provided by a class, only then encapsulation allows external access to internal details or class attributes. " }, { "code": null, "e": 3566, "s": 3459, "text": "The process by which an object is protected from direct access by external methods is called data hiding. " }, { "code": null, "e": 3575, "s": 3566, "text": "Example:" }, { "code": null, "e": 3680, "s": 3575, "text": "setStudentValues() – assigns values to department, academic, and all personal identities of the student." }, { "code": null, "e": 3758, "s": 3680, "text": "getStudentValues() – to get these values stored in the respective attributes." }, { "code": null, "e": 3775, "s": 3758, "text": "Message Passing " }, { "code": null, "e": 3913, "s": 3775, "text": "A number of objects are required to make an application interactive. The message is passed between objects using the following features –" }, { "code": null, "e": 3983, "s": 3913, "text": "In message passing, objects from different processes can be involved." }, { "code": null, "e": 4036, "s": 3983, "text": "Class methods need to be invoked in message passing." }, { "code": null, "e": 4100, "s": 4036, "text": "Between two objects, message passing is usually unidirectional." }, { "code": null, "e": 4163, "s": 4100, "text": "Interaction between two objects is enabled in message passing." }, { "code": null, "e": 4217, "s": 4163, "text": "The above example is demonstrated in the code below –" }, { "code": null, "e": 4222, "s": 4217, "text": "Java" }, { "code": "// package whatever import java.io.*; public class Student { private int rollNo; private String name; private String dep; // default constructor public Student() {} public Student(int rollNo, String name, String dep) { this.rollNo = rollNo; this.name = name; this.dep = dep; } // Methods to get and set the student properties public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDep() { return dep; } public void setDep(String dep) { this.dep = dep; } // function to calculate total public static int totalMarks(int math, int science) { int total = math + science; return total; } // function to calculate average marks public static double avgMarks(int total, int num_subs) { double avg = total / num_subs; return avg; } public static void main(String[] args) { // setting student attributes Student s1 = new Student(23, \"Deepthi\", \"CSE\"); // setRollNo(23); // setName(\"Deepthi\"); // setDep(\"CSE\"); // printing student attributes System.out.println( \"Roll number of student : \" + s1.getRollNo() + \". The name of student : \" + s1.getName() + \". Department of the student : \" + s1.getDep() + \".\"); // passing parameters to functions int tot = totalMarks(93, 99); double avg = avgMarks(tot, 2); // printing the output System.out.println(\"The total marks is = \" + tot + \". The average is = \" + avg + \".\"); }}", "e": 6031, "s": 4222, "text": null }, { "code": null, "e": 6039, "s": 6031, "text": "Output:" }, { "code": null, "e": 6181, "s": 6039, "text": "Roll number of student : 23. The name of student : Deepthi. Department of the student : CSE.\nThe total marks is = 192. The average is = 96.0." }, { "code": null, "e": 6511, "s": 6181, "text": "The process by which new classes are generated from existing classes by maintaining some or all of its properties is called inheritance. The original classes through which other classes can be generated are classed parent class or superclass or base class whereas the generated classes are known as derived classes or subclasses." }, { "code": null, "e": 6520, "s": 6511, "text": "Example:" }, { "code": null, "e": 6816, "s": 6520, "text": "For a class Vehicle, derived classes can be a Car, Bike, Bus, etc. In this example, these derived classes are passed down the properties of their parent class Vehicle along with their own properties like the number of wheels, seats, etc. The above example is demonstrated in the following code –" }, { "code": null, "e": 6821, "s": 6816, "text": "Java" }, { "code": "class Vehicle { String belongsTo = \"automobiles\";}public class Car extends Vehicle { int wheels = 4; public static void main(String args[]) { Car c = new Car(); System.out.println(\"Car belongs to- \" + c.belongsTo); System.out.println(\"Car has \" + c.wheels + \" wheels.\"); }}", "e": 7183, "s": 6821, "text": null }, { "code": null, "e": 7191, "s": 7183, "text": "Output:" }, { "code": null, "e": 7237, "s": 7191, "text": "Car belongs to- automobiles\nCar has 4 wheels." }, { "code": null, "e": 7763, "s": 7237, "text": "Single inheritance – One derived class generated out of a single base class.Multiple inheritance – One derived class generated out of two or more base classes.Multilevel inheritance – One derived class is generated out of a base class which is also generated out of another base class.Hierarchical inheritance – A group of derived classes generated out of a base class which in turn might have derived classes of their own.Hybrid inheritance – A lattice structure out of a combination of multilevel and multiple inheritances." }, { "code": null, "e": 7840, "s": 7763, "text": "Single inheritance – One derived class generated out of a single base class." }, { "code": null, "e": 7924, "s": 7840, "text": "Multiple inheritance – One derived class generated out of two or more base classes." }, { "code": null, "e": 8051, "s": 7924, "text": "Multilevel inheritance – One derived class is generated out of a base class which is also generated out of another base class." }, { "code": null, "e": 8190, "s": 8051, "text": "Hierarchical inheritance – A group of derived classes generated out of a base class which in turn might have derived classes of their own." }, { "code": null, "e": 8293, "s": 8190, "text": "Hybrid inheritance – A lattice structure out of a combination of multilevel and multiple inheritances." }, { "code": null, "e": 8552, "s": 8293, "text": "The ability in which objects can have a common external interface with different internal structures. While inheritance is implemented, Polymorphism is particularly effective. In polymorphism, functions can have the same names but different parameter lists. " }, { "code": null, "e": 8731, "s": 8552, "text": "Example: A Car and a Bus class both can have wheels() method but the number of wheels for both is different so since the internal implementation is different, no conflict arises." }, { "code": null, "e": 8846, "s": 8731, "text": "The representation of the hierarchy of different classes where derived classes are generated out of base classes –" }, { "code": null, "e": 8861, "s": 8846, "text": "Generalization" }, { "code": null, "e": 9003, "s": 8861, "text": "The combination of common characteristics from derived classes in order to form a generalized base class. Example – “A cow is a land animal”." }, { "code": null, "e": 9018, "s": 9003, "text": "Specialization" }, { "code": null, "e": 9168, "s": 9018, "text": "The distinction of objects from existing classes into specialized groups is specialization. This is almost like a reverse process of generalization. " }, { "code": null, "e": 9238, "s": 9168, "text": "The following diagram demonstrates generalization vs specialization –" }, { "code": null, "e": 9385, "s": 9238, "text": "Link: The representation of a connection in which an object collaborates with other objects i.e the relationship between objects is called a link." }, { "code": null, "e": 9544, "s": 9385, "text": "Association: A set of links that identify and demonstrated the behavior between objects is called association. The instances of associations are called links." }, { "code": null, "e": 9582, "s": 9544, "text": "There are three types of Association:" }, { "code": null, "e": 9643, "s": 9582, "text": "Unary relationship: Objects of the same class get connected." }, { "code": null, "e": 9702, "s": 9643, "text": "Binary relationship: Objects of two classes are connected." }, { "code": null, "e": 9772, "s": 9702, "text": "Ternary relationship: Objects of three or more classes are connected." }, { "code": null, "e": 9838, "s": 9772, "text": "One-to-One: One object of class A associated with an object of B." }, { "code": null, "e": 9922, "s": 9838, "text": "One-to-Many: One object of class A associated with more than one object of class B." }, { "code": null, "e": 10019, "s": 9922, "text": "Many-to-Many: More than one object of class A associated with more than one object from class B." }, { "code": null, "e": 10300, "s": 10019, "text": "A class can generally be made using a combination of other classes and objects. This is class composition or aggregation. The “has-a” or “part-of” of a relationship is generally the aggregate. If an object consists of other objects then this object is called an aggregate object." }, { "code": null, "e": 10309, "s": 10300, "text": "Example:" }, { "code": null, "e": 10486, "s": 10309, "text": "In a student-books relationship, the student “has-a” book and the book is a “part-of” the student’s curriculum. Here the student is the complete object. An aggregate includes –" }, { "code": null, "e": 10566, "s": 10486, "text": "Physical containment – For example, a bag consists of zips and a bottle holder." }, { "code": null, "e": 10625, "s": 10566, "text": "Conceptual containment – For example, a student has marks." }, { "code": null, "e": 10681, "s": 10625, "text": "Enable DRY (Don’t repeat yourself) way of writing code." }, { "code": null, "e": 10743, "s": 10681, "text": "While integrating complex systems, reduces development risks." }, { "code": null, "e": 10779, "s": 10743, "text": "Enables quick software development." }, { "code": null, "e": 10810, "s": 10779, "text": "Enables upgrades quite easily." }, { "code": null, "e": 10845, "s": 10810, "text": "Makes software easier to maintain." }, { "code": null, "e": 10863, "s": 10845, "text": "germanshephered48" }, { "code": null, "e": 10884, "s": 10863, "text": "Java-Object Oriented" }, { "code": null, "e": 10891, "s": 10884, "text": "Picked" }, { "code": null, "e": 10896, "s": 10891, "text": "Java" }, { "code": null, "e": 10901, "s": 10896, "text": "Java" }, { "code": null, "e": 10999, "s": 10901, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11014, "s": 10999, "text": "Stream In Java" }, { "code": null, "e": 11035, "s": 11014, "text": "Introduction to Java" }, { "code": null, "e": 11056, "s": 11035, "text": "Constructors in Java" }, { "code": null, "e": 11075, "s": 11056, "text": "Exceptions in Java" }, { "code": null, "e": 11092, "s": 11075, "text": "Generics in Java" }, { "code": null, "e": 11122, "s": 11092, "text": "Functional Interfaces in Java" }, { "code": null, "e": 11148, "s": 11122, "text": "Java Programming Examples" }, { "code": null, "e": 11164, "s": 11148, "text": "Strings in Java" }, { "code": null, "e": 11201, "s": 11164, "text": "Differences between JDK, JRE and JVM" } ]
PHP program to print the number pattern
To print the number pattern in PHP, the code is as follows − Live Demo <?php function num_pattern($val) { $num = 1; for ($m = 0; $m < $val; $m++) { for ($n = 0; $n <= $m; $n++ ) { echo $num." "; } $num = $num + 1; echo "\n"; } } $val = 6; num_pattern($val); ?> 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 This is similar to generating a star pattern, the only difference being, numbers are generated instead of stars. The function ‘num_pattern’ is defined that takes the limit as a parameter. The limit value is iterated over and the number is printed and relevant line breaks are also generated in between. The function is called by passing this limit value and the relevant output is generated on the console.
[ { "code": null, "e": 1248, "s": 1187, "text": "To print the number pattern in PHP, the code is as follows −" }, { "code": null, "e": 1259, "s": 1248, "text": " Live Demo" }, { "code": null, "e": 1500, "s": 1259, "text": "<?php\nfunction num_pattern($val)\n{\n $num = 1;\n for ($m = 0; $m < $val; $m++)\n {\n for ($n = 0; $n <= $m; $n++ )\n {\n echo $num.\" \";\n }\n $num = $num + 1;\n echo \"\\n\";\n }\n}\n$val = 6;\nnum_pattern($val);\n?>" }, { "code": null, "e": 1542, "s": 1500, "text": "1\n2 2\n3 3 3\n4 4 4 4\n5 5 5 5 5\n6 6 6 6 6 6" }, { "code": null, "e": 1949, "s": 1542, "text": "This is similar to generating a star pattern, the only difference being, numbers are generated instead of stars. The function ‘num_pattern’ is defined that takes the limit as a parameter. The limit value is iterated over and the number is printed and relevant line breaks are also generated in between. The function is called by passing this limit value and the relevant output is generated on the console." } ]
Pairwise Software Testing
20 Jun, 2019 Pairwise Testing is a type of software testing in which permutation and combination method is used to test the software. Pairwise testing is used to test all the possible discrete combinations of the parameters involved. Pairwise testing is a P&C based method, in which to test a system or an application, for each pair of input parameters of a system, all possible discrete combinations of the parameters are tested. By using the conventional or exhaustive testing approach it may be hard to test the system but by using the permutation and combination method it can be easily done. Example:Suppose there is a software to be tested which has 20 inputs and 20 possible settings for each input so in that case there are total 20^20 possible inputs to be tested. Therefore in this case, exhaustive testing is impossible even all combinations are tried to be tested. Graphical Representation of Pairwise Testing: Generalized form of Pairwise Testing:The generalized form of pairwise testing is N-wise testing. Basically sorting is applied to the set, X = n{i}, so that P = P{i} gets ordered too. Let the sorted set be a N tuple: P{s} = { P{i} } ; i |R(P{i})| < |R(P{j})| Now take the set X(2) = { P{N-1}, P{N-2} } And call it the pairwise testing. Generalizing further take the set X(3) = { P{N-1}, P{N-2}, P{N-3} } And call it the 3-wise testing. Similarly, we can say, X(K) = { P{N-1}, P{N-2}, ..., P{N-K} } K-wise testing.The N-wise testing is all possible combinations from the above formula. Advantages of Pairwise Testing:The advantages of pairwise testing are: Pairwise testing reduces the number of execution of test cases. Pairwise testing increases the test coverage almost up to hundred percentage. Pairwise testing increases the defect detection ratio. Pairwise testing takes less time to complete the execution of the test suite. Pairwise testing reduces the overall testing budget for a project. Disadvantages of Pairwise Testing:The disadvantages of pairwise testing are: Pairwise testing is not beneficial if the values of the variables are inappropriate. In pairwise testing it is possible to miss the highly probable combination while selecting the test data. In pairwise testing, defect yield ratio may be reduced if a combination is missed. Pairwise testing is not useful if combinations of variables are not understood correctly. Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2019" }, { "code": null, "e": 249, "s": 28, "text": "Pairwise Testing is a type of software testing in which permutation and combination method is used to test the software. Pairwise testing is used to test all the possible discrete combinations of the parameters involved." }, { "code": null, "e": 612, "s": 249, "text": "Pairwise testing is a P&C based method, in which to test a system or an application, for each pair of input parameters of a system, all possible discrete combinations of the parameters are tested. By using the conventional or exhaustive testing approach it may be hard to test the system but by using the permutation and combination method it can be easily done." }, { "code": null, "e": 892, "s": 612, "text": "Example:Suppose there is a software to be tested which has 20 inputs and 20 possible settings for each input so in that case there are total 20^20 possible inputs to be tested. Therefore in this case, exhaustive testing is impossible even all combinations are tried to be tested." }, { "code": null, "e": 938, "s": 892, "text": "Graphical Representation of Pairwise Testing:" }, { "code": null, "e": 1076, "s": 938, "text": "Generalized form of Pairwise Testing:The generalized form of pairwise testing is N-wise testing. Basically sorting is applied to the set," }, { "code": null, "e": 1123, "s": 1076, "text": "X = n{i}, \nso that P = P{i} gets ordered too. " }, { "code": null, "e": 1156, "s": 1123, "text": "Let the sorted set be a N tuple:" }, { "code": null, "e": 1244, "s": 1156, "text": "P{s} = { P{i} } ; i |R(P{i})| < |R(P{j})|\nNow take the set X(2) = { P{N-1}, P{N-2} } " }, { "code": null, "e": 1312, "s": 1244, "text": "And call it the pairwise testing. Generalizing further take the set" }, { "code": null, "e": 1346, "s": 1312, "text": "X(3) = { P{N-1}, P{N-2}, P{N-3} }" }, { "code": null, "e": 1401, "s": 1346, "text": "And call it the 3-wise testing. Similarly, we can say," }, { "code": null, "e": 1441, "s": 1401, "text": "X(K) = { P{N-1}, P{N-2}, ..., P{N-K} } " }, { "code": null, "e": 1528, "s": 1441, "text": "K-wise testing.The N-wise testing is all possible combinations from the above formula." }, { "code": null, "e": 1599, "s": 1528, "text": "Advantages of Pairwise Testing:The advantages of pairwise testing are:" }, { "code": null, "e": 1663, "s": 1599, "text": "Pairwise testing reduces the number of execution of test cases." }, { "code": null, "e": 1741, "s": 1663, "text": "Pairwise testing increases the test coverage almost up to hundred percentage." }, { "code": null, "e": 1796, "s": 1741, "text": "Pairwise testing increases the defect detection ratio." }, { "code": null, "e": 1874, "s": 1796, "text": "Pairwise testing takes less time to complete the execution of the test suite." }, { "code": null, "e": 1941, "s": 1874, "text": "Pairwise testing reduces the overall testing budget for a project." }, { "code": null, "e": 2018, "s": 1941, "text": "Disadvantages of Pairwise Testing:The disadvantages of pairwise testing are:" }, { "code": null, "e": 2103, "s": 2018, "text": "Pairwise testing is not beneficial if the values of the variables are inappropriate." }, { "code": null, "e": 2209, "s": 2103, "text": "In pairwise testing it is possible to miss the highly probable combination while selecting the test data." }, { "code": null, "e": 2292, "s": 2209, "text": "In pairwise testing, defect yield ratio may be reduced if a combination is missed." }, { "code": null, "e": 2382, "s": 2292, "text": "Pairwise testing is not useful if combinations of variables are not understood correctly." }, { "code": null, "e": 2399, "s": 2382, "text": "Software Testing" }, { "code": null, "e": 2420, "s": 2399, "text": "Software Engineering" } ]
Modify the default font in Python Tkinter
In order to change the default behavior of tkinter widgets, we generally override the option_add() method. The properties and values passed to option_add() method will reflect the changes in all the widgets in the application. Thus, changing the default font will affect the font for all the widgets defined in the application. Here we will pass two parameters into the option_add() method, i.e., option_add("*font", "font-family font-size font-style font-orientation"). #Import the required libraries from tkinter import * #Create an instance of tkinter frame win= Tk() #Set the geometry of frame win.geometry("600x400") #Change the default Font that will affect in all the widgets win.option_add( "*font", "lucida 20 bold italic" ) win.resizable(False, False) #Create a Label Label(win, text="This is a New Line").pack() Button(win, text="Button-1", width=10).pack() win.mainloop() Running the above code will set the default font as "lucida 20 bold italic" for all the widgets that uses textual information. Now, go back to the program, remove the following line, and run it again. win.option_add( "*font", "lucida 20 bold italic" ) The text will now appear in the default font −
[ { "code": null, "e": 1515, "s": 1187, "text": "In order to change the default behavior of tkinter widgets, we generally override the option_add() method. The properties and values passed to option_add() method will reflect the changes in all the widgets in the application. Thus, changing the default font will affect the font for all the widgets defined in the application." }, { "code": null, "e": 1658, "s": 1515, "text": "Here we will pass two parameters into the option_add() method, i.e., option_add(\"*font\", \"font-family font-size font-style font-orientation\")." }, { "code": null, "e": 2076, "s": 1658, "text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry of frame\nwin.geometry(\"600x400\")\n\n#Change the default Font that will affect in all the widgets\nwin.option_add( \"*font\", \"lucida 20 bold italic\" )\nwin.resizable(False, False)\n\n#Create a Label\nLabel(win, text=\"This is a New Line\").pack()\nButton(win, text=\"Button-1\", width=10).pack()\n\nwin.mainloop()" }, { "code": null, "e": 2203, "s": 2076, "text": "Running the above code will set the default font as \"lucida 20 bold italic\" for all the widgets that uses textual information." }, { "code": null, "e": 2277, "s": 2203, "text": "Now, go back to the program, remove the following line, and run it again." }, { "code": null, "e": 2328, "s": 2277, "text": "win.option_add( \"*font\", \"lucida 20 bold italic\" )" }, { "code": null, "e": 2375, "s": 2328, "text": "The text will now appear in the default font −" } ]
Mastermind Game using Python
11 Nov, 2019 Given the present generation’s acquaintance with gaming and its highly demanded technology, many aspire to pursue the idea of developing and advancing it further. Eventually, everyone starts at the beginning. Mastermind is an old code-breaking game played by two players. The game goes back to the 19th century and can be played with paper and pencil. Prerequisite:Random Numbers in Python Two players play the game against each other; let’s assume Player 1 and Player 2. Player 1 plays first by setting a multi-digit number. Player 2 now tries his first attempt at guessing the number. If Player 2 succeeds in his first attempt (despite odds which are highly unlikely) he wins the game and is crowned Mastermind! If not, then Player 1 hints by revealing which digits or numbers Player 2 got correct. The game continues till Player 2 eventually is able to guess the number entirely. Now, Player 2 gets to set the number and Player 1 plays the part of guessing the number. If Player 1 is able to guess the number within a lesser number of tries than Player 2 took, then Player 1 wins the game and is crowned Mastermind. If not, then Player 2 wins the game. The real game, however, has proved aesthetics since the numbers are represented by color-coded buttons. For example:Input: Player 1, set the number: 5672 Player 2, guess the number: 1472 Output: Not quite the number. You did get 2 digits correct. X X 7 2 Enter your next choice of numbers: We shall not be using any of the Pygame Libraries, to aid us with additional graphics, and therefore shall be dealing only with the framework and concept. Furthermore, we are going to be playing against the Computer i.e, the Computer would generate the number to be guessed. Below is the implementation of the above idea. import random # the .randrange() function generates a# random number within the specified range.num = random.randrange(1000, 10000) n = int(input("Guess the 4 digit number:")) # condition to test equality of the# guess made. Program terminates if true.if (n == num): print("Great! You guessed the number in just 1 try! You're a Mastermind!")else: # ctr variable initialized. It will keep count of # the number of tries the Player takes to guess the number. ctr = 0 # while loop repeats as long as the # Player fails to guess the number correctly. while (n != num): # variable increments every time the loop # is executed, giving an idea of how many # guesses were made. ctr += 1 count = 0 # explicit type conversion of an integer to # a string in order to ease extraction of digits n = str(n) # explicit type conversion of a string to an integer num = str(num) # correct[] list stores digits which are correct correct = ['X']*4 # for loop runs 4 times since the number has 4 digits. for i in range(0, 4): # checking for equality of digits if (n[i] == num[i]): # number of digits guessed correctly increments count += 1 # hence, the digit is stored in correct[]. correct[i] = n[i] else: continue # when not all the digits are guessed correctly. if (count < 4) and (count != 0): print("Not quite the number. But you did get ", count, " digit(s) correct!") print("Also these numbers in your input were correct.") for k in correct: print(k, end=' ') print('\n') print('\n') n = int(input("Enter your next choice of numbers: ")) # when none of the digits are guessed correctly. elif (count == 0): print("None of the numbers in your input match.") n = int(input("Enter your next choice of numbers: ")) # condition for equality. if n == num: print("You've become a Mastermind!") print("It took you only", ctr, "tries.") Let’s suppose the number set by computer is 1564 Output: Guess the 4 digit number: 1564 Great! You guessed the number in just 1 try! You're a Mastermind! If the number is not guessed in one chance. Output: Guess the 4 digit number: 2164 Not quite the number. But you did get 2 digit(s) correct! Also these numbers in your input were correct. X X 6 4 Enter your next choice of numbers: 3564 Not quite the number. But you did get 2 digit(s) correct! Also these numbers in your input were correct. X 5 6 4 Enter your next choice of numbers: 1564 You've become a Mastermind. It took you only 3 tries. You can make the game harder by either increasing the number of digits of the input or by not disclosing which numbers in the input were correctly placed.This has been explained in the code below. import random #the .randrange() function generates# a random number within the specified range.num = random.randrange(1000,10000) n = int(input("Guess the 4 digit number:")) # condition to test equality of the # guess made. Program terminates if true.if(n == num): print("Great! You guessed the number in just 1 try! You're a Mastermind!")else: # ctr variable initialized. It will keep count of # the number of tries the Player takes to guess the number. ctr = 0 # while loop repeats as long as the Player # fails to guess the number correctly. while(n!=num): # variable increments every time the loop # is executed, giving an idea of how many # guesses were made. ctr += 1 count = 0 # explicit type conversion of an integer to # a string in order to ease extraction of digits n = str(n) # explicit type conversion of a string to an integer num = str(num) # correct[] list stores digits which are correct correct=[] # for loop runs 4 times since the number has 4 digits. for i in range(0,4): # checking for equality of digits if(n[i] == num[i]): # number of digits guessed correctly increments count += 1 # hence, the digit is stored in correct[]. correct.append(n[i]) else: continue # when not all the digits are guessed correctly. if (count < 4) and (count != 0): print("Not quite the number. But you did get ",count," digit(s) correct!") print("Also these numbers in your input were correct.") for k in correct: print(k, end=' ') print('\n') print('\n') n = int(input("Enter your next choice of numbers: ")) # when none of the digits are guessed correctly. elif(count == 0): print("None of the numbers in your input match.") n=int(input("Enter your next choice of numbers: ")) if n==num: print("You've become a Mastermind!") print("It took you only",ctr,"tries.") Suppose the number set by computer is 54876. Output: Guess the 5 digit number: 38476 Not quite the number. But you did get 2 digit(s) correct! Enter your next choice of numbers: 41876 Not quite the number. But you did get 4 digit(s) correct! Enter the next choice of numbers: 54876 Great you've become a Mastermind! It took you only 3 tries! The entire scope of modifying this code is massive. The idea here is to get a sense of what the concept is. There are plenty of games such as this one which relies on similar basic code. By utilizing this code, developing it further while incorporating libraries from Pygame, would make it more like the real deal, not to mention much more involving! python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Nov, 2019" }, { "code": null, "e": 406, "s": 54, "text": "Given the present generation’s acquaintance with gaming and its highly demanded technology, many aspire to pursue the idea of developing and advancing it further. Eventually, everyone starts at the beginning. Mastermind is an old code-breaking game played by two players. The game goes back to the 19th century and can be played with paper and pencil." }, { "code": null, "e": 444, "s": 406, "text": "Prerequisite:Random Numbers in Python" }, { "code": null, "e": 526, "s": 444, "text": "Two players play the game against each other; let’s assume Player 1 and Player 2." }, { "code": null, "e": 580, "s": 526, "text": "Player 1 plays first by setting a multi-digit number." }, { "code": null, "e": 641, "s": 580, "text": "Player 2 now tries his first attempt at guessing the number." }, { "code": null, "e": 855, "s": 641, "text": "If Player 2 succeeds in his first attempt (despite odds which are highly unlikely) he wins the game and is crowned Mastermind! If not, then Player 1 hints by revealing which digits or numbers Player 2 got correct." }, { "code": null, "e": 937, "s": 855, "text": "The game continues till Player 2 eventually is able to guess the number entirely." }, { "code": null, "e": 1026, "s": 937, "text": "Now, Player 2 gets to set the number and Player 1 plays the part of guessing the number." }, { "code": null, "e": 1173, "s": 1026, "text": "If Player 1 is able to guess the number within a lesser number of tries than Player 2 took, then Player 1 wins the game and is crowned Mastermind." }, { "code": null, "e": 1210, "s": 1173, "text": "If not, then Player 2 wins the game." }, { "code": null, "e": 1314, "s": 1210, "text": "The real game, however, has proved aesthetics since the numbers are represented by color-coded buttons." }, { "code": null, "e": 1333, "s": 1314, "text": "For example:Input:" }, { "code": null, "e": 1398, "s": 1333, "text": "Player 1, set the number: 5672\nPlayer 2, guess the number: 1472\n" }, { "code": null, "e": 1406, "s": 1398, "text": "Output:" }, { "code": null, "e": 1503, "s": 1406, "text": "Not quite the number. You did get 2 digits correct.\nX X 7 2\n\nEnter your next choice of numbers:\n" }, { "code": null, "e": 1778, "s": 1503, "text": "We shall not be using any of the Pygame Libraries, to aid us with additional graphics, and therefore shall be dealing only with the framework and concept. Furthermore, we are going to be playing against the Computer i.e, the Computer would generate the number to be guessed." }, { "code": null, "e": 1825, "s": 1778, "text": "Below is the implementation of the above idea." }, { "code": "import random # the .randrange() function generates a# random number within the specified range.num = random.randrange(1000, 10000) n = int(input(\"Guess the 4 digit number:\")) # condition to test equality of the# guess made. Program terminates if true.if (n == num): print(\"Great! You guessed the number in just 1 try! You're a Mastermind!\")else: # ctr variable initialized. It will keep count of # the number of tries the Player takes to guess the number. ctr = 0 # while loop repeats as long as the # Player fails to guess the number correctly. while (n != num): # variable increments every time the loop # is executed, giving an idea of how many # guesses were made. ctr += 1 count = 0 # explicit type conversion of an integer to # a string in order to ease extraction of digits n = str(n) # explicit type conversion of a string to an integer num = str(num) # correct[] list stores digits which are correct correct = ['X']*4 # for loop runs 4 times since the number has 4 digits. for i in range(0, 4): # checking for equality of digits if (n[i] == num[i]): # number of digits guessed correctly increments count += 1 # hence, the digit is stored in correct[]. correct[i] = n[i] else: continue # when not all the digits are guessed correctly. if (count < 4) and (count != 0): print(\"Not quite the number. But you did get \", count, \" digit(s) correct!\") print(\"Also these numbers in your input were correct.\") for k in correct: print(k, end=' ') print('\\n') print('\\n') n = int(input(\"Enter your next choice of numbers: \")) # when none of the digits are guessed correctly. elif (count == 0): print(\"None of the numbers in your input match.\") n = int(input(\"Enter your next choice of numbers: \")) # condition for equality. if n == num: print(\"You've become a Mastermind!\") print(\"It took you only\", ctr, \"tries.\")", "e": 4073, "s": 1825, "text": null }, { "code": null, "e": 4122, "s": 4073, "text": "Let’s suppose the number set by computer is 1564" }, { "code": null, "e": 4130, "s": 4122, "text": "Output:" }, { "code": null, "e": 4229, "s": 4130, "text": "Guess the 4 digit number: 1564\n\nGreat! You guessed the number in just 1 try! You're a Mastermind!\n" }, { "code": null, "e": 4273, "s": 4229, "text": "If the number is not guessed in one chance." }, { "code": null, "e": 4281, "s": 4273, "text": "Output:" }, { "code": null, "e": 4680, "s": 4281, "text": "Guess the 4 digit number: 2164 \n\nNot quite the number. But you did get 2 digit(s) correct!\nAlso these numbers in your input were correct.\nX X 6 4\n\nEnter your next choice of numbers: 3564\nNot quite the number. But you did get 2 digit(s) correct!\nAlso these numbers in your input were correct.\nX 5 6 4\n\nEnter your next choice of numbers: 1564\nYou've become a Mastermind.\nIt took you only 3 tries.\n" }, { "code": null, "e": 4877, "s": 4680, "text": "You can make the game harder by either increasing the number of digits of the input or by not disclosing which numbers in the input were correctly placed.This has been explained in the code below." }, { "code": "import random #the .randrange() function generates# a random number within the specified range.num = random.randrange(1000,10000) n = int(input(\"Guess the 4 digit number:\")) # condition to test equality of the # guess made. Program terminates if true.if(n == num): print(\"Great! You guessed the number in just 1 try! You're a Mastermind!\")else: # ctr variable initialized. It will keep count of # the number of tries the Player takes to guess the number. ctr = 0 # while loop repeats as long as the Player # fails to guess the number correctly. while(n!=num): # variable increments every time the loop # is executed, giving an idea of how many # guesses were made. ctr += 1 count = 0 # explicit type conversion of an integer to # a string in order to ease extraction of digits n = str(n) # explicit type conversion of a string to an integer num = str(num) # correct[] list stores digits which are correct correct=[] # for loop runs 4 times since the number has 4 digits. for i in range(0,4): # checking for equality of digits if(n[i] == num[i]): # number of digits guessed correctly increments count += 1 # hence, the digit is stored in correct[]. correct.append(n[i]) else: continue # when not all the digits are guessed correctly. if (count < 4) and (count != 0): print(\"Not quite the number. But you did get \",count,\" digit(s) correct!\") print(\"Also these numbers in your input were correct.\") for k in correct: print(k, end=' ') print('\\n') print('\\n') n = int(input(\"Enter your next choice of numbers: \")) # when none of the digits are guessed correctly. elif(count == 0): print(\"None of the numbers in your input match.\") n=int(input(\"Enter your next choice of numbers: \")) if n==num: print(\"You've become a Mastermind!\") print(\"It took you only\",ctr,\"tries.\") ", "e": 7342, "s": 4877, "text": null }, { "code": null, "e": 7387, "s": 7342, "text": "Suppose the number set by computer is 54876." }, { "code": null, "e": 7395, "s": 7387, "text": "Output:" }, { "code": null, "e": 7689, "s": 7395, "text": "Guess the 5 digit number: 38476\n\nNot quite the number. But you did get 2 digit(s) correct! \nEnter your next choice of numbers: 41876\n\nNot quite the number. But you did get 4 digit(s) correct!\nEnter the next choice of numbers: 54876\n\nGreat you've become a Mastermind!\nIt took you only 3 tries!\n" }, { "code": null, "e": 7876, "s": 7689, "text": "The entire scope of modifying this code is massive. The idea here is to get a sense of what the concept is. There are plenty of games such as this one which relies on similar basic code." }, { "code": null, "e": 8040, "s": 7876, "text": "By utilizing this code, developing it further while incorporating libraries from Pygame, would make it more like the real deal, not to mention much more involving!" }, { "code": null, "e": 8055, "s": 8040, "text": "python-utility" }, { "code": null, "e": 8062, "s": 8055, "text": "Python" }, { "code": null, "e": 8160, "s": 8062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8192, "s": 8160, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 8219, "s": 8192, "text": "Python Classes and Objects" }, { "code": null, "e": 8240, "s": 8219, "text": "Python OOPs Concepts" }, { "code": null, "e": 8263, "s": 8240, "text": "Introduction To PYTHON" }, { "code": null, "e": 8319, "s": 8263, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 8350, "s": 8319, "text": "Python | os.path.join() method" }, { "code": null, "e": 8392, "s": 8350, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 8434, "s": 8392, "text": "Check if element exists in list in Python" }, { "code": null, "e": 8473, "s": 8434, "text": "Python | datetime.timedelta() function" } ]
MySQL | AES_ENCRYPT ( ) Function
25 Aug, 2021 The MySQL AES_ENCRYPT function is used for encrypting a string using Advanced Encryption Standard (AES) algorithm. The MySQL AES_ENCRYPT function encodes the data with 128 bits key length but it can be extended up to 256 bits key length. It encrypts a string and returns a binary string. The value returned by the AES_ENCRYPT function is a binary string or NULL if the argument in NULL. The AES_ENCRYPT function accepts two parameters which are the encrypted string and a key string used to encrypt the string. Syntax: AES_ENCRYPT(str, key_str) Parameters Used: str – It is used to specify the plain string. key_str – It is used to specify the String which is used to encrypt the str. Return Value: The AES_ENCRYPT function in MySQL returns a binary string. Supported Versions of MySQL: MySQL 5.7 MySQL 5.6 MySQL 5.5 MySQL 5.1 MySQL 5.0 MySQL 4.1 Example-1: Implementing AES_ENCRYPT function on a string. SELECT AES_ENCRYPT('ABC', 'key'); Output: \\YJ??f&K?M?q?* Example-2: Implementing AES_ENCRYPT function on a bigger string. SELECT AES_ENCRYPT('geeksforgeeks', 'key'); Output: 2G???B?????*?? Example-3: Implementing AES_ENCRYPT function on a NULL string. SELECT (AES_ENCRYPT(NULL, 'key'); Output: NULL abhishek0719kadiyan mysql SQLmysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL MySQL | Group_CONCAT() Function Window functions in SQL SQL Correlated Subqueries Difference between DELETE and TRUNCATE SQL | Sub queries in From Clause MySQL | Regular expressions (Regexp)
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2021" }, { "code": null, "e": 317, "s": 28, "text": "The MySQL AES_ENCRYPT function is used for encrypting a string using Advanced Encryption Standard (AES) algorithm. The MySQL AES_ENCRYPT function encodes the data with 128 bits key length but it can be extended up to 256 bits key length. It encrypts a string and returns a binary string. " }, { "code": null, "e": 541, "s": 317, "text": "The value returned by the AES_ENCRYPT function is a binary string or NULL if the argument in NULL. The AES_ENCRYPT function accepts two parameters which are the encrypted string and a key string used to encrypt the string. " }, { "code": null, "e": 551, "s": 541, "text": "Syntax: " }, { "code": null, "e": 577, "s": 551, "text": "AES_ENCRYPT(str, key_str)" }, { "code": null, "e": 596, "s": 577, "text": "Parameters Used: " }, { "code": null, "e": 642, "s": 596, "text": "str – It is used to specify the plain string." }, { "code": null, "e": 719, "s": 642, "text": "key_str – It is used to specify the String which is used to encrypt the str." }, { "code": null, "e": 793, "s": 719, "text": "Return Value: The AES_ENCRYPT function in MySQL returns a binary string. " }, { "code": null, "e": 824, "s": 793, "text": "Supported Versions of MySQL: " }, { "code": null, "e": 834, "s": 824, "text": "MySQL 5.7" }, { "code": null, "e": 844, "s": 834, "text": "MySQL 5.6" }, { "code": null, "e": 854, "s": 844, "text": "MySQL 5.5" }, { "code": null, "e": 864, "s": 854, "text": "MySQL 5.1" }, { "code": null, "e": 874, "s": 864, "text": "MySQL 5.0" }, { "code": null, "e": 884, "s": 874, "text": "MySQL 4.1" }, { "code": null, "e": 944, "s": 884, "text": "Example-1: Implementing AES_ENCRYPT function on a string. " }, { "code": null, "e": 979, "s": 944, "text": "SELECT\nAES_ENCRYPT('ABC', 'key'); " }, { "code": null, "e": 989, "s": 979, "text": "Output: " }, { "code": null, "e": 1006, "s": 989, "text": "\\\\YJ??f&K?M?q?* " }, { "code": null, "e": 1073, "s": 1006, "text": "Example-2: Implementing AES_ENCRYPT function on a bigger string. " }, { "code": null, "e": 1119, "s": 1073, "text": "SELECT \nAES_ENCRYPT('geeksforgeeks', 'key'); " }, { "code": null, "e": 1129, "s": 1119, "text": "Output: " }, { "code": null, "e": 1145, "s": 1129, "text": "2G???B?????*?? " }, { "code": null, "e": 1210, "s": 1145, "text": "Example-3: Implementing AES_ENCRYPT function on a NULL string. " }, { "code": null, "e": 1247, "s": 1210, "text": "SELECT \n(AES_ENCRYPT(NULL, 'key'); " }, { "code": null, "e": 1256, "s": 1247, "text": "Output: " }, { "code": null, "e": 1262, "s": 1256, "text": "NULL " }, { "code": null, "e": 1282, "s": 1262, "text": "abhishek0719kadiyan" }, { "code": null, "e": 1288, "s": 1282, "text": "mysql" }, { "code": null, "e": 1297, "s": 1288, "text": "SQLmysql" }, { "code": null, "e": 1301, "s": 1297, "text": "SQL" }, { "code": null, "e": 1305, "s": 1301, "text": "SQL" }, { "code": null, "e": 1403, "s": 1305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1414, "s": 1403, "text": "CTE in SQL" }, { "code": null, "e": 1480, "s": 1414, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1525, "s": 1480, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1558, "s": 1525, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 1590, "s": 1558, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1614, "s": 1590, "text": "Window functions in SQL" }, { "code": null, "e": 1640, "s": 1614, "text": "SQL Correlated Subqueries" }, { "code": null, "e": 1679, "s": 1640, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 1712, "s": 1679, "text": "SQL | Sub queries in From Clause" } ]
ASP.NET Core - Middleware
In this chapter, we will understand how to set up middleware. Middleware in ASP.NET Core controls how our application responds to HTTP requests. It can also control how our application looks when there is an error, and it is a key piece in how we authenticate and authorize a user to perform specific actions. Middleware are software components that are assembled into an application pipeline to handle requests and responses. Middleware are software components that are assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline. Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline. Request delegates are used to build the request pipeline. The request delegates handle each HTTP request. Request delegates are used to build the request pipeline. The request delegates handle each HTTP request. Each piece of middleware in ASP.NET Core is an object, and each piece has a very specific, focused, and limited role. Each piece of middleware in ASP.NET Core is an object, and each piece has a very specific, focused, and limited role. Ultimately, we need many pieces of middleware for an application to behave appropriately. Ultimately, we need many pieces of middleware for an application to behave appropriately. Let us now assume that we want to log information about every request into our application. In that case, the first piece of middleware that we might install into the application is a logging component. In that case, the first piece of middleware that we might install into the application is a logging component. This logger can see everything about the incoming request, but chances are a logger is simply going to record some information and then pass along this request to the next piece of middleware. This logger can see everything about the incoming request, but chances are a logger is simply going to record some information and then pass along this request to the next piece of middleware. Middleware is a series of components present in this processing pipeline. Middleware is a series of components present in this processing pipeline. The next piece of middleware that we've installed into the application is an authorizer. The next piece of middleware that we've installed into the application is an authorizer. An authorizer might be looking for specific cookie or access tokens in the HTTP headers. An authorizer might be looking for specific cookie or access tokens in the HTTP headers. If the authorizer finds a token, it allows the request to proceed. If not, perhaps the authorizer itself will respond to the request with an HTTP error code or redirect code to send the user to a login page. If the authorizer finds a token, it allows the request to proceed. If not, perhaps the authorizer itself will respond to the request with an HTTP error code or redirect code to send the user to a login page. But, otherwise, the authorizer will pass the request to the next piece of middleware which is a router. But, otherwise, the authorizer will pass the request to the next piece of middleware which is a router. A router looks at the URL and determines your next step of action. A router looks at the URL and determines your next step of action. The router looks over the application for something to respond to and if the router doesn't find anything to respond to, the router itself might return a 404 Not Found error. The router looks over the application for something to respond to and if the router doesn't find anything to respond to, the router itself might return a 404 Not Found error. Let us now take a simple example to understand more about middleware. We set up the middleware in ASP.NET using the Configure method of our Startup class. using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace FirstAppDemo { public class Startup { public Startup() { var builder = new ConfigurationBuilder() .AddJsonFile("AppSettings.json"); Configuration = builder.Build(); } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. // Use this method to add services to the container. // For more information on how to configure your application, // visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } } Inside the Configure() method, we will invoke the extension methods on the IApplicationBuilder interface to add middleware. There are two pieces of middleware in a new empty project by default − IISPlatformHandler Middleware registered with app.Run IISPlatformHandler allows us to work with Windows authentication. It will look at every incoming request and see if there is any Windows identity information associated with that request and then it calls the next piece of middleware. The next piece of middleware in this case is a piece of middleware registered with app.Run. The Run method allows us to pass in another method, which we can use to process every single response. Run is not something that you will see very often, it is something that we call a terminal piece of middleware. Middleware that you register with Run will never have the opportunity to call another piece of middleware, all it does is receive a request, and then it has to produce some sort of response. You also get access to a Response object and one of the things you can do with a Response object is to write a string. If you want to register another piece of middleware after app.Run, that piece of middleware would never be called because, again, Run is a terminal piece of middleware. It will never call into the next piece of middleware. Let us proceed with the following steps to add another middleware − Step 1 − To add another middleware, right-click on project and select Manage NuGet Packages. Step 2 − Search for Microsoft.aspnet.diagnostics that is actually ASP.NET Core middleware for exception handling, exception display pages, and diagnostics information. This particular package contains many different pieces of middleware that we can use. Step 3 − Install that package if it is not installed in your project. Step 4 − Let us now go to the Configure() method and invoke app.UseWelcomePage middleware. // This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseWelcomePage(); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); } Step 5 − Run your application and you will see the following welcome screen. This Welcome screen might not be as useful. Step 6 − Let us try something else that might be a little more useful. Instead of using the Welcome page, we will use the RuntimeInfoPage. // This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseRuntimeInfoPage(); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); } Step 7 − Save your Startup.cs page and refresh your browser and you will see the following page. This RuntimeInfoPage is a middleware that will only respond to requests that come in for a specific URL. If the incoming request does not match that URL, this piece of middleware just lets the request pass through to the next piece of middleware. The request will pass through the IISPlatformHandler middleware, then go to the UseRuntimeInfoPage middleware. It is not going to create a response, So it will go to our app.Run and display the string. Step 8 − Let us add “/runtimeinfo” at the end of your URL. You will now see a page that is produced by that runtime info page middleware. You will now see a response that gives you some information about your runtime environment such as the Operating System, runtime version, architecture, type and all the packages that you are using etc.
[ { "code": null, "e": 2905, "s": 2595, "text": "In this chapter, we will understand how to set up middleware. Middleware in ASP.NET Core controls how our application responds to HTTP requests. It can also control how our application looks when there is an error, and it is a key piece in how we authenticate and authorize a user to perform specific actions." }, { "code": null, "e": 3022, "s": 2905, "text": "Middleware are software components that are assembled into an application pipeline to handle requests and responses." }, { "code": null, "e": 3139, "s": 3022, "text": "Middleware are software components that are assembled into an application pipeline to handle requests and responses." }, { "code": null, "e": 3328, "s": 3139, "text": "Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline." }, { "code": null, "e": 3517, "s": 3328, "text": "Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline." }, { "code": null, "e": 3623, "s": 3517, "text": "Request delegates are used to build the request pipeline. The request delegates handle each HTTP request." }, { "code": null, "e": 3729, "s": 3623, "text": "Request delegates are used to build the request pipeline. The request delegates handle each HTTP request." }, { "code": null, "e": 3847, "s": 3729, "text": "Each piece of middleware in ASP.NET Core is an object, and each piece has a very specific, focused, and limited role." }, { "code": null, "e": 3965, "s": 3847, "text": "Each piece of middleware in ASP.NET Core is an object, and each piece has a very specific, focused, and limited role." }, { "code": null, "e": 4055, "s": 3965, "text": "Ultimately, we need many pieces of middleware for an application to behave appropriately." }, { "code": null, "e": 4145, "s": 4055, "text": "Ultimately, we need many pieces of middleware for an application to behave appropriately." }, { "code": null, "e": 4237, "s": 4145, "text": "Let us now assume that we want to log information about every request into our application." }, { "code": null, "e": 4348, "s": 4237, "text": "In that case, the first piece of middleware that we might install into the application is a logging component." }, { "code": null, "e": 4459, "s": 4348, "text": "In that case, the first piece of middleware that we might install into the application is a logging component." }, { "code": null, "e": 4652, "s": 4459, "text": "This logger can see everything about the incoming request, but chances are a logger is simply going to record some information and then pass along this request to the next piece of middleware." }, { "code": null, "e": 4845, "s": 4652, "text": "This logger can see everything about the incoming request, but chances are a logger is simply going to record some information and then pass along this request to the next piece of middleware." }, { "code": null, "e": 4919, "s": 4845, "text": "Middleware is a series of components present in this processing pipeline." }, { "code": null, "e": 4993, "s": 4919, "text": "Middleware is a series of components present in this processing pipeline." }, { "code": null, "e": 5082, "s": 4993, "text": "The next piece of middleware that we've installed into the application is an authorizer." }, { "code": null, "e": 5171, "s": 5082, "text": "The next piece of middleware that we've installed into the application is an authorizer." }, { "code": null, "e": 5260, "s": 5171, "text": "An authorizer might be looking for specific cookie or access tokens in the HTTP headers." }, { "code": null, "e": 5349, "s": 5260, "text": "An authorizer might be looking for specific cookie or access tokens in the HTTP headers." }, { "code": null, "e": 5557, "s": 5349, "text": "If the authorizer finds a token, it allows the request to proceed. If not, perhaps the authorizer itself will respond to the request with an HTTP error code or redirect code to send the user to a login page." }, { "code": null, "e": 5765, "s": 5557, "text": "If the authorizer finds a token, it allows the request to proceed. If not, perhaps the authorizer itself will respond to the request with an HTTP error code or redirect code to send the user to a login page." }, { "code": null, "e": 5869, "s": 5765, "text": "But, otherwise, the authorizer will pass the request to the next piece of middleware which is a router." }, { "code": null, "e": 5973, "s": 5869, "text": "But, otherwise, the authorizer will pass the request to the next piece of middleware which is a router." }, { "code": null, "e": 6040, "s": 5973, "text": "A router looks at the URL and determines your next step of action." }, { "code": null, "e": 6107, "s": 6040, "text": "A router looks at the URL and determines your next step of action." }, { "code": null, "e": 6282, "s": 6107, "text": "The router looks over the application for something to respond to and if the router doesn't find anything to respond to, the router itself might return a 404 Not Found error." }, { "code": null, "e": 6457, "s": 6282, "text": "The router looks over the application for something to respond to and if the router doesn't find anything to respond to, the router itself might return a 404 Not Found error." }, { "code": null, "e": 6612, "s": 6457, "text": "Let us now take a simple example to understand more about middleware. We set up the middleware in ASP.NET using the Configure method of our Startup class." }, { "code": null, "e": 7950, "s": 6612, "text": "using Microsoft.AspNet.Builder; \nusing Microsoft.AspNet.Hosting; \nusing Microsoft.AspNet.Http; \n\nusing Microsoft.Extensions.DependencyInjection; \nusing Microsoft.Extensions.Configuration; \n\nnamespace FirstAppDemo { \n public class Startup { \n public Startup() { \n var builder = new ConfigurationBuilder() \n .AddJsonFile(\"AppSettings.json\"); \n Configuration = builder.Build(); \n } \n public IConfiguration Configuration { get; set; } \n \n // This method gets called by the runtime. \n // Use this method to add services to the container. \n // For more information on how to configure your application, \n // visit http://go.microsoft.com/fwlink/?LinkID=398940 \n public void ConfigureServices(IServiceCollection services) { \n } \n \n // This method gets called by the runtime. \n // Use this method to configure the HTTP request pipeline. \n public void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n } \n // Entry point for the application. \n public static void Main(string[] args) => WebApplication.Run<Startup>(args); \n } \n} " }, { "code": null, "e": 8074, "s": 7950, "text": "Inside the Configure() method, we will invoke the extension methods on the IApplicationBuilder interface to add middleware." }, { "code": null, "e": 8145, "s": 8074, "text": "There are two pieces of middleware in a new empty project by default −" }, { "code": null, "e": 8164, "s": 8145, "text": "IISPlatformHandler" }, { "code": null, "e": 8199, "s": 8164, "text": "Middleware registered with app.Run" }, { "code": null, "e": 8434, "s": 8199, "text": "IISPlatformHandler allows us to work with Windows authentication. It will look at every incoming request and see if there is any Windows identity information associated with that request and then it calls the next piece of middleware." }, { "code": null, "e": 8741, "s": 8434, "text": "The next piece of middleware in this case is a piece of middleware registered with app.Run. The Run method allows us to pass in another method, which we can use to process every single response. Run is not something that you will see very often, it is something that we call a terminal piece of middleware." }, { "code": null, "e": 8932, "s": 8741, "text": "Middleware that you register with Run will never have the opportunity to call another piece of middleware, all it does is receive a request, and then it has to produce some sort of response." }, { "code": null, "e": 9051, "s": 8932, "text": "You also get access to a Response object and one of the things you can do with a Response object is to write a string." }, { "code": null, "e": 9274, "s": 9051, "text": "If you want to register another piece of middleware after app.Run, that piece of middleware would never be called because, again, Run is a terminal piece of middleware. It will never call into the next piece of middleware." }, { "code": null, "e": 9342, "s": 9274, "text": "Let us proceed with the following steps to add another middleware −" }, { "code": null, "e": 9435, "s": 9342, "text": "Step 1 − To add another middleware, right-click on project and select Manage NuGet Packages." }, { "code": null, "e": 9689, "s": 9435, "text": "Step 2 − Search for Microsoft.aspnet.diagnostics that is actually ASP.NET Core middleware for exception handling, exception display pages, and diagnostics information. This particular package contains many different pieces of middleware that we can use." }, { "code": null, "e": 9759, "s": 9689, "text": "Step 3 − Install that package if it is not installed in your project." }, { "code": null, "e": 9850, "s": 9759, "text": "Step 4 − Let us now go to the Configure() method and invoke app.UseWelcomePage middleware." }, { "code": null, "e": 10203, "s": 9850, "text": "// This method gets called by the runtime. \n// Use this method to configure the HTTP request pipeline. \npublic void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n app.UseWelcomePage(); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n}" }, { "code": null, "e": 10280, "s": 10203, "text": "Step 5 − Run your application and you will see the following welcome screen." }, { "code": null, "e": 10324, "s": 10280, "text": "This Welcome screen might not be as useful." }, { "code": null, "e": 10463, "s": 10324, "text": "Step 6 − Let us try something else that might be a little more useful. Instead of using the Welcome page, we will use the RuntimeInfoPage." }, { "code": null, "e": 10820, "s": 10463, "text": "// This method gets called by the runtime. \n// Use this method to configure the HTTP request pipeline. \npublic void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n app.UseRuntimeInfoPage(); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n}" }, { "code": null, "e": 10917, "s": 10820, "text": "Step 7 − Save your Startup.cs page and refresh your browser and you will see the following page." }, { "code": null, "e": 11366, "s": 10917, "text": "This RuntimeInfoPage is a middleware that will only respond to requests that come in for a specific URL. If the incoming request does not match that URL, this piece of middleware just lets the request pass through to the next piece of middleware. The request will pass through the IISPlatformHandler middleware, then go to the UseRuntimeInfoPage middleware. It is not going to create a response, So it will go to our app.Run and display the string." }, { "code": null, "e": 11504, "s": 11366, "text": "Step 8 − Let us add “/runtimeinfo” at the end of your URL. You will now see a page that is produced by that runtime info page middleware." } ]
What is Defunctionalization
25 Jun, 2021 Defunctionalization is a compile-time conversion which removes higher-order functions by replacing the higher-order functions with a single first-order apply function. This method was first represented by John C. Reynolds in the year 1972. It was represented in John C. Reynolds’s paper named “Definitional Interpreters for Higher-Order Programming Languages”. His examination was that : There are finitely many function abstractions in a given program, so these function abstractions are restored and assigned by a unique identifier. Within the program, every application of the function is then restored by a call to the apply function with the function identifier as the first argument. The task of this applied function is to execute on this first argument, and then the instructions are performed, which is indicated by the function identifier on the remaining arguments. One difficulty with the idea of defunctionalization is that : Free variables are referenced by function abstractions. In this type of situation, defunctionalization should be introduced by closure conversion or lambda lifting (It is a meta-process that restructures a program so that functions are defined independently of each other in a global scope), so that if a function abstraction has any free variables, then they are passed as extra arguments to apply. In adding to this, if closure conversions are holded up as first-class values, then it becomes mandatory to represent these bindings captured by constructing data structures. In a program, executes on all function abstractions rather than having a single applied function. To determine what functions should be called at each function application site, there are different kinds of control flow analysis (including simple difference based on type signature) and there is also a specialized apply function which may be recommended alternatively. Instead, indirect calls through function pointers are supported by the target language, which may be well organized and extensible than a dispatch-based approach. Steps for Defunctionalization :There are two steps to defunctionalize a higher-order function (HOF) : For each and every position where the higher-order function (HOF) is used and applied to a function, restore that function with the value of the assigned data type to constitute that function. This is known as a “defunctionalization symbol”.According to HOF’s definition, if a function parameter is applied anywhere, restore that applied function parameter with a call to a dedicated first-order function that will explain the defunctionalization symbol for which this parameter now stands for. Often, this function is called apply and sometimes it is known as eval. For each and every position where the higher-order function (HOF) is used and applied to a function, restore that function with the value of the assigned data type to constitute that function. This is known as a “defunctionalization symbol”. According to HOF’s definition, if a function parameter is applied anywhere, restore that applied function parameter with a call to a dedicated first-order function that will explain the defunctionalization symbol for which this parameter now stands for. Often, this function is called apply and sometimes it is known as eval. Functional programming ideas are made with the help of Defunctionalization. There is a lot of value of Defunctionalization in languages which have already higher-order functions, i.e, functional languages. Despite removing higher order functionalities, defunctionalization is a way of mechanically transforming interpreters into abstract machines and it also represents functions by function objects from object-oriented programming languages. Below is the example given by Olivier Danvy, which is translated to Haskell :Below is the tree datatype : data Tree a = Leaf a | Node (Tree a) (Tree a) Now, here we will have to defunctionalize the program given below : cons :: a -> [a] -> [a] cons x xs = x : xs o :: (b -> c) -> (a -> b) -> a -> c o f g x = f (g x) flatten :: Tree t -> [t] flatten t = walk t [] walk :: Tree t -> [t] -> [t] walk (Leaf x) = cons x walk (Node t1 t2) = o (walk t1) (walk t2) Now, to defunctionalize the above program, we will replace all higher-order functions (i.e, o which is the only higher order function here) with lam datatype value and rather than calling them directly, we will initiate an apply function that simplify the datatype – data Lam a = LamCons a | LamO (Lam a) (Lam a) apply :: Lam a -> [a] -> [a] apply (LamCons x) xs = x : xs apply (LamO f1 f2) xs = apply f1 (apply f2 xs) cons_def :: a -> Lam a cons_def x = LamCons x o_def :: Lam a -> Lam a -> Lam a o_def f1 f2 = LamO f1 f2 flatten_def :: Tree t -> [t] flatten_def t = apply (walk_def t) [] walk_def :: Tree t -> Lam t walk_def (Leaf x) = cons_def x walk_def (Node t1 t2) = o_def (walk_def t1) (walk_def t2) Picked C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2021" }, { "code": null, "e": 197, "s": 28, "text": "Defunctionalization is a compile-time conversion which removes higher-order functions by replacing the higher-order functions with a single first-order apply function. " }, { "code": null, "e": 419, "s": 197, "text": "This method was first represented by John C. Reynolds in the year 1972. It was represented in John C. Reynolds’s paper named “Definitional Interpreters for Higher-Order Programming Languages”. His examination was that : " }, { "code": null, "e": 567, "s": 419, "text": "There are finitely many function abstractions in a given program, so these function abstractions are restored and assigned by a unique identifier." }, { "code": null, "e": 722, "s": 567, "text": "Within the program, every application of the function is then restored by a call to the apply function with the function identifier as the first argument." }, { "code": null, "e": 909, "s": 722, "text": "The task of this applied function is to execute on this first argument, and then the instructions are performed, which is indicated by the function identifier on the remaining arguments." }, { "code": null, "e": 971, "s": 909, "text": "One difficulty with the idea of defunctionalization is that :" }, { "code": null, "e": 1371, "s": 971, "text": "Free variables are referenced by function abstractions. In this type of situation, defunctionalization should be introduced by closure conversion or lambda lifting (It is a meta-process that restructures a program so that functions are defined independently of each other in a global scope), so that if a function abstraction has any free variables, then they are passed as extra arguments to apply." }, { "code": null, "e": 1546, "s": 1371, "text": "In adding to this, if closure conversions are holded up as first-class values, then it becomes mandatory to represent these bindings captured by constructing data structures." }, { "code": null, "e": 2080, "s": 1546, "text": "In a program, executes on all function abstractions rather than having a single applied function. To determine what functions should be called at each function application site, there are different kinds of control flow analysis (including simple difference based on type signature) and there is also a specialized apply function which may be recommended alternatively. Instead, indirect calls through function pointers are supported by the target language, which may be well organized and extensible than a dispatch-based approach. " }, { "code": null, "e": 2182, "s": 2080, "text": "Steps for Defunctionalization :There are two steps to defunctionalize a higher-order function (HOF) :" }, { "code": null, "e": 2749, "s": 2182, "text": "For each and every position where the higher-order function (HOF) is used and applied to a function, restore that function with the value of the assigned data type to constitute that function. This is known as a “defunctionalization symbol”.According to HOF’s definition, if a function parameter is applied anywhere, restore that applied function parameter with a call to a dedicated first-order function that will explain the defunctionalization symbol for which this parameter now stands for. Often, this function is called apply and sometimes it is known as eval." }, { "code": null, "e": 2991, "s": 2749, "text": "For each and every position where the higher-order function (HOF) is used and applied to a function, restore that function with the value of the assigned data type to constitute that function. This is known as a “defunctionalization symbol”." }, { "code": null, "e": 3317, "s": 2991, "text": "According to HOF’s definition, if a function parameter is applied anywhere, restore that applied function parameter with a call to a dedicated first-order function that will explain the defunctionalization symbol for which this parameter now stands for. Often, this function is called apply and sometimes it is known as eval." }, { "code": null, "e": 3523, "s": 3317, "text": "Functional programming ideas are made with the help of Defunctionalization. There is a lot of value of Defunctionalization in languages which have already higher-order functions, i.e, functional languages." }, { "code": null, "e": 3762, "s": 3523, "text": "Despite removing higher order functionalities, defunctionalization is a way of mechanically transforming interpreters into abstract machines and it also represents functions by function objects from object-oriented programming languages." }, { "code": null, "e": 3868, "s": 3762, "text": "Below is the example given by Olivier Danvy, which is translated to Haskell :Below is the tree datatype :" }, { "code": null, "e": 3926, "s": 3868, "text": "data Tree a = Leaf a\n | Node (Tree a) (Tree a)" }, { "code": null, "e": 3994, "s": 3926, "text": "Now, here we will have to defunctionalize the program given below :" }, { "code": null, "e": 4239, "s": 3994, "text": "cons :: a -> [a] -> [a]\ncons x xs = x : xs\n\no :: (b -> c) -> (a -> b) -> a -> c\no f g x = f (g x)\n\nflatten :: Tree t -> [t]\nflatten t = walk t []\n\nwalk :: Tree t -> [t] -> [t]\nwalk (Leaf x) = cons x\nwalk (Node t1 t2) = o (walk t1) (walk t2)" }, { "code": null, "e": 4506, "s": 4239, "text": "Now, to defunctionalize the above program, we will replace all higher-order functions (i.e, o which is the only higher order function here) with lam datatype value and rather than calling them directly, we will initiate an apply function that simplify the datatype –" }, { "code": null, "e": 4968, "s": 4506, "text": "data Lam a = LamCons a\n | LamO (Lam a) (Lam a)\n\napply :: Lam a -> [a] -> [a]\napply (LamCons x) xs = x : xs\napply (LamO f1 f2) xs = apply f1 (apply f2 xs)\n\ncons_def :: a -> Lam a\ncons_def x = LamCons x\n\no_def :: Lam a -> Lam a -> Lam a\no_def f1 f2 = LamO f1 f2\n\nflatten_def :: Tree t -> [t]\nflatten_def t = apply (walk_def t) []\n\nwalk_def :: Tree t -> Lam t\nwalk_def (Leaf x) = cons_def x\nwalk_def (Node t1 t2) = o_def (walk_def t1) (walk_def t2)" }, { "code": null, "e": 4975, "s": 4968, "text": "Picked" }, { "code": null, "e": 4986, "s": 4975, "text": "C Language" } ]
PHP | Classes
25 Mar, 2018 Like C++ and Java, PHP also supports object oriented programming Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’.Class is a programmer-defined data type, which includes local methods and local variables.Class is a collection of objects. Object has properties and behavior. Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’. Class is a programmer-defined data type, which includes local methods and local variables. Class is a collection of objects. Object has properties and behavior. Syntax: We define our own class by starting with the keyword ‘class’ followed by the name you want to give your new class. <?php class person { } ?> Note: We enclose a class using curly braces ( { } ) ... just like you do with functions. Given below are the programs to elaborate the use of class in Object Oriented Programming in PHP.The programs will illustrate the examples given in the article. Program 1: <?phpclass GeeksforGeeks{ // Constructor public function __construct(){ echo 'The class "' . __CLASS__ . '" was initiated!<br>'; } } // Create a new object$obj = new GeeksforGeeks;?> Output: The class "GeeksforGeeks" was initiated. Program 2: <?phpclass GeeksforGeeks{ // Destructor public function __destruct(){ echo 'The class "' . __CLASS__ . '" was destroyed!'; } } // Create a new object$obj = new GeeksforGeeks;?> Output: The class "GeeksforGeeks" was destroyed. Reference:Classes in PHP PHP-OOP PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to get parameters from a URL string in PHP? Split a comma delimited string into an array in PHP Download file from URL using PHP Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Mar, 2018" }, { "code": null, "e": 119, "s": 54, "text": "Like C++ and Java, PHP also supports object oriented programming" }, { "code": null, "e": 476, "s": 119, "text": "Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’.Class is a programmer-defined data type, which includes local methods and local variables.Class is a collection of objects. Object has properties and behavior." }, { "code": null, "e": 674, "s": 476, "text": "Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’." }, { "code": null, "e": 765, "s": 674, "text": "Class is a programmer-defined data type, which includes local methods and local variables." }, { "code": null, "e": 835, "s": 765, "text": "Class is a collection of objects. Object has properties and behavior." }, { "code": null, "e": 958, "s": 835, "text": "Syntax: We define our own class by starting with the keyword ‘class’ followed by the name you want to give your new class." }, { "code": null, "e": 995, "s": 958, "text": "<?php \n class person {\n \n }\n?>" }, { "code": null, "e": 1084, "s": 995, "text": "Note: We enclose a class using curly braces ( { } ) ... just like you do with functions." }, { "code": null, "e": 1245, "s": 1084, "text": "Given below are the programs to elaborate the use of class in Object Oriented Programming in PHP.The programs will illustrate the examples given in the article." }, { "code": null, "e": 1256, "s": 1245, "text": "Program 1:" }, { "code": "<?phpclass GeeksforGeeks{ // Constructor public function __construct(){ echo 'The class \"' . __CLASS__ . '\" was initiated!<br>'; } } // Create a new object$obj = new GeeksforGeeks;?>", "e": 1462, "s": 1256, "text": null }, { "code": null, "e": 1470, "s": 1462, "text": "Output:" }, { "code": null, "e": 1511, "s": 1470, "text": "The class \"GeeksforGeeks\" was initiated." }, { "code": null, "e": 1522, "s": 1511, "text": "Program 2:" }, { "code": "<?phpclass GeeksforGeeks{ // Destructor public function __destruct(){ echo 'The class \"' . __CLASS__ . '\" was destroyed!'; } } // Create a new object$obj = new GeeksforGeeks;?>", "e": 1722, "s": 1522, "text": null }, { "code": null, "e": 1730, "s": 1722, "text": "Output:" }, { "code": null, "e": 1772, "s": 1730, "text": "The class \"GeeksforGeeks\" was destroyed.\n" }, { "code": null, "e": 1797, "s": 1772, "text": "Reference:Classes in PHP" }, { "code": null, "e": 1805, "s": 1797, "text": "PHP-OOP" }, { "code": null, "e": 1809, "s": 1805, "text": "PHP" }, { "code": null, "e": 1826, "s": 1809, "text": "Web Technologies" }, { "code": null, "e": 1830, "s": 1826, "text": "PHP" }, { "code": null, "e": 1928, "s": 1830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1968, "s": 1928, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2013, "s": 1968, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2061, "s": 2013, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 2113, "s": 2061, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 2146, "s": 2113, "text": "Download file from URL using PHP" }, { "code": null, "e": 2179, "s": 2146, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2241, "s": 2179, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2302, "s": 2241, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2352, "s": 2302, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
HTML Heading
28 Jun, 2022 In this article, we will know HTML Heading, & its implementation through the examples. A HTML heading tag is used to define the headings of a page. There are six levels of headings defined by HTML. These 6 heading elements are h1, h2, h3, h4, h5, and h6; with h1 being the highest level and h6 being the least. <h1>is used for main heading. (Biggest in size) <h2>is used for subheadings if there are further sections under the subheadings then the <h3> elements is used. <h6> for the small heading (smallest one). Browsers display the contents of headings in different sizes. The exact size at which each browser shows the heading can vary slightly. Users can also adjust the size of text in their browser. Syntax: // the 'h' inside the tag should be in small case only. <h1>Heading1</h1> <h2>Heading2</h2> . . . <h6>Heading6</h6> Importance of Heading: Search Engines use headings for indexing the structure and organizing the content of the webpage. Headings are used for highlighting important topics. They provide valuable information and tell us about the structure of the document. Example 1: This example illustrates the HTML heading tags. HTML <!DOCTYPE html><html> <head> <title>Heading Tags</title></head> <body> <h1>GeeksforGeeks</h1> <h2>GeeksforGeeks</h2> <h3>GeeksforGeeks</h3> <h4>GeeksforGeeks</h4> <h5>GeeksforGeeks</h5> <h6>GeeksforGeeks</h6></body> </html> Output: HTML Headings Example 2: This example explains the different HTML heading tags. HTML <!DOCTYPE html><html> <body> <h1>Welcome to GeeksforGeeks</h1> <h2>A computer science portal for geeks</h2> <h5>Tutorial</h5> <h6>Geeks</h6></body> </html> Output: Changing the size of HTML Headings: The default size of HTML headings can be changed, using the style attribute. Example: This example explains the HTML heading tags by specifying the size of the font. HTML <!DOCTYPE html><html> <body> <h1>H1 Heading</h1> <!-- With the help of Style attribute you can customize the size of the heading, As done below--> <h1 style="font-size: 50px">H1 with new size.</h1> <!-- Here font-size is the property by which we can modify the heading. Here we kept it 50px i.e. 50 pixels --> </body> </html> Output: Styling the <h1> tag with different font-size Horizontal rule: The <hr> tag which stands for the horizontal rule is used to define a thematic break in an HTML page. The <hr> tag is an empty tag, and it does not require any end tag. It is basically used to separate content. Please refer to the HTML <hr> Tag article for more detailed information. Example: This example explains the HTML Headings with horizontal rules. HTML <!DOCTYPE html><html> <body> <h1>Heading 1</h1> <p>I like HTML.</p> <!-- hr Tag is used here--> <hr /> <h2>Heading 2</h2> <p>I like CSS.</p> <!-- hr Tag is used here--> <hr /> <h2>Heading 3</h2> <p>I like Javascript.</p> </body> </html> Output: HTML Heading with the horizontal line Supported Browsers: Google Chrome 93.0 Microsoft Edge 93.0 Internet Explorer 11.0 Firefox 92.0 Opera 78.0 Safari 14.1 shubhamyadav4 bhaskargeeksforgeeks dishaagrawal1 lucidcoder121 sweetyty HTML-Basics HTML Technical Scripter 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": 53, "s": 25, "text": "\n28 Jun, 2022" }, { "code": null, "e": 364, "s": 53, "text": "In this article, we will know HTML Heading, & its implementation through the examples. A HTML heading tag is used to define the headings of a page. There are six levels of headings defined by HTML. These 6 heading elements are h1, h2, h3, h4, h5, and h6; with h1 being the highest level and h6 being the least." }, { "code": null, "e": 412, "s": 364, "text": "<h1>is used for main heading. (Biggest in size)" }, { "code": null, "e": 440, "s": 412, "text": "<h2>is used for subheadings" }, { "code": null, "e": 525, "s": 440, "text": "if there are further sections under the subheadings then the <h3> elements is used. " }, { "code": null, "e": 568, "s": 525, "text": "<h6> for the small heading (smallest one)." }, { "code": null, "e": 762, "s": 568, "text": "Browsers display the contents of headings in different sizes. The exact size at which each browser shows the heading can vary slightly. Users can also adjust the size of text in their browser. " }, { "code": null, "e": 770, "s": 762, "text": "Syntax:" }, { "code": null, "e": 886, "s": 770, "text": "// the 'h' inside the tag should be in small case only.\n<h1>Heading1</h1>\n<h2>Heading2</h2>\n.\n.\n.\n<h6>Heading6</h6>" }, { "code": null, "e": 909, "s": 886, "text": "Importance of Heading:" }, { "code": null, "e": 1007, "s": 909, "text": "Search Engines use headings for indexing the structure and organizing the content of the webpage." }, { "code": null, "e": 1060, "s": 1007, "text": "Headings are used for highlighting important topics." }, { "code": null, "e": 1143, "s": 1060, "text": "They provide valuable information and tell us about the structure of the document." }, { "code": null, "e": 1202, "s": 1143, "text": "Example 1: This example illustrates the HTML heading tags." }, { "code": null, "e": 1207, "s": 1202, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Heading Tags</title></head> <body> <h1>GeeksforGeeks</h1> <h2>GeeksforGeeks</h2> <h3>GeeksforGeeks</h3> <h4>GeeksforGeeks</h4> <h5>GeeksforGeeks</h5> <h6>GeeksforGeeks</h6></body> </html>", "e": 1452, "s": 1207, "text": null }, { "code": null, "e": 1460, "s": 1452, "text": "Output:" }, { "code": null, "e": 1474, "s": 1460, "text": "HTML Headings" }, { "code": null, "e": 1540, "s": 1474, "text": "Example 2: This example explains the different HTML heading tags." }, { "code": null, "e": 1545, "s": 1540, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>Welcome to GeeksforGeeks</h1> <h2>A computer science portal for geeks</h2> <h5>Tutorial</h5> <h6>Geeks</h6></body> </html>", "e": 1713, "s": 1545, "text": null }, { "code": null, "e": 1721, "s": 1713, "text": "Output:" }, { "code": null, "e": 1834, "s": 1721, "text": "Changing the size of HTML Headings: The default size of HTML headings can be changed, using the style attribute." }, { "code": null, "e": 1923, "s": 1834, "text": "Example: This example explains the HTML heading tags by specifying the size of the font." }, { "code": null, "e": 1928, "s": 1923, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>H1 Heading</h1> <!-- With the help of Style attribute you can customize the size of the heading, As done below--> <h1 style=\"font-size: 50px\">H1 with new size.</h1> <!-- Here font-size is the property by which we can modify the heading. Here we kept it 50px i.e. 50 pixels --> </body> </html>", "e": 2285, "s": 1928, "text": null }, { "code": null, "e": 2293, "s": 2285, "text": "Output:" }, { "code": null, "e": 2339, "s": 2293, "text": "Styling the <h1> tag with different font-size" }, { "code": null, "e": 2640, "s": 2339, "text": "Horizontal rule: The <hr> tag which stands for the horizontal rule is used to define a thematic break in an HTML page. The <hr> tag is an empty tag, and it does not require any end tag. It is basically used to separate content. Please refer to the HTML <hr> Tag article for more detailed information." }, { "code": null, "e": 2712, "s": 2640, "text": "Example: This example explains the HTML Headings with horizontal rules." }, { "code": null, "e": 2717, "s": 2712, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>Heading 1</h1> <p>I like HTML.</p> <!-- hr Tag is used here--> <hr /> <h2>Heading 2</h2> <p>I like CSS.</p> <!-- hr Tag is used here--> <hr /> <h2>Heading 3</h2> <p>I like Javascript.</p> </body> </html>", "e": 3010, "s": 2717, "text": null }, { "code": null, "e": 3018, "s": 3010, "text": "Output:" }, { "code": null, "e": 3056, "s": 3018, "text": "HTML Heading with the horizontal line" }, { "code": null, "e": 3077, "s": 3056, "text": "Supported Browsers: " }, { "code": null, "e": 3096, "s": 3077, "text": "Google Chrome 93.0" }, { "code": null, "e": 3116, "s": 3096, "text": "Microsoft Edge 93.0" }, { "code": null, "e": 3139, "s": 3116, "text": "Internet Explorer 11.0" }, { "code": null, "e": 3152, "s": 3139, "text": "Firefox 92.0" }, { "code": null, "e": 3163, "s": 3152, "text": "Opera 78.0" }, { "code": null, "e": 3175, "s": 3163, "text": "Safari 14.1" }, { "code": null, "e": 3189, "s": 3175, "text": "shubhamyadav4" }, { "code": null, "e": 3210, "s": 3189, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 3224, "s": 3210, "text": "dishaagrawal1" }, { "code": null, "e": 3238, "s": 3224, "text": "lucidcoder121" }, { "code": null, "e": 3247, "s": 3238, "text": "sweetyty" }, { "code": null, "e": 3259, "s": 3247, "text": "HTML-Basics" }, { "code": null, "e": 3264, "s": 3259, "text": "HTML" }, { "code": null, "e": 3283, "s": 3264, "text": "Technical Scripter" }, { "code": null, "e": 3300, "s": 3283, "text": "Web Technologies" }, { "code": null, "e": 3305, "s": 3300, "text": "HTML" }, { "code": null, "e": 3403, "s": 3305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3451, "s": 3403, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3513, "s": 3451, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3563, "s": 3513, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3587, "s": 3563, "text": "REST API (Introduction)" }, { "code": null, "e": 3640, "s": 3587, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3673, "s": 3640, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3735, "s": 3673, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3796, "s": 3735, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3846, "s": 3796, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Data type of case labels of switch statement in C++?
12 Aug, 2021 In C++ switch statement, the expression of each case label must be an integer constant expression. For example, the following program fails in compilation. CPP /* Using non-const in case label */#include<stdio.h>int main(){ int i = 10; int c = 10; switch(c) { case i: // not a "const int" expression printf("Value of c = %d", c); break; /*Some more cases */ } return 0;} Putting const before i makes the above program work. CPP #include<stdio.h>int main(){ const int i = 10; int c = 10; switch(c) { case i: // Works fine printf("Value of c = %d", c); break; /*Some more cases */ } return 0;} Note : The above fact is only for C++. In C, both programs produce an error. In C, using an integer literal does not cause an error.Program to find the largest number between two numbers using switch case: C #include<stdio.h>int main(){ int n1=10,n2=11; // n1 > n2 (10 > 11) is false so using // logical operator '>', n1 > n2 produces 0 // (0 means false, 1 means true) So, case 0 // is executed as 10 > 11 is false. Here we // have used type cast to convert boolean to int, // to avoid warning. switch((int)(n1 > n2)) { case 0: printf("%d is the largest\n", n2); break; default: printf("%d is the largest\n", n1); } // n1 < n2 (10 < 11) is true so using logical // operator '<', n1 < n2 produces 1 (1 means true, // 0 means false) So, default is executed as we // don't have case 1 to be executed. switch((int)(n1 < n2)) { case 0: printf("%d is the largest\n", n1); break; default: printf("%d is the largest\n", n2); } return 0;}//This code is contributed by Santanu Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SantanuBasak HanishGupta1 imohitagrawal C-Loops & Control Statements C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library Operators in C / C++ Exception Handling in C++ What is the purpose of a function prototype? TCP Server-Client implementation in C Smart Pointers in C++ and How to Use Them 'this' pointer in C++ Storage Classes in C Ways to copy a vector in C++ Understanding "extern" keyword in C
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Aug, 2021" }, { "code": null, "e": 210, "s": 52, "text": "In C++ switch statement, the expression of each case label must be an integer constant expression. For example, the following program fails in compilation. " }, { "code": null, "e": 214, "s": 210, "text": "CPP" }, { "code": "/* Using non-const in case label */#include<stdio.h>int main(){ int i = 10; int c = 10; switch(c) { case i: // not a \"const int\" expression printf(\"Value of c = %d\", c); break; /*Some more cases */ } return 0;}", "e": 473, "s": 214, "text": null }, { "code": null, "e": 527, "s": 473, "text": "Putting const before i makes the above program work. " }, { "code": null, "e": 531, "s": 527, "text": "CPP" }, { "code": "#include<stdio.h>int main(){ const int i = 10; int c = 10; switch(c) { case i: // Works fine printf(\"Value of c = %d\", c); break; /*Some more cases */ } return 0;}", "e": 744, "s": 531, "text": null }, { "code": null, "e": 951, "s": 744, "text": "Note : The above fact is only for C++. In C, both programs produce an error. In C, using an integer literal does not cause an error.Program to find the largest number between two numbers using switch case: " }, { "code": null, "e": 953, "s": 951, "text": "C" }, { "code": "#include<stdio.h>int main(){ int n1=10,n2=11; // n1 > n2 (10 > 11) is false so using // logical operator '>', n1 > n2 produces 0 // (0 means false, 1 means true) So, case 0 // is executed as 10 > 11 is false. Here we // have used type cast to convert boolean to int, // to avoid warning. switch((int)(n1 > n2)) { case 0: printf(\"%d is the largest\\n\", n2); break; default: printf(\"%d is the largest\\n\", n1); } // n1 < n2 (10 < 11) is true so using logical // operator '<', n1 < n2 produces 1 (1 means true, // 0 means false) So, default is executed as we // don't have case 1 to be executed. switch((int)(n1 < n2)) { case 0: printf(\"%d is the largest\\n\", n1); break; default: printf(\"%d is the largest\\n\", n2); } return 0;}//This code is contributed by Santanu", "e": 1799, "s": 953, "text": null }, { "code": null, "e": 1925, "s": 1799, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 1938, "s": 1925, "text": "SantanuBasak" }, { "code": null, "e": 1951, "s": 1938, "text": "HanishGupta1" }, { "code": null, "e": 1965, "s": 1951, "text": "imohitagrawal" }, { "code": null, "e": 1994, "s": 1965, "text": "C-Loops & Control Statements" }, { "code": null, "e": 2005, "s": 1994, "text": "C Language" }, { "code": null, "e": 2103, "s": 2005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2151, "s": 2103, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 2172, "s": 2151, "text": "Operators in C / C++" }, { "code": null, "e": 2198, "s": 2172, "text": "Exception Handling in C++" }, { "code": null, "e": 2243, "s": 2198, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 2281, "s": 2243, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2323, "s": 2281, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 2345, "s": 2323, "text": "'this' pointer in C++" }, { "code": null, "e": 2366, "s": 2345, "text": "Storage Classes in C" }, { "code": null, "e": 2395, "s": 2366, "text": "Ways to copy a vector in C++" } ]
Python | Working with buttons in Kivy with .kv file
25 Jun, 2019 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. The Button is a Label with associated actions that are triggered when the button is pressed (or released after a click/touch). We can add functions behind the button and style the button. In this article, we are going to discuss how we can create the buttons using .kv file. We do a little bit of button styling also and also we define you how to bind a button to a callback. To use button you must have to import : import kivy.uix.button as Button Basic Approach: 1) import kivy 2) import kivyApp 3) import Widget 4) import Button 5) Set minimum version(optional) 6) Create widget class: 1) Arrange a callback 2) Define Callback function 7) create App class 8) create .kv file (name same as the app class): 1) create Widget 2) Create Button 3) Specify requirements 9) return Layout/widget/Class(according to requirement) 10) Run an instance of the class One of the common problems is how to add functionality to the button. So to add functionality we use bind() function it binds the function to the button. bind() creates an event that is send to callback(). One of the most common problems for new Kivy users is misunderstanding how the bind method works, especially amongst newer Python users who haven’t fully formed their intuition about function calls.The thing is that the bind method doesn’t know about the existence of a function or its arguments, it only receives the result of this function call. As in the given code when the button is pressed it prints that “button pressed” def in the function callback. Code to implement the above Approach with button action and styling. # import kivy module import kivy # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require("1.9.1") # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # creates the button in kivy # if not imported shows the error from kivy.uix.button import Button # Widgets are elements of a graphical user # interface that form part of the User Experience. from kivy.uix.widget import Widget # Creating a widget class # through this we add button # the commands of the class is in .kv file class Button_Widget(Widget): def __init__(self, **kwargs): # Python super() function allows us to # refer to the parent class explicitly. super(Button_Widget, self).__init__(**kwargs) # creating Button btn1 = Button(text ='Hello World 1', font_size ="15sp", background_color =(1, 1, 1, 1), color =(1, 1, 1, 1), # size =(32, 32), # size_hint =(.2, .2), pos =(300, 250)) # Arranging a callback to a button using # bind() function in kivy. btn1.bind(on_press = self.callback) self.add_widget(btn1) # callback function tells when button pressed # It tells the state and instance of button. def callback(self, instance): print("Button is pressed") print('The button % s state is <%s>' % (instance, instance.state)) # create App class class ButtonApp(App): def build(self): # return the widget return Button_Widget() # run the Appif __name__ == "__main__": ButtonApp().run() .kv file implementation of the Approach # .kv file of the main.py code # Adding Button widget <Button_Widget>: # defining Button size size: 100, 100 # creating Canvas canvas.before: Color: rgba: 0.72, 0.62, 0.92, 1 Rectangle: pos: self.pos size: self.size Output: Showing the button action picture:i.e on clicking on button you will get this output Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2019" }, { "code": null, "e": 264, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications." }, { "code": null, "e": 452, "s": 264, "text": "The Button is a Label with associated actions that are triggered when the button is pressed (or released after a click/touch). We can add functions behind the button and style the button." }, { "code": null, "e": 640, "s": 452, "text": "In this article, we are going to discuss how we can create the buttons using .kv file. We do a little bit of button styling also and also we define you how to bind a button to a callback." }, { "code": null, "e": 680, "s": 640, "text": "To use button you must have to import :" }, { "code": null, "e": 713, "s": 680, "text": "import kivy.uix.button as Button" }, { "code": null, "e": 1164, "s": 713, "text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import Widget\n4) import Button\n5) Set minimum version(optional)\n6) Create widget class:\n 1) Arrange a callback\n 2) Define Callback function\n7) create App class\n8) create .kv file (name same as the app class):\n 1) create Widget\n 2) Create Button\n 3) Specify requirements\n9) return Layout/widget/Class(according to requirement)\n10) Run an instance of the class" }, { "code": null, "e": 1370, "s": 1164, "text": "One of the common problems is how to add functionality to the button. So to add functionality we use bind() function it binds the function to the button. bind() creates an event that is send to callback()." }, { "code": null, "e": 1828, "s": 1370, "text": "One of the most common problems for new Kivy users is misunderstanding how the bind method works, especially amongst newer Python users who haven’t fully formed their intuition about function calls.The thing is that the bind method doesn’t know about the existence of a function or its arguments, it only receives the result of this function call. As in the given code when the button is pressed it prints that “button pressed” def in the function callback." }, { "code": null, "e": 1897, "s": 1828, "text": "Code to implement the above Approach with button action and styling." }, { "code": "# import kivy module import kivy # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require(\"1.9.1\") # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # creates the button in kivy # if not imported shows the error from kivy.uix.button import Button # Widgets are elements of a graphical user # interface that form part of the User Experience. from kivy.uix.widget import Widget # Creating a widget class # through this we add button # the commands of the class is in .kv file class Button_Widget(Widget): def __init__(self, **kwargs): # Python super() function allows us to # refer to the parent class explicitly. super(Button_Widget, self).__init__(**kwargs) # creating Button btn1 = Button(text ='Hello World 1', font_size =\"15sp\", background_color =(1, 1, 1, 1), color =(1, 1, 1, 1), # size =(32, 32), # size_hint =(.2, .2), pos =(300, 250)) # Arranging a callback to a button using # bind() function in kivy. btn1.bind(on_press = self.callback) self.add_widget(btn1) # callback function tells when button pressed # It tells the state and instance of button. def callback(self, instance): print(\"Button is pressed\") print('The button % s state is <%s>' % (instance, instance.state)) # create App class class ButtonApp(App): def build(self): # return the widget return Button_Widget() # run the Appif __name__ == \"__main__\": ButtonApp().run()", "e": 3630, "s": 1897, "text": null }, { "code": null, "e": 3670, "s": 3630, "text": ".kv file implementation of the Approach" }, { "code": "# .kv file of the main.py code # Adding Button widget <Button_Widget>: # defining Button size size: 100, 100 # creating Canvas canvas.before: Color: rgba: 0.72, 0.62, 0.92, 1 Rectangle: pos: self.pos size: self.size", "e": 3951, "s": 3670, "text": null }, { "code": null, "e": 3959, "s": 3951, "text": "Output:" }, { "code": null, "e": 4044, "s": 3959, "text": "Showing the button action picture:i.e on clicking on button you will get this output" }, { "code": null, "e": 4055, "s": 4044, "text": "Python-gui" }, { "code": null, "e": 4067, "s": 4055, "text": "Python-kivy" }, { "code": null, "e": 4074, "s": 4067, "text": "Python" } ]
What does intern() method in java?
The intern() method of the String method returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. For any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. All literal strings and string-valued constant expressions are interned. Live Demo import java.lang.*; public class StringDemo { public static void main(String[] args) { String str1 = "This is TutorialsPoint"; // returns canonical representation for the string object String str2 = str1.intern(); // prints the string str2 System.out.println(str2); // check if str1 and str2 are equal or not System.out.println("Is str1 equal to str2 ? = " + (str1 == str2)); } } This is TutorialsPoint Is str1 equal to str2 ? = true
[ { "code": null, "e": 1242, "s": 1062, "text": "The intern() method of the String method returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String." }, { "code": null, "e": 1340, "s": 1242, "text": "For any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true." }, { "code": null, "e": 1413, "s": 1340, "text": "All literal strings and string-valued constant expressions are interned." }, { "code": null, "e": 1424, "s": 1413, "text": " Live Demo" }, { "code": null, "e": 1864, "s": 1424, "text": "import java.lang.*;\npublic class StringDemo {\n public static void main(String[] args) {\n String str1 = \"This is TutorialsPoint\";\n // returns canonical representation for the string object\n String str2 = str1.intern();\n \n // prints the string str2\n System.out.println(str2);\n \n // check if str1 and str2 are equal or not\n System.out.println(\"Is str1 equal to str2 ? = \" + (str1 == str2));\n }\n}" }, { "code": null, "e": 1918, "s": 1864, "text": "This is TutorialsPoint\nIs str1 equal to str2 ? = true" } ]
Find the value of ln(N!) using Recursion - GeeksforGeeks
14 May, 2021 Given a number N, the task is to find the log value of the factorial of N i.e. log(N!).Note: ln means log with base e.Examples: Input: N = 2 Output: 0.693147 Input: N = 3 Output: 1.791759 Approach:Method -1: Calculate n! first, then take its log value.Method -2: By using the property of log, i.e. take the sum of log values of n, n-1, n-2 ...1. ln(n!) = ln(n*n-1*n-2*.....*2*1) = ln(n)+ln(n-1)+......+ln(2)+ln(1) Below is the implementation of the Method-2: C++ C Java Python C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the valuedouble fact(int n){ if (n == 1) return 0; return fact(n - 1) + log(n);}// Driver codeint main(){ int N = 3; cout << fact(N) << "\n"; return 0;} // C implementation of the above approach#include <math.h>#include <stdio.h> long double fact(int n){ if (n == 1) return 0; return fact(n - 1) + log(n);} // Driver codeint main(){ int n = 3; printf("%Lf", fact(n)); return 0;} // Java implementation of the above approachimport java.util.*;import java.io.*;class logfact { public static double fact(int n) { if (n == 1) return 0; return fact(n - 1) + Math.log(n); } public static void main(String[] args) { int N = 3; System.out.println(fact(N)); }} # Python implementation of the above approachimport mathdef fact(n): if (n == 1): return 0 else: return fact(n-1) + math.log(n)N = 3print(fact(N)) // C# implementation of the above approachusing System; class GFG{ public static double fact(int n) { if (n == 1) return 0; return fact(n - 1) + Math.Log(n); } // Driver code public static void Main() { int N = 3; Console.WriteLine(fact(N)); }} // This code is contributed by ihritik <?php //PHP implementation of the above approach function fact($n){ if ($n == 1) return 0; return fact($n - 1) + log($n);} // Driver code$n = 3;echo fact($n); // This code is contributed by ihritik?> <script> // Javascript implementation of the above approach // Function to calculate the valuefunction fact(n){ if (n == 1) return 0; return fact(n - 1) + Math.log(n);}// Driver codevar N = 3;document.write( fact(N).toFixed(6) + "<br>"); </script> 1.791759 ihritik rutvik_56 maths-log Mathematical Recursion Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Generate all permutation of a set in Python Check if a number is Palindrome Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction Program for Sum of the digits of a given number
[ { "code": null, "e": 25963, "s": 25935, "text": "\n14 May, 2021" }, { "code": null, "e": 26093, "s": 25963, "text": "Given a number N, the task is to find the log value of the factorial of N i.e. log(N!).Note: ln means log with base e.Examples: " }, { "code": null, "e": 26155, "s": 26093, "text": "Input: N = 2\nOutput: 0.693147\n\nInput: N = 3\nOutput: 1.791759" }, { "code": null, "e": 26317, "s": 26157, "text": "Approach:Method -1: Calculate n! first, then take its log value.Method -2: By using the property of log, i.e. take the sum of log values of n, n-1, n-2 ...1. " }, { "code": null, "e": 26387, "s": 26317, "text": "ln(n!) = ln(n*n-1*n-2*.....*2*1) = ln(n)+ln(n-1)+......+ln(2)+ln(1) " }, { "code": null, "e": 26434, "s": 26387, "text": "Below is the implementation of the Method-2: " }, { "code": null, "e": 26438, "s": 26434, "text": "C++" }, { "code": null, "e": 26440, "s": 26438, "text": "C" }, { "code": null, "e": 26445, "s": 26440, "text": "Java" }, { "code": null, "e": 26452, "s": 26445, "text": "Python" }, { "code": null, "e": 26455, "s": 26452, "text": "C#" }, { "code": null, "e": 26459, "s": 26455, "text": "PHP" }, { "code": null, "e": 26470, "s": 26459, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the valuedouble fact(int n){ if (n == 1) return 0; return fact(n - 1) + log(n);}// Driver codeint main(){ int N = 3; cout << fact(N) << \"\\n\"; return 0;}", "e": 26758, "s": 26470, "text": null }, { "code": "// C implementation of the above approach#include <math.h>#include <stdio.h> long double fact(int n){ if (n == 1) return 0; return fact(n - 1) + log(n);} // Driver codeint main(){ int n = 3; printf(\"%Lf\", fact(n)); return 0;}", "e": 27006, "s": 26758, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*;import java.io.*;class logfact { public static double fact(int n) { if (n == 1) return 0; return fact(n - 1) + Math.log(n); } public static void main(String[] args) { int N = 3; System.out.println(fact(N)); }}", "e": 27338, "s": 27006, "text": null }, { "code": "# Python implementation of the above approachimport mathdef fact(n): if (n == 1): return 0 else: return fact(n-1) + math.log(n)N = 3print(fact(N))", "e": 27505, "s": 27338, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ public static double fact(int n) { if (n == 1) return 0; return fact(n - 1) + Math.Log(n); } // Driver code public static void Main() { int N = 3; Console.WriteLine(fact(N)); }} // This code is contributed by ihritik", "e": 27850, "s": 27505, "text": null }, { "code": "<?php //PHP implementation of the above approach function fact($n){ if ($n == 1) return 0; return fact($n - 1) + log($n);} // Driver code$n = 3;echo fact($n); // This code is contributed by ihritik?>", "e": 28063, "s": 27850, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function to calculate the valuefunction fact(n){ if (n == 1) return 0; return fact(n - 1) + Math.log(n);}// Driver codevar N = 3;document.write( fact(N).toFixed(6) + \"<br>\"); </script>", "e": 28324, "s": 28063, "text": null }, { "code": null, "e": 28333, "s": 28324, "text": "1.791759" }, { "code": null, "e": 28343, "s": 28335, "text": "ihritik" }, { "code": null, "e": 28353, "s": 28343, "text": "rutvik_56" }, { "code": null, "e": 28363, "s": 28353, "text": "maths-log" }, { "code": null, "e": 28376, "s": 28363, "text": "Mathematical" }, { "code": null, "e": 28386, "s": 28376, "text": "Recursion" }, { "code": null, "e": 28399, "s": 28386, "text": "Mathematical" }, { "code": null, "e": 28409, "s": 28399, "text": "Recursion" }, { "code": null, "e": 28507, "s": 28409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28551, "s": 28507, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 28582, "s": 28551, "text": "Modular multiplicative inverse" }, { "code": null, "e": 28607, "s": 28582, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 28651, "s": 28607, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 28683, "s": 28651, "text": "Check if a number is Palindrome" }, { "code": null, "e": 28768, "s": 28683, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 28778, "s": 28768, "text": "Recursion" }, { "code": null, "e": 28805, "s": 28778, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 28833, "s": 28805, "text": "Backtracking | Introduction" } ]
What are the different types of classes in Java?
Any normal class which does not have any abstract method or a class that has an implementation of all the methods of its parent class or interface and its own methods is a concrete class. Live Demo public class Concrete { // Concrete Class static int product(int a, int b) { return a * b; } public static void main(String args[]) { int p = product(2, 3); System.out.println("Product: " + p); } } Product: 6 A class declared with abstract keyword and have zero or more abstract methods are known as abstract class. The abstract classes are incomplete classes, therefore, to use we strictly need to extend the abstract classes to a concrete class. Live Demo abstract class Animal { //abstract parent class public abstract void sound(); //abstract method } public class Dog extends Animal { //Dog class extends Animal class public void sound() { System.out.println("Woof"); } public static void main(String args[]) { Animal a = new Dog(); a.sound(); } } Woof A class declared with the final keyword is a final class and it cannot be extended by another class, for example, java.lang.System class. Live Demo final class BaseClass { void Display() { System.out.print("This is Display() method of BaseClass."); } } class DerivedClass extends BaseClass { //Compile-time error - can't inherit final class void Display() { System.out.print("This is Display() method of DerivedClass."); } } public class FinalClassDemo { public static void main(String[] arg) { DerivedClass d = new DerivedClass(); d.Display(); } } In the above example, DerivedClass extends BaseClass(final), we can't extend a final class, so compiler will throw an error. The above program doesn't execute. cannot inherit from final BaseClass Compile-time error - can't inherit final class A class that contains only private variables and setter and getter methods to use those variables is called POJO (Plain Old Java Object) class. It is a fully encapsulated class. Live Demo class POJO { private int value=100; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } public class Test { public static void main(String args[]){ POJO p = new POJO(); System.out.println(p.getValue()); } } 100 Static classes are nested classes means a class declared within another class as a static member is called a static class. Live Demo import java.util.Scanner; class staticclasses { static int s; // static variable static void met(int a, int b) { // static method System.out.println("static method to calculate sum"); s = a + b; System.out.println(a + "+" + b); // print two numbers } static class MyNestedClass { // static class static { // static block System.out.println("static block inside a static class"); } public void disp() { int c, d; Scanner sc = new Scanner(System.in); System.out.println("Enter two values"); c = sc.nextInt(); d = sc.nextInt(); met(c, d); // calling static method System.out.println("Sum of two numbers-" + s); // print the result in static variable } } } public class Test { public static void main(String args[]) { staticclasses.MyNestedClass mnc = new staticclasses.MyNestedClass(); // object for static class mnc.disp(); // accessing methods inside a static class } } static block inside a static class Enter two values 10 20 static method to calculate sum 10+20 Sum of two numbers-30 A class declared within another class or method is called an inner class. Live Demo public class OuterClass { public static void main(String[] args) { System.out.println("Outer"); } class InnerClass { public void inner_print() { System.out.println("Inner"); } } } Outer
[ { "code": null, "e": 1250, "s": 1062, "text": "Any normal class which does not have any abstract method or a class that has an implementation of all the methods of its parent class or interface and its own methods is a concrete class." }, { "code": null, "e": 1260, "s": 1250, "text": "Live Demo" }, { "code": null, "e": 1488, "s": 1260, "text": "public class Concrete { // Concrete Class\n static int product(int a, int b) {\n return a * b;\n }\n public static void main(String args[]) {\n int p = product(2, 3);\n System.out.println(\"Product: \" + p);\n }\n}" }, { "code": null, "e": 1499, "s": 1488, "text": "Product: 6" }, { "code": null, "e": 1738, "s": 1499, "text": "A class declared with abstract keyword and have zero or more abstract methods are known as abstract class. The abstract classes are incomplete classes, therefore, to use we strictly need to extend the abstract classes to a concrete class." }, { "code": null, "e": 1748, "s": 1738, "text": "Live Demo" }, { "code": null, "e": 2076, "s": 1748, "text": "abstract class Animal { //abstract parent class\n public abstract void sound(); //abstract method\n}\npublic class Dog extends Animal { //Dog class extends Animal class\n public void sound() {\n System.out.println(\"Woof\");\n }\n public static void main(String args[]) {\n Animal a = new Dog();\n a.sound();\n }\n}" }, { "code": null, "e": 2081, "s": 2076, "text": "Woof" }, { "code": null, "e": 2219, "s": 2081, "text": "A class declared with the final keyword is a final class and it cannot be extended by another class, for example, java.lang.System class." }, { "code": null, "e": 2229, "s": 2219, "text": "Live Demo" }, { "code": null, "e": 2672, "s": 2229, "text": "final class BaseClass {\n void Display() {\n System.out.print(\"This is Display() method of BaseClass.\");\n }\n}\nclass DerivedClass extends BaseClass { //Compile-time error - can't inherit final class\n void Display() {\n System.out.print(\"This is Display() method of DerivedClass.\");\n }\n}\npublic class FinalClassDemo {\n public static void main(String[] arg) {\n DerivedClass d = new DerivedClass();\n d.Display();\n }\n}" }, { "code": null, "e": 2832, "s": 2672, "text": "In the above example, DerivedClass extends BaseClass(final), we can't extend a final class, so compiler will throw an error. The above program doesn't execute." }, { "code": null, "e": 2915, "s": 2832, "text": "cannot inherit from final BaseClass\nCompile-time error - can't inherit final class" }, { "code": null, "e": 3093, "s": 2915, "text": "A class that contains only private variables and setter and getter methods to use those variables is called POJO (Plain Old Java Object) class. It is a fully encapsulated class." }, { "code": null, "e": 3103, "s": 3093, "text": "Live Demo" }, { "code": null, "e": 3399, "s": 3103, "text": "class POJO {\n private int value=100;\n public int getValue() {\n return value;\n }\n public void setValue(int value) {\n this.value = value;\n }\n}\npublic class Test {\n public static void main(String args[]){\n POJO p = new POJO();\n System.out.println(p.getValue());\n }\n}" }, { "code": null, "e": 3403, "s": 3399, "text": "100" }, { "code": null, "e": 3526, "s": 3403, "text": "Static classes are nested classes means a class declared within another class as a static member is called a static class." }, { "code": null, "e": 3536, "s": 3526, "text": "Live Demo" }, { "code": null, "e": 4540, "s": 3536, "text": "import java.util.Scanner;\nclass staticclasses {\n static int s; // static variable\n static void met(int a, int b) { // static method\n System.out.println(\"static method to calculate sum\");\n s = a + b;\n System.out.println(a + \"+\" + b); // print two numbers\n}\n static class MyNestedClass { // static class\n static { // static block\n System.out.println(\"static block inside a static class\");\n }\n public void disp() {\n int c, d;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter two values\");\n c = sc.nextInt();\n d = sc.nextInt();\n met(c, d); // calling static method\n System.out.println(\"Sum of two numbers-\" + s); // print the result in static variable\n }\n }\n}\npublic class Test {\n public static void main(String args[]) {\n staticclasses.MyNestedClass mnc = new staticclasses.MyNestedClass(); // object for static class\n mnc.disp(); // accessing methods inside a static class\n }\n}" }, { "code": null, "e": 4657, "s": 4540, "text": "static block inside a static class\nEnter two values 10 20\nstatic method to calculate sum\n10+20\nSum of two numbers-30" }, { "code": null, "e": 4731, "s": 4657, "text": "A class declared within another class or method is called an inner class." }, { "code": null, "e": 4741, "s": 4731, "text": "Live Demo" }, { "code": null, "e": 4960, "s": 4741, "text": "public class OuterClass {\n public static void main(String[] args) {\n System.out.println(\"Outer\");\n }\n class InnerClass {\n public void inner_print() {\n System.out.println(\"Inner\");\n }\n }\n}" }, { "code": null, "e": 4966, "s": 4960, "text": "Outer" } ]
How can MySQL COALESCE() function be used with MySQL SUM() function to customize the output?
When MySQL SUM() function got a column, having no values, an argument then it will return NULL, rather than 0, as output. But if we want to customize this output to show 0 as output then we can use MySQL COALESCE() function which accepts two arguments and returns the second argument if the first argument is NULL, otherwise, it returns the first argument. To illustrate it, we are taking the example of ‘Tender’ table having the following data − mysql> Select * from tender; +----+---------------+--------------+ | Sr | CompanyName | Tender_value | +----+---------------+--------------+ | 1 | Abc Corp. | 250.369003 | | 2 | Khaitan Corp. | 265.588989 | | 3 | Singla group. | 220.255997 | | 4 | Hero group. | 221.253006 | | 5 | Honda group | NULL | +----+---------------+--------------+ 5 rows in set (0.00 sec) MySQL SUM() function returns NULL when we try to find the total tender value quoted by ‘Honda Group’ because it is having no value in the column. mysql> Select SUM(Tender_value) From Tender Where CompanyName = 'Honda Group'; +-------------------+ | SUM(Tender_value) | +-------------------+ | NULL | +-------------------+ 1 row in set (0.00 sec) But, suppose if we want to customize this output from NULL to 0 then we can use COALESCE function with SUM() to find the total tender value quoted by ‘Honda Group’. mysql> Select COALESCE(SUM(Tender_value),0) From Tender Where CompanyName = 'Honda Group'; +-------------------------------+ | COALESCE(SUM(Tender_value),0) | +-------------------------------+ | 0.000000 | +-------------------------------+ 1 row in set (0.00 sec) Now, MySQL SUM() function returns 0 when we use COALESCE function with SUM() to find the total number of pages typed by ‘Mohan’, the name which is not in the ‘Name’ column − mysql> SELECT COALESCE(SUM(daily_typing_pages),0) FROM employee_tbl WHERE Name = ‘Mohan’; +-------------------------+ | SUM(daily_typing_pages) | +-------------------------+ | 0 | +-------------------------+ 1 row in set (0.00 sec) From the above result sets, it is clear that MySQL SUM() function will return NULL if there would be no values in the column irrespective of its data type.
[ { "code": null, "e": 1509, "s": 1062, "text": "When MySQL SUM() function got a column, having no values, an argument then it will return NULL, rather than 0, as output. But if we want to customize this output to show 0 as output then we can use MySQL COALESCE() function which accepts two arguments and returns the second argument if the first argument is NULL, otherwise, it returns the first argument. To illustrate it, we are taking the example of ‘Tender’ table having the following data −" }, { "code": null, "e": 1907, "s": 1509, "text": "mysql> Select * from tender;\n\n+----+---------------+--------------+\n| Sr | CompanyName | Tender_value |\n+----+---------------+--------------+\n| 1 | Abc Corp. | 250.369003 |\n| 2 | Khaitan Corp. | 265.588989 |\n| 3 | Singla group. | 220.255997 |\n| 4 | Hero group. | 221.253006 |\n| 5 | Honda group | NULL |\n+----+---------------+--------------+\n\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2053, "s": 1907, "text": "MySQL SUM() function returns NULL when we try to find the total tender value quoted by ‘Honda Group’ because it is having no value in the column." }, { "code": null, "e": 2268, "s": 2053, "text": "mysql> Select SUM(Tender_value) From Tender Where CompanyName = 'Honda Group';\n\n+-------------------+\n| SUM(Tender_value) |\n+-------------------+\n| NULL |\n+-------------------+\n\n1 row in set (0.00 sec)" }, { "code": null, "e": 2433, "s": 2268, "text": "But, suppose if we want to customize this output from NULL to 0 then we can use COALESCE function with SUM() to find the total tender value quoted by ‘Honda Group’." }, { "code": null, "e": 2720, "s": 2433, "text": "mysql> Select COALESCE(SUM(Tender_value),0) From Tender Where CompanyName = 'Honda Group';\n\n+-------------------------------+\n| COALESCE(SUM(Tender_value),0) |\n+-------------------------------+\n| 0.000000 |\n+-------------------------------+\n\n1 row in set (0.00 sec)" }, { "code": null, "e": 2894, "s": 2720, "text": "Now, MySQL SUM() function returns 0 when we use COALESCE function with SUM() to find the total number of pages typed by ‘Mohan’, the name which is not in the ‘Name’ column −" }, { "code": null, "e": 3150, "s": 2894, "text": "mysql> SELECT COALESCE(SUM(daily_typing_pages),0) FROM employee_tbl WHERE Name = ‘Mohan’;\n\n+-------------------------+\n| SUM(daily_typing_pages) |\n+-------------------------+\n| 0 |\n+-------------------------+\n\n1 row in set (0.00 sec)" }, { "code": null, "e": 3306, "s": 3150, "text": "From the above result sets, it is clear that MySQL SUM() function will return NULL if there would be no values in the column irrespective of its data type." } ]
Chef - ChefSpec
Test Driven Development (TDD) is a way to write unit test before writing any actual recipe code. The test should be real and should validate what a recipe does. It should actually fail as there was no recipe developed. Once the recipe is developed, the test should pass. ChefSpec is built on the popular RSpec framework and offers a tailored syntax for testing Chef recipe. Step 1 − Create a gem file containing the chefSpec gem. vipin@laptop:~/chef-repo $ subl Gemfile source 'https://rubygems.org' gem 'chefspec' Step 2 − Install the gem. vipin@laptop:~/chef-repo $ bundler install Fetching gem metadata from https://rubygems.org/ ...TRUNCATED OUTPUT... Installing chefspec (1.3.1) Using bundler (1.3.5) Your bundle is complete! Step 3 − Create a spec directory. vipin@laptop:~/chef-repo $ mkdir cookbooks/<Cookbook Name>/spec Step 4 − Create a Spec vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/spec/default_spec.rb require 'chefspec' describe 'my_cookbook::default' do let(:chef_run) { ChefSpec::ChefRunner.new( platform:'ubuntu', version:'12.04' ).converge(described_recipe) } it 'creates a greetings file, containing the platform name' do expect(chef_run).to create_file_with_content('/tmp/greeting.txt','Hello! ubuntu!') end end Step 5 − Validate ChefSpec. vipin@laptop:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb F Failures: 1) <CookBook Name> ::default creates a greetings file, containing the platform name Failure/Error: expect(chef_run.converge(described_recipe)).to create_file_with_content('/tmp/greeting.txt','Hello! ubuntu!') File content: does not match expected: Hello! ubuntu! # ./cookbooks/my_cookbook/spec/default_spec.rb:11:in `block (2 levels) in <top (required)>' Finished in 0.11152 seconds 1 example, 1 failure Failed examples: rspec ./cookbooks/my_cookbook/spec/default_spec.rb:10 # my_ cookbook::default creates a greetings file, containing the platform name Step 6 − Edit Cookbooks default recipe. vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb template '/tmp/greeting.txt' do variables greeting: 'Hello!' end Step 7 − Create a template file. vipin@laptop:~/chef-repo $ subl cookbooks/< Cookbook Name>/recipes/default.rb <%= @greeting %> <%= node['platform'] %>! Step 8 − Run the rspec again. vipin@laptop:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb . Finished in 0.10142 seconds 1 example, 0 failures In order to make it work, we need to first set up the base infrastructure for using RSpec with Chef. Then we need to ChefSpec Ruby gem and the cookbook needs a directory called spec where all the tests will be saved. Print Add Notes Bookmark this page
[ { "code": null, "e": 2651, "s": 2380, "text": "Test Driven Development (TDD) is a way to write unit test before writing any actual recipe code. The test should be real and should validate what a recipe does. It should actually fail as there was no recipe developed. Once the recipe is developed, the test should pass." }, { "code": null, "e": 2754, "s": 2651, "text": "ChefSpec is built on the popular RSpec framework and offers a tailored syntax for testing Chef recipe." }, { "code": null, "e": 2810, "s": 2754, "text": "Step 1 − Create a gem file containing the chefSpec gem." }, { "code": null, "e": 2899, "s": 2810, "text": "vipin@laptop:~/chef-repo $ subl Gemfile \nsource 'https://rubygems.org' \ngem 'chefspec' \n" }, { "code": null, "e": 2925, "s": 2899, "text": "Step 2 − Install the gem." }, { "code": null, "e": 3122, "s": 2925, "text": "vipin@laptop:~/chef-repo $ bundler install \nFetching gem metadata from https://rubygems.org/ \n...TRUNCATED OUTPUT... \nInstalling chefspec (1.3.1) \nUsing bundler (1.3.5) \nYour bundle is complete! \n" }, { "code": null, "e": 3156, "s": 3122, "text": "Step 3 − Create a spec directory." }, { "code": null, "e": 3222, "s": 3156, "text": "vipin@laptop:~/chef-repo $ mkdir cookbooks/<Cookbook Name>/spec \n" }, { "code": null, "e": 3245, "s": 3222, "text": "Step 4 − Create a Spec" }, { "code": null, "e": 3715, "s": 3245, "text": "vipin@laptop:~/chef-repo $ subl \ncookbooks/my_cookbook/spec/default_spec.rb \nrequire 'chefspec' \ndescribe 'my_cookbook::default' do \n let(:chef_run) { \n ChefSpec::ChefRunner.new( \n platform:'ubuntu', version:'12.04' \n ).converge(described_recipe) \n } \n\n it 'creates a greetings file, containing the platform \n name' do \n expect(chef_run).to \n create_file_with_content('/tmp/greeting.txt','Hello! ubuntu!') \n end \nend " }, { "code": null, "e": 3743, "s": 3715, "text": "Step 5 − Validate ChefSpec." }, { "code": null, "e": 4409, "s": 3743, "text": "vipin@laptop:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb \nF \nFailures: \n1) <CookBook Name> ::default creates a greetings file, containing the platform name \nFailure/Error: expect(chef_run.converge(described_recipe)).to \ncreate_file_with_content('/tmp/greeting.txt','Hello! ubuntu!') \nFile content: \ndoes not match expected: \nHello! ubuntu! \n# ./cookbooks/my_cookbook/spec/default_spec.rb:11:in `block \n(2 levels) in <top (required)>' \nFinished in 0.11152 seconds \n1 example, 1 failure \n\nFailed examples: \nrspec ./cookbooks/my_cookbook/spec/default_spec.rb:10 # my_ \ncookbook::default creates a greetings file, containing the \nplatform name \n" }, { "code": null, "e": 4449, "s": 4409, "text": "Step 6 − Edit Cookbooks default recipe." }, { "code": null, "e": 4598, "s": 4449, "text": "vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb \ntemplate '/tmp/greeting.txt' do \n variables greeting: 'Hello!' \nend " }, { "code": null, "e": 4631, "s": 4598, "text": "Step 7 − Create a template file." }, { "code": null, "e": 4753, "s": 4631, "text": "vipin@laptop:~/chef-repo $ subl cookbooks/< Cookbook Name>/recipes/default.rb \n<%= @greeting %> <%= node['platform'] %>! " }, { "code": null, "e": 4783, "s": 4753, "text": "Step 8 − Run the rspec again." }, { "code": null, "e": 4920, "s": 4783, "text": "vipin@laptop:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb \n. \nFinished in 0.10142 seconds \n1 example, 0 failures \n" }, { "code": null, "e": 5137, "s": 4920, "text": "In order to make it work, we need to first set up the base infrastructure for using RSpec with Chef. Then we need to ChefSpec Ruby gem and the cookbook needs a directory called spec where all the tests will be saved." }, { "code": null, "e": 5144, "s": 5137, "text": " Print" }, { "code": null, "e": 5155, "s": 5144, "text": " Add Notes" } ]
Attention in computer vision | by Javier Fernandez | Towards Data Science
Ever since the introduction of Transformer in the work “Attention is all you need”, there has been a transition in the field of NLP towards replacing Recurrent Neural Networks (RNN) with attention-based networks. In current literature, there are already many great articles that describe this method. Here are two of the best ones I found during my review: The Annotated Transformer and Transformers explained Visually. However, after researching how to implement attention in computer vision (Best found articles: Understanding Attention Modules, CBAM, Papers with Code-Attention, Self-Attention, Self-Attention and Conv), I noticed that only a few of them clearly describe the attention mechanisms and include clean code along with the theory. Hence, the goal of this article is to describe in detail the two most important attention modules in computer vision and apply them to a practical case using PyTorch. The structure of the article is as follows: Introduction to attention moduleAttention method in computer visionImplementation and results of attention-based networksConclusion Introduction to attention module Attention method in computer vision Implementation and results of attention-based networks Conclusion In the context of machine learning, attention is a technique that mimics cognitive attention, defined as the ability to choose and concentrate on relevant stimuli. In other words, attention is a method that tries to enhance the important parts while fading out the non-relevant information. Despite this mechanism can be divided into several families (Attention? Attention!), we focus on self-attention since it is the most popular type of attention for computer vision tasks. This one refers to the mechanism of relating different positions of a single sequence to compute a representation of the same sequence. To better understand this concept, let’s think of the following sentence: Bank of a river. Do we agree that the word Bank losses its contextual information if we don’t see the word River? Well, that’s actually the main idea behind self-attention. It tries to give contextual information to each word since individual meanings of the words do not represent their meanings in the sentence. As explained in An Intuitive Explanation of Self-attention, if we consider the example given above, self-attention works by comparing every word in the sentence to every other word and reweighing the word embeddings of each word to include contextual relevance. The input to the output module is the embedding for each word without contextual information while the output is a similar embedding with contextual information. Here there is listed a continuously updating list of attention modules. From the listed ones, we focus on the two most popular ones for computer vision tasks: Multi-Head Attention and Convolutional Block Attention Module (CBAM). 2.1. Multi-Head Attention Multi-Head Attention is a module for attention mechanism that runs an attention module several times in parallel. Hence, to understand its logic it is first needed to understand the Attention module. The two most commonly used attention functions are Additive Attention and Dot-Product Attention, being the latter the one of interest for this work. The basic structure of the Attention module is that there are two lists of vectors x1 and x2, one which is attended and the other one which attends. The vector x2 generates a ‘query’ while the vector x1 creates a ‘key’ and a ‘value’. The idea behind the attention function is to map the query and the set key-value pairs to an output. “The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key” [Attention is all you need]. The output is computed as follows: As mentioned in this discussion, the key/value/query concepts come from retrieval systems. For example, when typing a query on Youtube to search for some video, the search engine will map your query against a set of keys (video title, description, etc.) linked with candidate videos in the database. Then, it will present you with the best-matched videos (values). Let’s run this Dot-Product Attention before moving towards the Multi-Head attention, which is an extension of this module. Below is the implementation in PyTorch. The input is [128, 32, 1, 256], where 128 corresponds to the batch, 32 to the sequence length, 1 to the number of heads (we will increase it for multiple attention heads), and 256 are the number of features. The output is: attn_output: [128, 32, 1, 256], attn_weights: [128, 1, 32, 32]attn_output: [128, 32, 1, 256], attn_weights: [128, 1, 32, 16] Some takeaways from this basic implementation: The output will have the same shape as the query input size. The attention weights for each data have to be a matrix where the number of rows corresponds to the sequence length of the query and the number of columns to the sequence length of the key. There is no learnable parameter in the Dot-Product Attention. So, coming back to Multi-Head Attention, this one runs this explained Attention module several times in parallel. The independent attention outputs are then concatenated and linearly transformed into the expected dimension. Here is the implementation: The output is: attn_output: [128, 32, 256], attn_weights: [128, 8, 32, 32]attn_output: [128, 32, 256], attn_weights: [128, 8, 32, 32] From the code, observe that: The input to the linear layer for, for example, the query is [128, 32, 256]. However, and as is mentioned in this post, the Linear layer accepts tensors of arbitrary shape, where only the last dimension must match with the in_features argument you specified in the constructor. The output will have exactly the same shape as the input, only the last dimension will change to whatever you specified as out_features in the constructor. For our case, the input shape is a set of 128 * 32 = 4096 and 256 features. Therefore, we are applying the dense net to each of the elements of the sequence length and each data of the batch. Also, we added the residual connection and layer normalization as it is implemented in the transformer neural network. But, those should be excluded if you just want to implement the Multi-Head Attention module. So, at this point you might be wondering, why do we implement Multi-Head Attention instead of just a simple Attention module? According to the paper Attention is all you need, “multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.” In other words, dividing the features into heads allows each attention module to focus only on a set of features, giving greater power to encode multiple relationships and nuances for each word. If at this point you still want to dig more into this type of attention, I encourage you to read this article, which explains in detail all this module with great illustrations. Before finishing, I just want to mention that we have used this attention module as if we were working with sequences but this article is about images. If you understood to this point everything explained, the only difference between sequences and images is the input vector. What corresponds to the sequence length, for images will be the pixels. Therefore, if the input is [batch=128, no_channels=256, height=24, width=24] , one possible implementation could be: The output is: attn_output: [128, 256, 24, 24], attn_weights: [128, 8, 576, 576] 2.2. Convolutional Block Attention Module (CBAM) In 2018, S. Woo et al. (2018) published a new attention module named Convolutional Block Attention Module (CBAM) that, as well as convolutions operations do, emphasizes meaningful features along the channel and spatial axes. Compared to Multi-Head attention, this type of attention was intentionally made for feed-forward convolutional neural networks and can be applied at every convolutional block in deep networks. CBAM contains two sequential sub-modules called the Channel Attention Module (CAM) and the Spatial Attention Module (SAM). These two concepts are probably the two most important concepts when speaking about convolutions. While channel refers to the number of features or channels for each pixel, spatial refers to the feature maps of dimension (h x w). Spatial Attention Module (SAM): This module is comprised of a three-fold sequential operation. The first part of it is called the Channel Pool and it consists of applying Max Pooling and Average Pooling across the channels to the input (c × h × w) to generate an output with shape (2 × h × w). This is the input to a convolution layer that outputs a 1-channel feature map (1 × h × w). After passing this output through a BatchNorm and an optional ReLU, the data goes to a Sigmoid Activation layer. Channel Attention Module (CAM): This module first decomposes the input tensor into 2 subsequent vectors of dimensionality (c × 1 × 1) generated by Global Average Pooling (GAP) and Global Max Pooling (GMP). Thereafter, the output goes through a fully connected layer followed by a ReLu activation layer. For further information about CBAM, I recommend reading this great post which has great explanatory images. Here is the implementation: The output is: attn_output: [128, 256, 24, 24] After the theoretical part presented above, this section focuses on the implementation of both attention layers on a practical case. Specifically, we have selected the STL dataset and have included a white patch to some images as displayed below. The task is to create a neural network that classifies both types of images. Then, we created three classes. The first one is just a CNN while the second contains the Multi-Head attention layer and the third includes the CBAM module. Here is the code to run the training. And these are the outputs: CNN: Min train error: 0.0011167450276843738Min test error: 0.05411996720208516 CNN + Multi-Head attention: The performance improves when adding the attention layer but the attention plots do not highlight the part of the image with the white patch. Min train error: 9.811600781858942e-06Min test error: 0.04209221125441423 Since there was some overfitting and the attention layer did not do what it was supposed to, I reimplemented this layer using convolutional layers. If anyone has any suggestions, please leave them in the comments. CNN + 1DConv-based Multi-Head attention: This time, the stability and performance improve notably. Also, it is possible to observe how the output of the attention layer highlights the white patch for the images that contain it. Min train error: 0.00025470180017873645Min test error: 0.014278276459193759 CNN + CBAM attention: This one presents the best result. It is clearly possible to observe the white patch in the output of the attention layer and the training is really stable, achieving the lowest validation loss of all the models. Min train error: 2.786791462858673e-05Min test error: 0.028047989653949175 In summary, this article presents Multi-Head Attention and CBAM modules, the two most popular attention modules in computer vision. Also, it includes an implementation in PyTorch where we classify images from the CIFAR dataset that contains a white patch (added manually). For future work, I consider it interesting to include positional encoding along with the attention. Here I leave a link for anyone interested:
[ { "code": null, "e": 591, "s": 171, "text": "Ever since the introduction of Transformer in the work “Attention is all you need”, there has been a transition in the field of NLP towards replacing Recurrent Neural Networks (RNN) with attention-based networks. In current literature, there are already many great articles that describe this method. Here are two of the best ones I found during my review: The Annotated Transformer and Transformers explained Visually." }, { "code": null, "e": 1128, "s": 591, "text": "However, after researching how to implement attention in computer vision (Best found articles: Understanding Attention Modules, CBAM, Papers with Code-Attention, Self-Attention, Self-Attention and Conv), I noticed that only a few of them clearly describe the attention mechanisms and include clean code along with the theory. Hence, the goal of this article is to describe in detail the two most important attention modules in computer vision and apply them to a practical case using PyTorch. The structure of the article is as follows:" }, { "code": null, "e": 1260, "s": 1128, "text": "Introduction to attention moduleAttention method in computer visionImplementation and results of attention-based networksConclusion" }, { "code": null, "e": 1293, "s": 1260, "text": "Introduction to attention module" }, { "code": null, "e": 1329, "s": 1293, "text": "Attention method in computer vision" }, { "code": null, "e": 1384, "s": 1329, "text": "Implementation and results of attention-based networks" }, { "code": null, "e": 1395, "s": 1384, "text": "Conclusion" }, { "code": null, "e": 1686, "s": 1395, "text": "In the context of machine learning, attention is a technique that mimics cognitive attention, defined as the ability to choose and concentrate on relevant stimuli. In other words, attention is a method that tries to enhance the important parts while fading out the non-relevant information." }, { "code": null, "e": 2008, "s": 1686, "text": "Despite this mechanism can be divided into several families (Attention? Attention!), we focus on self-attention since it is the most popular type of attention for computer vision tasks. This one refers to the mechanism of relating different positions of a single sequence to compute a representation of the same sequence." }, { "code": null, "e": 2396, "s": 2008, "text": "To better understand this concept, let’s think of the following sentence: Bank of a river. Do we agree that the word Bank losses its contextual information if we don’t see the word River? Well, that’s actually the main idea behind self-attention. It tries to give contextual information to each word since individual meanings of the words do not represent their meanings in the sentence." }, { "code": null, "e": 2820, "s": 2396, "text": "As explained in An Intuitive Explanation of Self-attention, if we consider the example given above, self-attention works by comparing every word in the sentence to every other word and reweighing the word embeddings of each word to include contextual relevance. The input to the output module is the embedding for each word without contextual information while the output is a similar embedding with contextual information." }, { "code": null, "e": 3049, "s": 2820, "text": "Here there is listed a continuously updating list of attention modules. From the listed ones, we focus on the two most popular ones for computer vision tasks: Multi-Head Attention and Convolutional Block Attention Module (CBAM)." }, { "code": null, "e": 3075, "s": 3049, "text": "2.1. Multi-Head Attention" }, { "code": null, "e": 3424, "s": 3075, "text": "Multi-Head Attention is a module for attention mechanism that runs an attention module several times in parallel. Hence, to understand its logic it is first needed to understand the Attention module. The two most commonly used attention functions are Additive Attention and Dot-Product Attention, being the latter the one of interest for this work." }, { "code": null, "e": 4001, "s": 3424, "text": "The basic structure of the Attention module is that there are two lists of vectors x1 and x2, one which is attended and the other one which attends. The vector x2 generates a ‘query’ while the vector x1 creates a ‘key’ and a ‘value’. The idea behind the attention function is to map the query and the set key-value pairs to an output. “The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key” [Attention is all you need]. The output is computed as follows:" }, { "code": null, "e": 4366, "s": 4001, "text": "As mentioned in this discussion, the key/value/query concepts come from retrieval systems. For example, when typing a query on Youtube to search for some video, the search engine will map your query against a set of keys (video title, description, etc.) linked with candidate videos in the database. Then, it will present you with the best-matched videos (values)." }, { "code": null, "e": 4737, "s": 4366, "text": "Let’s run this Dot-Product Attention before moving towards the Multi-Head attention, which is an extension of this module. Below is the implementation in PyTorch. The input is [128, 32, 1, 256], where 128 corresponds to the batch, 32 to the sequence length, 1 to the number of heads (we will increase it for multiple attention heads), and 256 are the number of features." }, { "code": null, "e": 4752, "s": 4737, "text": "The output is:" }, { "code": null, "e": 4877, "s": 4752, "text": "attn_output: [128, 32, 1, 256], attn_weights: [128, 1, 32, 32]attn_output: [128, 32, 1, 256], attn_weights: [128, 1, 32, 16]" }, { "code": null, "e": 4924, "s": 4877, "text": "Some takeaways from this basic implementation:" }, { "code": null, "e": 4985, "s": 4924, "text": "The output will have the same shape as the query input size." }, { "code": null, "e": 5175, "s": 4985, "text": "The attention weights for each data have to be a matrix where the number of rows corresponds to the sequence length of the query and the number of columns to the sequence length of the key." }, { "code": null, "e": 5237, "s": 5175, "text": "There is no learnable parameter in the Dot-Product Attention." }, { "code": null, "e": 5489, "s": 5237, "text": "So, coming back to Multi-Head Attention, this one runs this explained Attention module several times in parallel. The independent attention outputs are then concatenated and linearly transformed into the expected dimension. Here is the implementation:" }, { "code": null, "e": 5504, "s": 5489, "text": "The output is:" }, { "code": null, "e": 5623, "s": 5504, "text": "attn_output: [128, 32, 256], attn_weights: [128, 8, 32, 32]attn_output: [128, 32, 256], attn_weights: [128, 8, 32, 32]" }, { "code": null, "e": 5652, "s": 5623, "text": "From the code, observe that:" }, { "code": null, "e": 6278, "s": 5652, "text": "The input to the linear layer for, for example, the query is [128, 32, 256]. However, and as is mentioned in this post, the Linear layer accepts tensors of arbitrary shape, where only the last dimension must match with the in_features argument you specified in the constructor. The output will have exactly the same shape as the input, only the last dimension will change to whatever you specified as out_features in the constructor. For our case, the input shape is a set of 128 * 32 = 4096 and 256 features. Therefore, we are applying the dense net to each of the elements of the sequence length and each data of the batch." }, { "code": null, "e": 6490, "s": 6278, "text": "Also, we added the residual connection and layer normalization as it is implemented in the transformer neural network. But, those should be excluded if you just want to implement the Multi-Head Attention module." }, { "code": null, "e": 7053, "s": 6490, "text": "So, at this point you might be wondering, why do we implement Multi-Head Attention instead of just a simple Attention module? According to the paper Attention is all you need, “multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.” In other words, dividing the features into heads allows each attention module to focus only on a set of features, giving greater power to encode multiple relationships and nuances for each word." }, { "code": null, "e": 7231, "s": 7053, "text": "If at this point you still want to dig more into this type of attention, I encourage you to read this article, which explains in detail all this module with great illustrations." }, { "code": null, "e": 7696, "s": 7231, "text": "Before finishing, I just want to mention that we have used this attention module as if we were working with sequences but this article is about images. If you understood to this point everything explained, the only difference between sequences and images is the input vector. What corresponds to the sequence length, for images will be the pixels. Therefore, if the input is [batch=128, no_channels=256, height=24, width=24] , one possible implementation could be:" }, { "code": null, "e": 7711, "s": 7696, "text": "The output is:" }, { "code": null, "e": 7777, "s": 7711, "text": "attn_output: [128, 256, 24, 24], attn_weights: [128, 8, 576, 576]" }, { "code": null, "e": 7826, "s": 7777, "text": "2.2. Convolutional Block Attention Module (CBAM)" }, { "code": null, "e": 8244, "s": 7826, "text": "In 2018, S. Woo et al. (2018) published a new attention module named Convolutional Block Attention Module (CBAM) that, as well as convolutions operations do, emphasizes meaningful features along the channel and spatial axes. Compared to Multi-Head attention, this type of attention was intentionally made for feed-forward convolutional neural networks and can be applied at every convolutional block in deep networks." }, { "code": null, "e": 8597, "s": 8244, "text": "CBAM contains two sequential sub-modules called the Channel Attention Module (CAM) and the Spatial Attention Module (SAM). These two concepts are probably the two most important concepts when speaking about convolutions. While channel refers to the number of features or channels for each pixel, spatial refers to the feature maps of dimension (h x w)." }, { "code": null, "e": 9095, "s": 8597, "text": "Spatial Attention Module (SAM): This module is comprised of a three-fold sequential operation. The first part of it is called the Channel Pool and it consists of applying Max Pooling and Average Pooling across the channels to the input (c × h × w) to generate an output with shape (2 × h × w). This is the input to a convolution layer that outputs a 1-channel feature map (1 × h × w). After passing this output through a BatchNorm and an optional ReLU, the data goes to a Sigmoid Activation layer." }, { "code": null, "e": 9398, "s": 9095, "text": "Channel Attention Module (CAM): This module first decomposes the input tensor into 2 subsequent vectors of dimensionality (c × 1 × 1) generated by Global Average Pooling (GAP) and Global Max Pooling (GMP). Thereafter, the output goes through a fully connected layer followed by a ReLu activation layer." }, { "code": null, "e": 9506, "s": 9398, "text": "For further information about CBAM, I recommend reading this great post which has great explanatory images." }, { "code": null, "e": 9534, "s": 9506, "text": "Here is the implementation:" }, { "code": null, "e": 9549, "s": 9534, "text": "The output is:" }, { "code": null, "e": 9581, "s": 9549, "text": "attn_output: [128, 256, 24, 24]" }, { "code": null, "e": 9714, "s": 9581, "text": "After the theoretical part presented above, this section focuses on the implementation of both attention layers on a practical case." }, { "code": null, "e": 9905, "s": 9714, "text": "Specifically, we have selected the STL dataset and have included a white patch to some images as displayed below. The task is to create a neural network that classifies both types of images." }, { "code": null, "e": 10062, "s": 9905, "text": "Then, we created three classes. The first one is just a CNN while the second contains the Multi-Head attention layer and the third includes the CBAM module." }, { "code": null, "e": 10100, "s": 10062, "text": "Here is the code to run the training." }, { "code": null, "e": 10127, "s": 10100, "text": "And these are the outputs:" }, { "code": null, "e": 10132, "s": 10127, "text": "CNN:" }, { "code": null, "e": 10206, "s": 10132, "text": "Min train error: 0.0011167450276843738Min test error: 0.05411996720208516" }, { "code": null, "e": 10376, "s": 10206, "text": "CNN + Multi-Head attention: The performance improves when adding the attention layer but the attention plots do not highlight the part of the image with the white patch." }, { "code": null, "e": 10450, "s": 10376, "text": "Min train error: 9.811600781858942e-06Min test error: 0.04209221125441423" }, { "code": null, "e": 10664, "s": 10450, "text": "Since there was some overfitting and the attention layer did not do what it was supposed to, I reimplemented this layer using convolutional layers. If anyone has any suggestions, please leave them in the comments." }, { "code": null, "e": 10892, "s": 10664, "text": "CNN + 1DConv-based Multi-Head attention: This time, the stability and performance improve notably. Also, it is possible to observe how the output of the attention layer highlights the white patch for the images that contain it." }, { "code": null, "e": 10968, "s": 10892, "text": "Min train error: 0.00025470180017873645Min test error: 0.014278276459193759" }, { "code": null, "e": 11203, "s": 10968, "text": "CNN + CBAM attention: This one presents the best result. It is clearly possible to observe the white patch in the output of the attention layer and the training is really stable, achieving the lowest validation loss of all the models." }, { "code": null, "e": 11278, "s": 11203, "text": "Min train error: 2.786791462858673e-05Min test error: 0.028047989653949175" }, { "code": null, "e": 11551, "s": 11278, "text": "In summary, this article presents Multi-Head Attention and CBAM modules, the two most popular attention modules in computer vision. Also, it includes an implementation in PyTorch where we classify images from the CIFAR dataset that contains a white patch (added manually)." } ]
How to splice duplicate item in array JavaScript
We have an array of Number / String literals that contain some duplicate values, we have to remove these values from the array without creating a new array or storing the duplicate values anywhere else. We will use the Array.prototype.splice() method to remove entries inplace, and we will take help of Array.prototype.indexOf() and Array.prototype.lastIndexOf() method to determine the duplicacy of any element. const arr = [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5]; arr.forEach((el, ind, array) => { if(array.indexOf(el) !== array.lastIndexOf(el)){ array.splice(ind, 1); } }); console.log(arr); The output in the console will be − [ 4, 1, 5, 2, 6, 8, 7 ]
[ { "code": null, "e": 1265, "s": 1062, "text": "We have an array of Number / String literals that contain some duplicate values, we have to\nremove these values from the array without creating a new array or storing the duplicate values\nanywhere else." }, { "code": null, "e": 1475, "s": 1265, "text": "We will use the Array.prototype.splice() method to remove entries inplace, and we will take help\nof Array.prototype.indexOf() and Array.prototype.lastIndexOf() method to determine the\nduplicacy of any element." }, { "code": null, "e": 1666, "s": 1475, "text": "const arr = [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5];\narr.forEach((el, ind, array) => {\n if(array.indexOf(el) !== array.lastIndexOf(el)){\n array.splice(ind, 1);\n }\n});\nconsole.log(arr);" }, { "code": null, "e": 1702, "s": 1666, "text": "The output in the console will be −" }, { "code": null, "e": 1732, "s": 1702, "text": "[\n 4, 1, 5, 2,\n 6, 8, 7\n]" } ]
Ngx-Bootstrap - accordion
Accordion is a control to display collapsible panels and it is used to display information in limited space. Displays collapsible content panels for presenting information in a limited amount of space. accordion accordion closeOthers − boolean, if true expanding one item will close all others closeOthers − boolean, if true expanding one item will close all others isAnimated − boolean, turn on/off animation, default: false isAnimated − boolean, turn on/off animation, default: false Instead of using heading attribute on the accordion-group, you can use an accordion-heading attribute on any element inside of a group that will be used as group's header template. accordion-group, accordion-panel accordion-group, accordion-panel heading − string, Clickable text in accordion's group header heading − string, Clickable text in accordion's group header isDisabled − boolean, enables/disables accordion group isDisabled − boolean, enables/disables accordion group isOpen − boolean, Is accordion group open or closed. This property supports two-way binding isOpen − boolean, Is accordion group open or closed. This property supports two-way binding panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...). panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...). isOpenChange − Emits when the opened state changes isOpenChange − Emits when the opened state changes Configuration service, provides default values for the AccordionComponent. closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false isAnimated − boolean, turn on/off animation isAnimated − boolean, turn on/off animation As we're going to use accordion, We've updated app.module.ts to use AccordionModule as in ngx-bootstrap Environment Setup chapter. Update test.component.html to use the accordion. test.component.html <accordion> <accordion-group heading="Open By Default" [isOpen]="open"> <p>Open By Default</p> </accordion-group> <accordion-group heading="Disabled" [isDisabled]="disabled"> <p>Disabled</p> </accordion-group> <accordion-group heading="with isOpenChange" (isOpenChange)="log($event)"> <p>Open Event</p> </accordion-group> </accordion> Update test.component.ts for corresponding variables and methods. test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { open: boolean = true; disabled: boolean = true; constructor() { } ngOnInit(): void { } log(isOpened: boolean){ console.log(isOpened); } } Run the following command to start the angular server. ng serve Once server is up and running. Open http://localhost:4200 and verify the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2209, "s": 2100, "text": "Accordion is a control to display collapsible panels and it is used to display information in limited space." }, { "code": null, "e": 2302, "s": 2209, "text": "Displays collapsible content panels for presenting information in a limited amount of space." }, { "code": null, "e": 2312, "s": 2302, "text": "accordion" }, { "code": null, "e": 2322, "s": 2312, "text": "accordion" }, { "code": null, "e": 2394, "s": 2322, "text": "closeOthers − boolean, if true expanding one item will close all others" }, { "code": null, "e": 2466, "s": 2394, "text": "closeOthers − boolean, if true expanding one item will close all others" }, { "code": null, "e": 2526, "s": 2466, "text": "isAnimated − boolean, turn on/off animation, default: false" }, { "code": null, "e": 2586, "s": 2526, "text": "isAnimated − boolean, turn on/off animation, default: false" }, { "code": null, "e": 2767, "s": 2586, "text": "Instead of using heading attribute on the accordion-group, you can use an accordion-heading attribute on any element inside of a group that will be used as group's header template." }, { "code": null, "e": 2800, "s": 2767, "text": "accordion-group, accordion-panel" }, { "code": null, "e": 2833, "s": 2800, "text": "accordion-group, accordion-panel" }, { "code": null, "e": 2894, "s": 2833, "text": "heading − string, Clickable text in accordion's group header" }, { "code": null, "e": 2955, "s": 2894, "text": "heading − string, Clickable text in accordion's group header" }, { "code": null, "e": 3010, "s": 2955, "text": "isDisabled − boolean, enables/disables accordion group" }, { "code": null, "e": 3065, "s": 3010, "text": "isDisabled − boolean, enables/disables accordion group" }, { "code": null, "e": 3157, "s": 3065, "text": "isOpen − boolean, Is accordion group open or closed. This property supports two-way binding" }, { "code": null, "e": 3249, "s": 3157, "text": "isOpen − boolean, Is accordion group open or closed. This property supports two-way binding" }, { "code": null, "e": 3386, "s": 3249, "text": "panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...)." }, { "code": null, "e": 3523, "s": 3386, "text": "panelClass − string, Provides an ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...)." }, { "code": null, "e": 3574, "s": 3523, "text": "isOpenChange − Emits when the opened state changes" }, { "code": null, "e": 3625, "s": 3574, "text": "isOpenChange − Emits when the opened state changes" }, { "code": null, "e": 3700, "s": 3625, "text": "Configuration service, provides default values for the AccordionComponent." }, { "code": null, "e": 3804, "s": 3700, "text": "closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false" }, { "code": null, "e": 3908, "s": 3804, "text": "closeOthers − boolean, Whether the other panels should be closed when a panel is opened. Default: false" }, { "code": null, "e": 3952, "s": 3908, "text": "isAnimated − boolean, turn on/off animation" }, { "code": null, "e": 3996, "s": 3952, "text": "isAnimated − boolean, turn on/off animation" }, { "code": null, "e": 4127, "s": 3996, "text": "As we're going to use accordion, We've updated app.module.ts to use AccordionModule as in ngx-bootstrap Environment Setup chapter." }, { "code": null, "e": 4176, "s": 4127, "text": "Update test.component.html to use the accordion." }, { "code": null, "e": 4196, "s": 4176, "text": "test.component.html" }, { "code": null, "e": 4567, "s": 4196, "text": "<accordion>\n <accordion-group heading=\"Open By Default\" [isOpen]=\"open\">\n <p>Open By Default</p>\n </accordion-group>\n <accordion-group heading=\"Disabled\" [isDisabled]=\"disabled\">\n <p>Disabled</p>\n </accordion-group>\n <accordion-group heading=\"with isOpenChange\" (isOpenChange)=\"log($event)\">\n <p>Open Event</p>\n </accordion-group>\n</accordion>" }, { "code": null, "e": 4633, "s": 4567, "text": "Update test.component.ts for corresponding variables and methods." }, { "code": null, "e": 4651, "s": 4633, "text": "test.component.ts" }, { "code": null, "e": 5035, "s": 4651, "text": "import { Component, OnInit } from '@angular/core';\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\nexport class TestComponent implements OnInit {\n open: boolean = true;\n disabled: boolean = true;\n constructor() { }\n ngOnInit(): void {\n }\n log(isOpened: boolean){\n console.log(isOpened);\n }\n}" }, { "code": null, "e": 5090, "s": 5035, "text": "Run the following command to start the angular server." }, { "code": null, "e": 5100, "s": 5090, "text": "ng serve\n" }, { "code": null, "e": 5191, "s": 5100, "text": "Once server is up and running. Open http://localhost:4200 and verify the following output." }, { "code": null, "e": 5198, "s": 5191, "text": " Print" }, { "code": null, "e": 5209, "s": 5198, "text": " Add Notes" } ]
Deploying Keras Deep Learning Models with Java | by Ben Weber | Towards Data Science
The Keras library provides an approachable interface to deep learning, making neural networks accessible to a broad audience. However, one of the challenges I’ve faced is transitioning from exploring models in Keras to productizing models. Keras is written in Python, and until recently had limited support outside of these languages. While tools such as Flask, PySpark, and Cloud ML make it possible to productize these models directly in Python, I usually prefer Java for deploying models. Projects such as ONNX are moving towards standardization of deep learning, but the runtimes that support these formats are still limited. One approach that’s often used is converting Keras models to TensorFlow graphs, and then using these graphs in other runtines that support TensorFlow. I recently discovered the Deeplearning4J (DL4J) project, which natively supports Keras models, making it easy to get up and running with deep learning in Java. deeplearning4j.org One of the use cases that I’ve been exploring for deep learning is training models in Python using Keras, and then productizing models using Java. This is useful for situations where you need deep learning directly on the client, such as Android devices applying models, as well as situations where you want to leverage existing production systems written in Java. A DL4J introduction to using Keras is available here. This post provides an overview of training a Keras model in Python, and deploying it with Java. I use Jetty to provide real-time predictions and Google’s DataFlow to build a batch prediction system. The full code and data needed to run these examples is available on GitHub. github.com The first step is to train a model using the Keras library in Python. Once you have a model that is ready to deploy, you can save it in the h5 format and utilize it in Python and Java applications.For this tutorial, we’ll use the same model that I trained for predicting which players are likely to purchase a new game in my blog post on Flask. towardsdatascience.com The input to the model is ten binary features (G1, G2, ... ,G10) that describe the games that a player has already purchased, and the label is a single variable that describes if the user purchased a game not included in the inputs. The main steps involved in the training process are shown below: import kerasfrom keras import models, layers# Define the model structuremodel = models.Sequential()model.add(layers.Dense(64, activation='relu', input_shape=(10,)))...model.add(layers.Dense(1, activation='sigmoid'))# Compile and fit the modelmodel.compile(optimizer='rmsprop',loss='binary_crossentropy', metrics=[auc])history = model.fit(x, y, epochs=100, batch_size=100, validation_split = .2, verbose=0)# Save the model in h5 format model.save("games.h5") The output of this process is an h5 file that represents the trained model that we can deploy in Python and Java applications. In my past post, I showed how to use Flask to serve real-time model predictions in Python. In this post, I’ll show how to build batch and real-time predictions in Java. To deploy Keras models with Java, we’ll use the Deeplearing4j library. It provides functionality for deep learning in Java and can load and utilize models trained with Keras. We’ll also use Dataflow for batch predictions and Jetty for real-time predictions. Here’s the libraries I used for this project: Deeplearning4j: Provides deep neural network functionality for Java. ND4J: Provides tensor operations for Java. Jetty: Used for setting up a web endpoint. Cloud DataFlow: Provides autoscaling for batch predictions on GCP. I imported these into my project using the pom.xml shown below. For DL4J, boths the core and modelimport libraries are needed when using Keras. <dependencies> <dependency> <groupId>org.deeplearning4j</groupId> <artifactId>deeplearning4j-core</artifactId> <version>1.0.0-beta2</version> </dependency> <dependency> <groupId>org.deeplearning4j</groupId> <artifactId>deeplearning4j-modelimport</artifactId> <version>1.0.0-beta2</version> </dependency> <dependency> <groupId>org.nd4j</groupId> <artifactId>nd4j-native-platform</artifactId> <version>1.0.0-beta2</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>9.4.9.v20180320</version> </dependency> <dependency> <groupId>com.google.cloud.dataflow</groupId> <artifactId>google-cloud-dataflow-java-sdk-all</artifactId> <version>2.2.0</version> </dependency></dependencies> I set up my project in Eclipse, and once I got the pom file properly configured, no additional setup was needed to get started. Now that we have the libraries set up, we can start making predictions with the Keras model. I wrote the script below to test out loading a Keras model and making a prediction for a sample data set. The first step is to load the model from the h5 file. Next, I define a 1D tensor of length 10 and generate random binary values. The last step is to call the output method on the model to generate a prediction. Since my model has a single output node, I use getDouble(0) to return the output of the model. // importsimport org.deeplearning4j.nn.modelimport.keras.KerasModelImport;import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;import org.nd4j.linalg.api.ndarray.INDArray;import org.nd4j.linalg.factory.Nd4j;import org.nd4j.linalg.io.ClassPathResource;// load the modelString simpleMlp = new ClassPathResource( "games.h5").getFile().getPath();MultiLayerNetwork model = KerasModelImport. importKerasSequentialModelAndWeights(simpleMlp);// make a random sampleint inputs = 10;INDArray features = Nd4j.zeros(inputs);for (int i=0; i<inputs; i++) features.putScalar(new int[] {i}, Math.random() < 0.5 ? 0 : 1);// get the predictiondouble prediction = model.output(features).getDouble(0); One of the key concepts to become familiar with when using DL4J is tensors. Java does not have a built-in library for efficient tensor options, which is why NDJ4 is a prerequisite. It provides N-Dimensional arrays for implementing deep learning backends in Java. To set a value in the tensor object, you pass an integer array which provides a n-dimensional index to the tensor, and the value to set. Since I am using a 1D tensor, the array is of length one. The model object provides predict and output methods. The predict method returns a class prediction (0 or 1), while the output method returns a continuous label, similar to predict_proba in scikit-learn. Now that we have a Keras model up and running in Java, we can start serving model predictions. The first approach we’ll take is using Jetty to set up an endpoint on the web for providing model predictions. I previously covered setup for Jetty in my posts on tracking data and model production. The full code for the model endpoint is available here. The model endpoint is implemented as a single class that loads the Keras model and provides predictions. It implements Jetty’s AbstractHandler interface to provide model results. The code below shows how to set up the Jetty service to run on port 8080 and instantiate the JettyDL4J class which loads the Keras model in the constructor. // Setting up the web endpointServer server = new Server(8080);server.setHandler(new JettyDL4J());server.start();server.join();// Load the Keras model public JettyDL4J() throws Exception { String p=new ClassPathResource("games.h5").getFile().getPath(); model=KerasModelImport.importKerasSequentialModelAndWeights(p); } The handler for managing web requests is shown in the code snippet below. The passed-in parameters (G1,G2, ...,G10) are converted into a 1D tensor object and passed to the output method of the Keras model. The request is then marked as handled and the prediction is returned as string. // Entry point for the model prediction request public void handle(String target,Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // create a dataset from the input parameters INDArray features = Nd4j.zeros(inputs); for (int i=0; i<inputs; i++) features.putScalar(new int[] {i}, Double.parseDouble( baseRequest.getParameter("G" + (i + 1)))); // output the estimate double prediction = model.output(features).getDouble(0); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("Prediction: " + prediction); baseRequest.setHandled(true);} When you run the class, it sets up an endpoint on port 8080. You can call the model service by pointing your browser to the following URL: // Requesthttp://localhost:8080/?G1=1&G2=0&G3=1&G4=1&G5=0&G6=1&G7=0&G8=1&G9=1&G10=1// ResultPrediction: 0.735433042049408 The result is a Keras model that you can now invoke in real-time to get predictions from your deep learning model. For a production system, you’d want to set up a service in front of the Jetty endpoint, rather than exposing the endpoint directly on the web. Another use case for Keras models is batch predictions, where you may need to apply the estimator to millions and millions of records. You can do this directly in Python with your Keras model, but scalability is limited with this approach. I’ll show how to use Google’s DataFlow to apply predictions to massive data sets using a full-managed pipeline. I previously covered setting up DataFlow in my past posts on model production and game simulations. With DataFlow, you specify a graph of operations to perform on a data set, where the source and destination data sets can be relational databases, messaging services, application databases, and other services. The graphs can be executed as a batch operation, where infrastructure is spun up to handle a large data set and then spun down, or in streaming mode, where infrastructure is maintained and requests are process as they arrive. In both scenarios, the service will autoscale to meet demand. It’s fully managed and great for large calculations that can be performed independently. The DAG of operations in my DataFlow process is shown above. The first step is to create a dataset for the model to score. In this example, I’m loading values from my sample CSV, while in practice I’d usually use BigQuery as both the source and sync for model predictions. The next step is a transformation which takes TableRow objects as the input, transforms the rows to 1D tensors, applies the model to each tensor, and create a new output TableRow with the predicted value. The complete code for the DAG is available here. The key step in this pipeline is the Keras Predict transformation, which is shown in the code snippet below. A transformation operates on a collection of objects and returns a collection of objects. Within a transformer, you can define objects such as the Keras model, which are shared across each of the process element steps defined in the transformer. The result is that the model is loaded once for each transformer, rather than loaded for each record that needs a prediction. // Apply the transform to the pipeline.apply("Keras Predict", new PTransform<PCollection<TableRow>, PCollection<TableRow>>() { // Load the model in the transformer public PCollection<TableRow> expand(PCollection<TableRow> input) { final int inputs = 10; final MultiLayerNetwork model; try { String p= newClassPathResource("games.h5").getFile().getPath(); model=KerasModelImport.importKerasSequentialModelAndWeights(p); } catch (Exception e) { throw new RuntimeException(e); } // create a DoFn for applying the Keras model to instances return input.apply("Pred",ParDo.of(new DoFn<TableRow,TableRow>(){ @ProcessElement public void processElement(ProcessContext c) throws Exception { ... // Apply the Keras model }})); }}) The code for the process element method is shown below. It reads the input record, creates a tensor from the table row, applies the model, and then saves the record. The output row contains the predicted and actual values. // get the record to score TableRow row = c.element(); // create the feature vector INDArray features = Nd4j.zeros(inputs); for (int i=0; i<inputs; i++) features.putScalar(new int[] {i}, Double.parseDouble(row.get("G" + (i+1)).toString())); // get the prediction double estimate = model.output(features).getDouble(0); // save the result TableRow prediction = new TableRow(); prediction.set("actual", row.get("actual")); prediction.set("predicted", estimate); c.output(prediction); I’ve excluded the CSV loading and BigQuery writing code blocks in this post, since you may be working with different endpoints. The code and CSV is available on GitHub if you want to try running the DAG. To save the results to BigQuery, you’ll need to set the tempLocation program argument as follows: --tempLocation=gs://your-gs-bucket/temp-dataflow-location After running the DAG, a new table will be created in BigQuery with the actual and predicted values for the dataset. The image below shows sample data points from my application of the Keras model. The result of using DataFlow with DL4J is that you can score millions of records using autoscaling infrastructure for batch predictions. As deep learning becomes increasingly popular, more languages and environments are supporting these models. As libraries start to standardize on model formats, it’s becoming possible to use separate languages for model training and model deployment. This post showed how neural networks trained using the Keras library in Python can be used for batch and real-time predictions using the DL4J library in Java. For the first time, I’ve been able to set up a batch process for applying deep learning to millions of data points. Ben Weber is a principal data scientist at Zynga. We are hiring!
[ { "code": null, "e": 664, "s": 172, "text": "The Keras library provides an approachable interface to deep learning, making neural networks accessible to a broad audience. However, one of the challenges I’ve faced is transitioning from exploring models in Keras to productizing models. Keras is written in Python, and until recently had limited support outside of these languages. While tools such as Flask, PySpark, and Cloud ML make it possible to productize these models directly in Python, I usually prefer Java for deploying models." }, { "code": null, "e": 1113, "s": 664, "text": "Projects such as ONNX are moving towards standardization of deep learning, but the runtimes that support these formats are still limited. One approach that’s often used is converting Keras models to TensorFlow graphs, and then using these graphs in other runtines that support TensorFlow. I recently discovered the Deeplearning4J (DL4J) project, which natively supports Keras models, making it easy to get up and running with deep learning in Java." }, { "code": null, "e": 1132, "s": 1113, "text": "deeplearning4j.org" }, { "code": null, "e": 1551, "s": 1132, "text": "One of the use cases that I’ve been exploring for deep learning is training models in Python using Keras, and then productizing models using Java. This is useful for situations where you need deep learning directly on the client, such as Android devices applying models, as well as situations where you want to leverage existing production systems written in Java. A DL4J introduction to using Keras is available here." }, { "code": null, "e": 1826, "s": 1551, "text": "This post provides an overview of training a Keras model in Python, and deploying it with Java. I use Jetty to provide real-time predictions and Google’s DataFlow to build a batch prediction system. The full code and data needed to run these examples is available on GitHub." }, { "code": null, "e": 1837, "s": 1826, "text": "github.com" }, { "code": null, "e": 2182, "s": 1837, "text": "The first step is to train a model using the Keras library in Python. Once you have a model that is ready to deploy, you can save it in the h5 format and utilize it in Python and Java applications.For this tutorial, we’ll use the same model that I trained for predicting which players are likely to purchase a new game in my blog post on Flask." }, { "code": null, "e": 2205, "s": 2182, "text": "towardsdatascience.com" }, { "code": null, "e": 2503, "s": 2205, "text": "The input to the model is ten binary features (G1, G2, ... ,G10) that describe the games that a player has already purchased, and the label is a single variable that describes if the user purchased a game not included in the inputs. The main steps involved in the training process are shown below:" }, { "code": null, "e": 2993, "s": 2503, "text": "import kerasfrom keras import models, layers# Define the model structuremodel = models.Sequential()model.add(layers.Dense(64, activation='relu', input_shape=(10,)))...model.add(layers.Dense(1, activation='sigmoid'))# Compile and fit the modelmodel.compile(optimizer='rmsprop',loss='binary_crossentropy', metrics=[auc])history = model.fit(x, y, epochs=100, batch_size=100, validation_split = .2, verbose=0)# Save the model in h5 format model.save(\"games.h5\")" }, { "code": null, "e": 3289, "s": 2993, "text": "The output of this process is an h5 file that represents the trained model that we can deploy in Python and Java applications. In my past post, I showed how to use Flask to serve real-time model predictions in Python. In this post, I’ll show how to build batch and real-time predictions in Java." }, { "code": null, "e": 3593, "s": 3289, "text": "To deploy Keras models with Java, we’ll use the Deeplearing4j library. It provides functionality for deep learning in Java and can load and utilize models trained with Keras. We’ll also use Dataflow for batch predictions and Jetty for real-time predictions. Here’s the libraries I used for this project:" }, { "code": null, "e": 3662, "s": 3593, "text": "Deeplearning4j: Provides deep neural network functionality for Java." }, { "code": null, "e": 3705, "s": 3662, "text": "ND4J: Provides tensor operations for Java." }, { "code": null, "e": 3748, "s": 3705, "text": "Jetty: Used for setting up a web endpoint." }, { "code": null, "e": 3815, "s": 3748, "text": "Cloud DataFlow: Provides autoscaling for batch predictions on GCP." }, { "code": null, "e": 3959, "s": 3815, "text": "I imported these into my project using the pom.xml shown below. For DL4J, boths the core and modelimport libraries are needed when using Keras." }, { "code": null, "e": 4885, "s": 3959, "text": "<dependencies> <dependency> <groupId>org.deeplearning4j</groupId> <artifactId>deeplearning4j-core</artifactId> <version>1.0.0-beta2</version> </dependency> <dependency> <groupId>org.deeplearning4j</groupId> <artifactId>deeplearning4j-modelimport</artifactId> <version>1.0.0-beta2</version> </dependency> <dependency> <groupId>org.nd4j</groupId> <artifactId>nd4j-native-platform</artifactId> <version>1.0.0-beta2</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>9.4.9.v20180320</version> </dependency> <dependency> <groupId>com.google.cloud.dataflow</groupId> <artifactId>google-cloud-dataflow-java-sdk-all</artifactId> <version>2.2.0</version> </dependency></dependencies>" }, { "code": null, "e": 5013, "s": 4885, "text": "I set up my project in Eclipse, and once I got the pom file properly configured, no additional setup was needed to get started." }, { "code": null, "e": 5518, "s": 5013, "text": "Now that we have the libraries set up, we can start making predictions with the Keras model. I wrote the script below to test out loading a Keras model and making a prediction for a sample data set. The first step is to load the model from the h5 file. Next, I define a 1D tensor of length 10 and generate random binary values. The last step is to call the output method on the model to generate a prediction. Since my model has a single output node, I use getDouble(0) to return the output of the model." }, { "code": null, "e": 6253, "s": 5518, "text": "// importsimport org.deeplearning4j.nn.modelimport.keras.KerasModelImport;import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;import org.nd4j.linalg.api.ndarray.INDArray;import org.nd4j.linalg.factory.Nd4j;import org.nd4j.linalg.io.ClassPathResource;// load the modelString simpleMlp = new ClassPathResource( \"games.h5\").getFile().getPath();MultiLayerNetwork model = KerasModelImport. importKerasSequentialModelAndWeights(simpleMlp);// make a random sampleint inputs = 10;INDArray features = Nd4j.zeros(inputs);for (int i=0; i<inputs; i++) features.putScalar(new int[] {i}, Math.random() < 0.5 ? 0 : 1);// get the predictiondouble prediction = model.output(features).getDouble(0);" }, { "code": null, "e": 6711, "s": 6253, "text": "One of the key concepts to become familiar with when using DL4J is tensors. Java does not have a built-in library for efficient tensor options, which is why NDJ4 is a prerequisite. It provides N-Dimensional arrays for implementing deep learning backends in Java. To set a value in the tensor object, you pass an integer array which provides a n-dimensional index to the tensor, and the value to set. Since I am using a 1D tensor, the array is of length one." }, { "code": null, "e": 6915, "s": 6711, "text": "The model object provides predict and output methods. The predict method returns a class prediction (0 or 1), while the output method returns a continuous label, similar to predict_proba in scikit-learn." }, { "code": null, "e": 7265, "s": 6915, "text": "Now that we have a Keras model up and running in Java, we can start serving model predictions. The first approach we’ll take is using Jetty to set up an endpoint on the web for providing model predictions. I previously covered setup for Jetty in my posts on tracking data and model production. The full code for the model endpoint is available here." }, { "code": null, "e": 7601, "s": 7265, "text": "The model endpoint is implemented as a single class that loads the Keras model and provides predictions. It implements Jetty’s AbstractHandler interface to provide model results. The code below shows how to set up the Jetty service to run on port 8080 and instantiate the JettyDL4J class which loads the Keras model in the constructor." }, { "code": null, "e": 7929, "s": 7601, "text": "// Setting up the web endpointServer server = new Server(8080);server.setHandler(new JettyDL4J());server.start();server.join();// Load the Keras model public JettyDL4J() throws Exception { String p=new ClassPathResource(\"games.h5\").getFile().getPath(); model=KerasModelImport.importKerasSequentialModelAndWeights(p); }" }, { "code": null, "e": 8215, "s": 7929, "text": "The handler for managing web requests is shown in the code snippet below. The passed-in parameters (G1,G2, ...,G10) are converted into a 1D tensor object and passed to the output method of the Keras model. The request is then marked as handled and the prediction is returned as string." }, { "code": null, "e": 8891, "s": 8215, "text": "// Entry point for the model prediction request public void handle(String target,Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // create a dataset from the input parameters INDArray features = Nd4j.zeros(inputs); for (int i=0; i<inputs; i++) features.putScalar(new int[] {i}, Double.parseDouble( baseRequest.getParameter(\"G\" + (i + 1)))); // output the estimate double prediction = model.output(features).getDouble(0); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(\"Prediction: \" + prediction); baseRequest.setHandled(true);}" }, { "code": null, "e": 9030, "s": 8891, "text": "When you run the class, it sets up an endpoint on port 8080. You can call the model service by pointing your browser to the following URL:" }, { "code": null, "e": 9152, "s": 9030, "text": "// Requesthttp://localhost:8080/?G1=1&G2=0&G3=1&G4=1&G5=0&G6=1&G7=0&G8=1&G9=1&G10=1// ResultPrediction: 0.735433042049408" }, { "code": null, "e": 9410, "s": 9152, "text": "The result is a Keras model that you can now invoke in real-time to get predictions from your deep learning model. For a production system, you’d want to set up a service in front of the Jetty endpoint, rather than exposing the endpoint directly on the web." }, { "code": null, "e": 9862, "s": 9410, "text": "Another use case for Keras models is batch predictions, where you may need to apply the estimator to millions and millions of records. You can do this directly in Python with your Keras model, but scalability is limited with this approach. I’ll show how to use Google’s DataFlow to apply predictions to massive data sets using a full-managed pipeline. I previously covered setting up DataFlow in my past posts on model production and game simulations." }, { "code": null, "e": 10449, "s": 9862, "text": "With DataFlow, you specify a graph of operations to perform on a data set, where the source and destination data sets can be relational databases, messaging services, application databases, and other services. The graphs can be executed as a batch operation, where infrastructure is spun up to handle a large data set and then spun down, or in streaming mode, where infrastructure is maintained and requests are process as they arrive. In both scenarios, the service will autoscale to meet demand. It’s fully managed and great for large calculations that can be performed independently." }, { "code": null, "e": 10976, "s": 10449, "text": "The DAG of operations in my DataFlow process is shown above. The first step is to create a dataset for the model to score. In this example, I’m loading values from my sample CSV, while in practice I’d usually use BigQuery as both the source and sync for model predictions. The next step is a transformation which takes TableRow objects as the input, transforms the rows to 1D tensors, applies the model to each tensor, and create a new output TableRow with the predicted value. The complete code for the DAG is available here." }, { "code": null, "e": 11457, "s": 10976, "text": "The key step in this pipeline is the Keras Predict transformation, which is shown in the code snippet below. A transformation operates on a collection of objects and returns a collection of objects. Within a transformer, you can define objects such as the Keras model, which are shared across each of the process element steps defined in the transformer. The result is that the model is loaded once for each transformer, rather than loaded for each record that needs a prediction." }, { "code": null, "e": 12329, "s": 11457, "text": "// Apply the transform to the pipeline.apply(\"Keras Predict\", new PTransform<PCollection<TableRow>, PCollection<TableRow>>() { // Load the model in the transformer public PCollection<TableRow> expand(PCollection<TableRow> input) { final int inputs = 10; final MultiLayerNetwork model; try { String p= newClassPathResource(\"games.h5\").getFile().getPath(); model=KerasModelImport.importKerasSequentialModelAndWeights(p); } catch (Exception e) { throw new RuntimeException(e); } // create a DoFn for applying the Keras model to instances return input.apply(\"Pred\",ParDo.of(new DoFn<TableRow,TableRow>(){ @ProcessElement public void processElement(ProcessContext c) throws Exception { ... // Apply the Keras model }})); }})" }, { "code": null, "e": 12552, "s": 12329, "text": "The code for the process element method is shown below. It reads the input record, creates a tensor from the table row, applies the model, and then saves the record. The output row contains the predicted and actual values." }, { "code": null, "e": 13278, "s": 12552, "text": " // get the record to score TableRow row = c.element(); // create the feature vector INDArray features = Nd4j.zeros(inputs); for (int i=0; i<inputs; i++) features.putScalar(new int[] {i}, Double.parseDouble(row.get(\"G\" + (i+1)).toString())); // get the prediction double estimate = model.output(features).getDouble(0); // save the result TableRow prediction = new TableRow(); prediction.set(\"actual\", row.get(\"actual\")); prediction.set(\"predicted\", estimate); c.output(prediction);" }, { "code": null, "e": 13580, "s": 13278, "text": "I’ve excluded the CSV loading and BigQuery writing code blocks in this post, since you may be working with different endpoints. The code and CSV is available on GitHub if you want to try running the DAG. To save the results to BigQuery, you’ll need to set the tempLocation program argument as follows:" }, { "code": null, "e": 13638, "s": 13580, "text": "--tempLocation=gs://your-gs-bucket/temp-dataflow-location" }, { "code": null, "e": 13836, "s": 13638, "text": "After running the DAG, a new table will be created in BigQuery with the actual and predicted values for the dataset. The image below shows sample data points from my application of the Keras model." }, { "code": null, "e": 13973, "s": 13836, "text": "The result of using DataFlow with DL4J is that you can score millions of records using autoscaling infrastructure for batch predictions." }, { "code": null, "e": 14498, "s": 13973, "text": "As deep learning becomes increasingly popular, more languages and environments are supporting these models. As libraries start to standardize on model formats, it’s becoming possible to use separate languages for model training and model deployment. This post showed how neural networks trained using the Keras library in Python can be used for batch and real-time predictions using the DL4J library in Java. For the first time, I’ve been able to set up a batch process for applying deep learning to millions of data points." } ]
Program to calculate First and Follow sets of given grammar
05 Nov, 2021 Before proceeding, it is highly recommended to be familiar with the basics in Syntax Analysis, LL(1) parsing, and the rules of calculating First and Follow sets of a grammar. Introduction to Syntax AnalysisWhy First and Follow?FIRST Set in Syntax AnalysisFOLLOW Set in Syntax Analysis Introduction to Syntax Analysis Why First and Follow? FIRST Set in Syntax Analysis FOLLOW Set in Syntax Analysis Assuming the reader is familiar with the basics discussed above, let’s start discussing how to implement the C program to calculate the first and follow of given grammar. Example : Input : E -> TR R -> +T R| # T -> F Y Y -> *F Y | # F -> (E) | i Output : First(E)= { (, i, } First(R)= { +, #, } First(T)= { (, i, } First(Y)= { *, #, } First(F)= { (, i, } ----------------------------------------------- Follow(E) = { $, ), } Follow(R) = { $, ), } Follow(T) = { +, $, ), } Follow(Y) = { +, $, ), } Follow(F) = { *, +, $, ), } The functions follow and followfirst are both involved in the calculation of the Follow Set of a given Non-Terminal. The follow set of the start symbol will always contain “$”. Now the calculation of Follow falls under three broad cases : If a Non-Terminal on the R.H.S. of any production is followed immediately by a Terminal then it can immediately be included in the Follow set of that Non-Terminal. If a Non-Terminal on the R.H.S. of any production is followed immediately by a Non-Terminal, then the First Set of that new Non-Terminal gets included on the follow set of our original Non-Terminal. In case encountered an epsilon i.e. ” # ” then, move on to the next symbol in the production. Note: “#” is never included in the Follow set of any Non-Terminal. If reached the end of a production while calculating follow, then the Follow set of that non-terminal will include the Follow set of the Non-Terminal on the L.H.S. of that production. This can easily be implemented by recursion. Assumptions : Epsilon is represented by ‘#’.Productions are of the form A=B, where ‘A’ is a single Non-Terminal and ‘B’ can be any combination of Terminals and Non- Terminals.L.H.S. of the first production rule is the start symbol.Grammar is not left recursive.Each production of a non-terminal is entered on a different line.Only Upper Case letters are Non-Terminals and everything else is a terminal.Do not use ‘!’ or ‘$’ as they are reserved for special purposes. Epsilon is represented by ‘#’. Productions are of the form A=B, where ‘A’ is a single Non-Terminal and ‘B’ can be any combination of Terminals and Non- Terminals. L.H.S. of the first production rule is the start symbol. Grammar is not left recursive. Each production of a non-terminal is entered on a different line. Only Upper Case letters are Non-Terminals and everything else is a terminal. Do not use ‘!’ or ‘$’ as they are reserved for special purposes. Explanation : Store the grammar on a 2D character array production. findfirst function is for calculating the first of any non terminal. Calculation of first falls under two broad cases : If the first symbol in the R.H.S of the production is a Terminal then it can directly be included in the first set. If the first symbol in the R.H.S of the production is a Non-Terminal then call the findfirst function again on that Non-Terminal. To handle these cases like Recursion is the best possible solution. Here again, if the First of the new Non-Terminal contains an epsilon then we have to move to the next symbol of the original production which can again be a Terminal or a Non-Terminal. Note : For the second case it is very easy to fall prey to an INFINITE LOOP even if the code looks perfect. So it is important to keep track of all the function calls at all times and never call the same function again. Below is the implementation : C // C program to calculate the First and// Follow sets of a given grammar#include<stdio.h>#include<ctype.h>#include<string.h> // Functions to calculate Followvoid followfirst(char, int, int);void follow(char c); // Function to calculate Firstvoid findfirst(char, int, int); int count, n = 0; // Stores the final result// of the First Setschar calc_first[10][100]; // Stores the final result// of the Follow Setschar calc_follow[10][100];int m = 0; // Stores the production ruleschar production[10][10];char f[10], first[10];int k;char ck;int e; int main(int argc, char **argv){ int jm = 0; int km = 0; int i, choice; char c, ch; count = 8; // The Input grammar strcpy(production[0], "E=TR"); strcpy(production[1], "R=+TR"); strcpy(production[2], "R=#"); strcpy(production[3], "T=FY"); strcpy(production[4], "Y=*FY"); strcpy(production[5], "Y=#"); strcpy(production[6], "F=(E)"); strcpy(production[7], "F=i"); int kay; char done[count]; int ptr = -1; // Initializing the calc_first array for(k = 0; k < count; k++) { for(kay = 0; kay < 100; kay++) { calc_first[k][kay] = '!'; } } int point1 = 0, point2, xxx; for(k = 0; k < count; k++) { c = production[k][0]; point2 = 0; xxx = 0; // Checking if First of c has // already been calculated for(kay = 0; kay <= ptr; kay++) if(c == done[kay]) xxx = 1; if (xxx == 1) continue; // Function call findfirst(c, 0, 0); ptr += 1; // Adding c to the calculated list done[ptr] = c; printf("\n First(%c) = { ", c); calc_first[point1][point2++] = c; // Printing the First Sets of the grammar for(i = 0 + jm; i < n; i++) { int lark = 0, chk = 0; for(lark = 0; lark < point2; lark++) { if (first[i] == calc_first[point1][lark]) { chk = 1; break; } } if(chk == 0) { printf("%c, ", first[i]); calc_first[point1][point2++] = first[i]; } } printf("}\n"); jm = n; point1++; } printf("\n"); printf("-----------------------------------------------\n\n"); char donee[count]; ptr = -1; // Initializing the calc_follow array for(k = 0; k < count; k++) { for(kay = 0; kay < 100; kay++) { calc_follow[k][kay] = '!'; } } point1 = 0; int land = 0; for(e = 0; e < count; e++) { ck = production[e][0]; point2 = 0; xxx = 0; // Checking if Follow of ck // has already been calculated for(kay = 0; kay <= ptr; kay++) if(ck == donee[kay]) xxx = 1; if (xxx == 1) continue; land += 1; // Function call follow(ck); ptr += 1; // Adding ck to the calculated list donee[ptr] = ck; printf(" Follow(%c) = { ", ck); calc_follow[point1][point2++] = ck; // Printing the Follow Sets of the grammar for(i = 0 + km; i < m; i++) { int lark = 0, chk = 0; for(lark = 0; lark < point2; lark++) { if (f[i] == calc_follow[point1][lark]) { chk = 1; break; } } if(chk == 0) { printf("%c, ", f[i]); calc_follow[point1][point2++] = f[i]; } } printf(" }\n\n"); km = m; point1++; }} void follow(char c){ int i, j; // Adding "$" to the follow // set of the start symbol if(production[0][0] == c) { f[m++] = '$'; } for(i = 0; i < 10; i++) { for(j = 2;j < 10; j++) { if(production[i][j] == c) { if(production[i][j+1] != '\0') { // Calculate the first of the next // Non-Terminal in the production followfirst(production[i][j+1], i, (j+2)); } if(production[i][j+1]=='\0' && c!=production[i][0]) { // Calculate the follow of the Non-Terminal // in the L.H.S. of the production follow(production[i][0]); } } } }} void findfirst(char c, int q1, int q2){ int j; // The case where we // encounter a Terminal if(!(isupper(c))) { first[n++] = c; } for(j = 0; j < count; j++) { if(production[j][0] == c) { if(production[j][2] == '#') { if(production[q1][q2] == '\0') first[n++] = '#'; else if(production[q1][q2] != '\0' && (q1 != 0 || q2 != 0)) { // Recursion to calculate First of New // Non-Terminal we encounter after epsilon findfirst(production[q1][q2], q1, (q2+1)); } else first[n++] = '#'; } else if(!isupper(production[j][2])) { first[n++] = production[j][2]; } else { // Recursion to calculate First of // New Non-Terminal we encounter // at the beginning findfirst(production[j][2], j, 3); } } }} void followfirst(char c, int c1, int c2){ int k; // The case where we encounter // a Terminal if(!(isupper(c))) f[m++] = c; else { int i = 0, j = 1; for(i = 0; i < count; i++) { if(calc_first[i][0] == c) break; } //Including the First set of the // Non-Terminal in the Follow of // the original query while(calc_first[i][j] != '!') { if(calc_first[i][j] != '#') { f[m++] = calc_first[i][j]; } else { if(production[c1][c2] == '\0') { // Case where we reach the // end of a production follow(production[c1][0]); } else { // Recursion to the next symbol // in case we encounter a "#" followfirst(production[c1][c2], c1, c2+1); } } j++; } }} Output : First(E)= { (, i, } First(R)= { +, #, } First(T)= { (, i, } First(Y)= { *, #, } First(F)= { (, i, } ----------------------------------------------- Follow(E) = { $, ), } Follow(R) = { $, ), } Follow(T) = { +, $, ), } Follow(Y) = { +, $, ), } Follow(F) = { *, +, $, ), } kapoorsagar226 simmytarika5 surindertarika1234 C Programs Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Nov, 2021" }, { "code": null, "e": 228, "s": 52, "text": "Before proceeding, it is highly recommended to be familiar with the basics in Syntax Analysis, LL(1) parsing, and the rules of calculating First and Follow sets of a grammar. " }, { "code": null, "e": 338, "s": 228, "text": "Introduction to Syntax AnalysisWhy First and Follow?FIRST Set in Syntax AnalysisFOLLOW Set in Syntax Analysis" }, { "code": null, "e": 370, "s": 338, "text": "Introduction to Syntax Analysis" }, { "code": null, "e": 392, "s": 370, "text": "Why First and Follow?" }, { "code": null, "e": 421, "s": 392, "text": "FIRST Set in Syntax Analysis" }, { "code": null, "e": 451, "s": 421, "text": "FOLLOW Set in Syntax Analysis" }, { "code": null, "e": 622, "s": 451, "text": "Assuming the reader is familiar with the basics discussed above, let’s start discussing how to implement the C program to calculate the first and follow of given grammar." }, { "code": null, "e": 634, "s": 622, "text": "Example : " }, { "code": null, "e": 992, "s": 634, "text": "Input :\nE -> TR\nR -> +T R| #\nT -> F Y\nY -> *F Y | #\nF -> (E) | i\n\n\nOutput :\nFirst(E)= { (, i, }\nFirst(R)= { +, #, }\nFirst(T)= { (, i, }\nFirst(Y)= { *, #, }\nFirst(F)= { (, i, }\n\n-----------------------------------------------\n\nFollow(E) = { $, ), }\nFollow(R) = { $, ), }\nFollow(T) = { +, $, ), }\nFollow(Y) = { +, $, ), }\nFollow(F) = { *, +, $, ), }" }, { "code": null, "e": 1232, "s": 992, "text": "The functions follow and followfirst are both involved in the calculation of the Follow Set of a given Non-Terminal. The follow set of the start symbol will always contain “$”. Now the calculation of Follow falls under three broad cases : " }, { "code": null, "e": 1396, "s": 1232, "text": "If a Non-Terminal on the R.H.S. of any production is followed immediately by a Terminal then it can immediately be included in the Follow set of that Non-Terminal." }, { "code": null, "e": 1756, "s": 1396, "text": "If a Non-Terminal on the R.H.S. of any production is followed immediately by a Non-Terminal, then the First Set of that new Non-Terminal gets included on the follow set of our original Non-Terminal. In case encountered an epsilon i.e. ” # ” then, move on to the next symbol in the production. Note: “#” is never included in the Follow set of any Non-Terminal." }, { "code": null, "e": 1985, "s": 1756, "text": "If reached the end of a production while calculating follow, then the Follow set of that non-terminal will include the Follow set of the Non-Terminal on the L.H.S. of that production. This can easily be implemented by recursion." }, { "code": null, "e": 2001, "s": 1985, "text": "Assumptions : " }, { "code": null, "e": 2454, "s": 2001, "text": "Epsilon is represented by ‘#’.Productions are of the form A=B, where ‘A’ is a single Non-Terminal and ‘B’ can be any combination of Terminals and Non- Terminals.L.H.S. of the first production rule is the start symbol.Grammar is not left recursive.Each production of a non-terminal is entered on a different line.Only Upper Case letters are Non-Terminals and everything else is a terminal.Do not use ‘!’ or ‘$’ as they are reserved for special purposes." }, { "code": null, "e": 2485, "s": 2454, "text": "Epsilon is represented by ‘#’." }, { "code": null, "e": 2617, "s": 2485, "text": "Productions are of the form A=B, where ‘A’ is a single Non-Terminal and ‘B’ can be any combination of Terminals and Non- Terminals." }, { "code": null, "e": 2674, "s": 2617, "text": "L.H.S. of the first production rule is the start symbol." }, { "code": null, "e": 2705, "s": 2674, "text": "Grammar is not left recursive." }, { "code": null, "e": 2771, "s": 2705, "text": "Each production of a non-terminal is entered on a different line." }, { "code": null, "e": 2848, "s": 2771, "text": "Only Upper Case letters are Non-Terminals and everything else is a terminal." }, { "code": null, "e": 2913, "s": 2848, "text": "Do not use ‘!’ or ‘$’ as they are reserved for special purposes." }, { "code": null, "e": 3101, "s": 2913, "text": "Explanation : Store the grammar on a 2D character array production. findfirst function is for calculating the first of any non terminal. Calculation of first falls under two broad cases :" }, { "code": null, "e": 3217, "s": 3101, "text": "If the first symbol in the R.H.S of the production is a Terminal then it can directly be included in the first set." }, { "code": null, "e": 3600, "s": 3217, "text": "If the first symbol in the R.H.S of the production is a Non-Terminal then call the findfirst function again on that Non-Terminal. To handle these cases like Recursion is the best possible solution. Here again, if the First of the new Non-Terminal contains an epsilon then we have to move to the next symbol of the original production which can again be a Terminal or a Non-Terminal." }, { "code": null, "e": 3821, "s": 3600, "text": "Note : For the second case it is very easy to fall prey to an INFINITE LOOP even if the code looks perfect. So it is important to keep track of all the function calls at all times and never call the same function again. " }, { "code": null, "e": 3853, "s": 3821, "text": "Below is the implementation : " }, { "code": null, "e": 3855, "s": 3853, "text": "C" }, { "code": "// C program to calculate the First and// Follow sets of a given grammar#include<stdio.h>#include<ctype.h>#include<string.h> // Functions to calculate Followvoid followfirst(char, int, int);void follow(char c); // Function to calculate Firstvoid findfirst(char, int, int); int count, n = 0; // Stores the final result// of the First Setschar calc_first[10][100]; // Stores the final result// of the Follow Setschar calc_follow[10][100];int m = 0; // Stores the production ruleschar production[10][10];char f[10], first[10];int k;char ck;int e; int main(int argc, char **argv){ int jm = 0; int km = 0; int i, choice; char c, ch; count = 8; // The Input grammar strcpy(production[0], \"E=TR\"); strcpy(production[1], \"R=+TR\"); strcpy(production[2], \"R=#\"); strcpy(production[3], \"T=FY\"); strcpy(production[4], \"Y=*FY\"); strcpy(production[5], \"Y=#\"); strcpy(production[6], \"F=(E)\"); strcpy(production[7], \"F=i\"); int kay; char done[count]; int ptr = -1; // Initializing the calc_first array for(k = 0; k < count; k++) { for(kay = 0; kay < 100; kay++) { calc_first[k][kay] = '!'; } } int point1 = 0, point2, xxx; for(k = 0; k < count; k++) { c = production[k][0]; point2 = 0; xxx = 0; // Checking if First of c has // already been calculated for(kay = 0; kay <= ptr; kay++) if(c == done[kay]) xxx = 1; if (xxx == 1) continue; // Function call findfirst(c, 0, 0); ptr += 1; // Adding c to the calculated list done[ptr] = c; printf(\"\\n First(%c) = { \", c); calc_first[point1][point2++] = c; // Printing the First Sets of the grammar for(i = 0 + jm; i < n; i++) { int lark = 0, chk = 0; for(lark = 0; lark < point2; lark++) { if (first[i] == calc_first[point1][lark]) { chk = 1; break; } } if(chk == 0) { printf(\"%c, \", first[i]); calc_first[point1][point2++] = first[i]; } } printf(\"}\\n\"); jm = n; point1++; } printf(\"\\n\"); printf(\"-----------------------------------------------\\n\\n\"); char donee[count]; ptr = -1; // Initializing the calc_follow array for(k = 0; k < count; k++) { for(kay = 0; kay < 100; kay++) { calc_follow[k][kay] = '!'; } } point1 = 0; int land = 0; for(e = 0; e < count; e++) { ck = production[e][0]; point2 = 0; xxx = 0; // Checking if Follow of ck // has already been calculated for(kay = 0; kay <= ptr; kay++) if(ck == donee[kay]) xxx = 1; if (xxx == 1) continue; land += 1; // Function call follow(ck); ptr += 1; // Adding ck to the calculated list donee[ptr] = ck; printf(\" Follow(%c) = { \", ck); calc_follow[point1][point2++] = ck; // Printing the Follow Sets of the grammar for(i = 0 + km; i < m; i++) { int lark = 0, chk = 0; for(lark = 0; lark < point2; lark++) { if (f[i] == calc_follow[point1][lark]) { chk = 1; break; } } if(chk == 0) { printf(\"%c, \", f[i]); calc_follow[point1][point2++] = f[i]; } } printf(\" }\\n\\n\"); km = m; point1++; }} void follow(char c){ int i, j; // Adding \"$\" to the follow // set of the start symbol if(production[0][0] == c) { f[m++] = '$'; } for(i = 0; i < 10; i++) { for(j = 2;j < 10; j++) { if(production[i][j] == c) { if(production[i][j+1] != '\\0') { // Calculate the first of the next // Non-Terminal in the production followfirst(production[i][j+1], i, (j+2)); } if(production[i][j+1]=='\\0' && c!=production[i][0]) { // Calculate the follow of the Non-Terminal // in the L.H.S. of the production follow(production[i][0]); } } } }} void findfirst(char c, int q1, int q2){ int j; // The case where we // encounter a Terminal if(!(isupper(c))) { first[n++] = c; } for(j = 0; j < count; j++) { if(production[j][0] == c) { if(production[j][2] == '#') { if(production[q1][q2] == '\\0') first[n++] = '#'; else if(production[q1][q2] != '\\0' && (q1 != 0 || q2 != 0)) { // Recursion to calculate First of New // Non-Terminal we encounter after epsilon findfirst(production[q1][q2], q1, (q2+1)); } else first[n++] = '#'; } else if(!isupper(production[j][2])) { first[n++] = production[j][2]; } else { // Recursion to calculate First of // New Non-Terminal we encounter // at the beginning findfirst(production[j][2], j, 3); } } }} void followfirst(char c, int c1, int c2){ int k; // The case where we encounter // a Terminal if(!(isupper(c))) f[m++] = c; else { int i = 0, j = 1; for(i = 0; i < count; i++) { if(calc_first[i][0] == c) break; } //Including the First set of the // Non-Terminal in the Follow of // the original query while(calc_first[i][j] != '!') { if(calc_first[i][j] != '#') { f[m++] = calc_first[i][j]; } else { if(production[c1][c2] == '\\0') { // Case where we reach the // end of a production follow(production[c1][0]); } else { // Recursion to the next symbol // in case we encounter a \"#\" followfirst(production[c1][c2], c1, c2+1); } } j++; } }}", "e": 10696, "s": 3855, "text": null }, { "code": null, "e": 10706, "s": 10696, "text": "Output : " }, { "code": null, "e": 10993, "s": 10706, "text": " First(E)= { (, i, }\n First(R)= { +, #, }\n First(T)= { (, i, }\n First(Y)= { *, #, }\n First(F)= { (, i, }\n\n-----------------------------------------------\n\n Follow(E) = { $, ), }\n Follow(R) = { $, ), }\n Follow(T) = { +, $, ), }\n Follow(Y) = { +, $, ), }\n Follow(F) = { *, +, $, ), }" }, { "code": null, "e": 11008, "s": 10993, "text": "kapoorsagar226" }, { "code": null, "e": 11021, "s": 11008, "text": "simmytarika5" }, { "code": null, "e": 11040, "s": 11021, "text": "surindertarika1234" }, { "code": null, "e": 11051, "s": 11040, "text": "C Programs" }, { "code": null, "e": 11067, "s": 11051, "text": "Compiler Design" } ]
Number of distinct subsets of a set
07 Apr, 2021 Given an array of n distinct elements, count total number of subsets.Examples: Input : {1, 2, 3} Output : 8 Explanation the array contain total 3 element.its subset are {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {3, 1}, {1, 2, 3}. so the output is 8.. We know number of subsets of set of size n is 2n How does this formula work? For every element, we have two choices, we either pick it or do not pick it. So in total we have 2 * 2 * ... (n times) choices which is 2nAlternate explanation is : Number of subsets of size 0 = nC0 Number of subsets of size 1 = nC1 Number of subsets of size 2 = nC2 ....................Total number of subsets = nC0 + nC1 + nC2 + .... + nCn = 2nPlease refer Sum of Binomial Coefficients for details. C++ Java Python3 C# PHP Javascript // CPP program to count number of distinct// subsets in an array of distinct numbers#include <bits/stdc++.h>using namespace std; // Returns 2 ^ nint subsetCount(int arr[], int n){ return 1 << n;} /* Driver program to test above function */int main(){ int A[] = { 1, 2, 3 }; int n = sizeof(A) / sizeof(A[0]); cout << subsetCount(A, n); return 0;} // Java program to count number of distinct// subsets in an array of distinct numbers class GFG { // Returns 2 ^ n static int subsetCount(int arr[], int n) { return 1 << n; } /* Driver program to test above function */ public static void main(String[] args) { int A[] = { 1, 2, 3 }; int n = A.length; System.out.println(subsetCount(A, n)); }} // This code is contributed by Prerna Saini. # Python3 program to count number# of distinct subsets in an# array of distinct numbersimport math # Returns 2 ^ ndef subsetCount(arr, n): return 1 << n # driver codeA = [ 1, 2, 3 ]n = len(A)print(subsetCount(A, n)) # This code is contributed by Gitanjali. // C# program to count number of distinct// subsets in an array of distinct numbersusing System; class GFG { // Returns 2 ^ n static int subsetCount(int []arr, int n) { return 1 << n; } // Driver program public static void Main() { int []A = { 1, 2, 3 }; int n = A.Length; Console.WriteLine(subsetCount(A, n)); }} // This code is contributed by vt_m. <?php// PHP program to count// number of distinct// subsets in an array// of distinct numbers // Returns 2 ^ nfunction subsetCount($arr, $n){ return 1 << $n;} // Driver Code$A = array( 1, 2, 3 );$n = sizeof($A);echo(subsetCount($A, $n)); // This code is contributed by Ajit.?> <script> // JavaScript program to count number of distinct// subsets in an array of distinct numbers // Returns 2 ^ n function subsetCount(arr, n) { return 1 << n; } // Driver code let A = [ 1, 2, 3 ]; let n = A.length; document.write(subsetCount(A, n)); </script> 8 jit_t code_hunt binomial coefficient Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Apr, 2021" }, { "code": null, "e": 134, "s": 53, "text": "Given an array of n distinct elements, count total number of subsets.Examples: " }, { "code": null, "e": 300, "s": 134, "text": "Input : {1, 2, 3}\nOutput : 8\nExplanation\nthe array contain total 3 element.its subset \nare {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {3, 1}, {1, 2, 3}.\nso the output is 8.." }, { "code": null, "e": 782, "s": 302, "text": "We know number of subsets of set of size n is 2n How does this formula work? For every element, we have two choices, we either pick it or do not pick it. So in total we have 2 * 2 * ... (n times) choices which is 2nAlternate explanation is : Number of subsets of size 0 = nC0 Number of subsets of size 1 = nC1 Number of subsets of size 2 = nC2 ....................Total number of subsets = nC0 + nC1 + nC2 + .... + nCn = 2nPlease refer Sum of Binomial Coefficients for details. " }, { "code": null, "e": 786, "s": 782, "text": "C++" }, { "code": null, "e": 791, "s": 786, "text": "Java" }, { "code": null, "e": 799, "s": 791, "text": "Python3" }, { "code": null, "e": 802, "s": 799, "text": "C#" }, { "code": null, "e": 806, "s": 802, "text": "PHP" }, { "code": null, "e": 817, "s": 806, "text": "Javascript" }, { "code": "// CPP program to count number of distinct// subsets in an array of distinct numbers#include <bits/stdc++.h>using namespace std; // Returns 2 ^ nint subsetCount(int arr[], int n){ return 1 << n;} /* Driver program to test above function */int main(){ int A[] = { 1, 2, 3 }; int n = sizeof(A) / sizeof(A[0]); cout << subsetCount(A, n); return 0;}", "e": 1179, "s": 817, "text": null }, { "code": "// Java program to count number of distinct// subsets in an array of distinct numbers class GFG { // Returns 2 ^ n static int subsetCount(int arr[], int n) { return 1 << n; } /* Driver program to test above function */ public static void main(String[] args) { int A[] = { 1, 2, 3 }; int n = A.length; System.out.println(subsetCount(A, n)); }} // This code is contributed by Prerna Saini.", "e": 1634, "s": 1179, "text": null }, { "code": "# Python3 program to count number# of distinct subsets in an# array of distinct numbersimport math # Returns 2 ^ ndef subsetCount(arr, n): return 1 << n # driver codeA = [ 1, 2, 3 ]n = len(A)print(subsetCount(A, n)) # This code is contributed by Gitanjali.", "e": 1899, "s": 1634, "text": null }, { "code": "// C# program to count number of distinct// subsets in an array of distinct numbersusing System; class GFG { // Returns 2 ^ n static int subsetCount(int []arr, int n) { return 1 << n; } // Driver program public static void Main() { int []A = { 1, 2, 3 }; int n = A.Length; Console.WriteLine(subsetCount(A, n)); }} // This code is contributed by vt_m.", "e": 2317, "s": 1899, "text": null }, { "code": "<?php// PHP program to count// number of distinct// subsets in an array// of distinct numbers // Returns 2 ^ nfunction subsetCount($arr, $n){ return 1 << $n;} // Driver Code$A = array( 1, 2, 3 );$n = sizeof($A);echo(subsetCount($A, $n)); // This code is contributed by Ajit.?>", "e": 2597, "s": 2317, "text": null }, { "code": "<script> // JavaScript program to count number of distinct// subsets in an array of distinct numbers // Returns 2 ^ n function subsetCount(arr, n) { return 1 << n; } // Driver code let A = [ 1, 2, 3 ]; let n = A.length; document.write(subsetCount(A, n)); </script>", "e": 2916, "s": 2597, "text": null }, { "code": null, "e": 2918, "s": 2916, "text": "8" }, { "code": null, "e": 2926, "s": 2920, "text": "jit_t" }, { "code": null, "e": 2936, "s": 2926, "text": "code_hunt" }, { "code": null, "e": 2957, "s": 2936, "text": "binomial coefficient" }, { "code": null, "e": 2964, "s": 2957, "text": "Arrays" }, { "code": null, "e": 2977, "s": 2964, "text": "Mathematical" }, { "code": null, "e": 2984, "s": 2977, "text": "Arrays" }, { "code": null, "e": 2997, "s": 2984, "text": "Mathematical" } ]
Processing time with Pandas DataFrame
07 Jan, 2022 Pandas was created with regards to financial modeling, so as you may expect, it contains a genuinely ample number of tools for working with dates and times. Sometimes the given format of the date and time in our dataset cannot be directly used for analysis, so we pre-process these time values to obtain features like date, month, year, hours, minutes and seconds. Let’s discuss all the different ways to process date and time with Pandas dataframe. Divide date and time into multiple features:Create five dates and time using pd.date_range which generate sequences of fixed-frequency dates and time spans. Then we use pandas.Series.dt to extract the features. Python3 # Load libraryimport pandas as pd # calling DataFrame constructordf = pd.DataFrame() # Create 6 datesdf['time'] = pd.date_range('2/5/2019', periods = 6, freq ='2H')print(df['time']) # print dataframe # Extract features - year, month, day, hour, and minutedf['year'] = df['time'].dt.yeardf['month'] = df['time'].dt.monthdf['day'] = df['time'].dt.daydf['hour'] = df['time'].dt.hourdf['minute'] = df['time'].dt.minute # Show six rowsdf.head(6) 0 2019-02-05 00:00:00 1 2019-02-05 02:00:00 2 2019-02-05 04:00:00 3 2019-02-05 06:00:00 4 2019-02-05 08:00:00 5 2019-02-05 10:00:00 Name: time, dtype: datetime64[ns] time year month day hour minute 0 2019-02-05 00:00:00 2019 2 5 0 0 1 2019-02-05 02:00:00 2019 2 5 2 0 2 2019-02-05 04:00:00 2019 2 5 4 0 3 2019-02-05 06:00:00 2019 2 5 6 0 4 2019-02-05 08:00:00 2019 2 5 8 0 5 2019-02-05 10:00:00 2019 2 5 10 0 Convert strings to Timestamps:We convert the given strings to datetime format using pd.to_datetime and then we can extract different features from the datetime using first method. Python3 # Load librariesimport numpy as npimport pandas as pd # Create time Stringsdt_strings = np.array(['04-03-2019 12:35 PM', '22-06-2017 11:01 AM', '05-09-2009 07:09 PM']) # Convert to datetime formattimestamps = [pd.to_datetime(date, format ="%d-%m-%Y%I:%M %p", errors ="coerce") for date in dt_strings] # Convert to datetimestimestamps = [pd.to_datetime(date, format ="%d-%m-%Y %I:%M %p", errors ="coerce") for date in dt_strings] Output: [Timestamp(‘2019-03-04 12:35:00’), Timestamp(‘2017-06-22 11:01:00’), Timestamp(‘2009-09-05 19:09:00’)] Extract Days Of the Week from the given Date:We use Series.dt.weekday_name to find name of the day in a week from the given Date. Python3 # Load libraryimport pandas as pddf = pd.DataFrame() # Create 6 datesdates = pd.pd.Series(date_range('2/5/2019', periods = 6, freq ='M')) print(dates) # Extract days of week and then printprint(dates.dt.weekday_name) 0 2019-02-28 1 2019-03-31 2 2019-04-30 3 2019-05-31 4 2019-06-30 5 2019-07-31 dtype: datetime64[ns] 0 Thursday 1 Sunday 2 Tuesday 3 Friday 4 Sunday 5 Wednesday dtype: object Extract Data in Date and Time Ranges:We can obtain the rows that lie in particular time range from the given dataset. Method #1: If the dataset is not indexed with time. Python3 # Load libraryimport pandas as pd # Create data framedf = pd.DataFrame() # Create datetimesdf['date'] = pd.date_range('1/1/2012', periods = 1000, freq ='H') print(df.head(5)) # Select observations between two datetimesx = df[(df['date'] > '2012-1-1 01:00:00') & (df['date'] <= '2012-1-1 11:00:00')] print(x) Output: date 0 2012-01-01 00:00:00 1 2012-01-01 01:00:00 // 5 rows of Timestamps out of 1000 2 2012-01-01 02:00:00 3 2012-01-01 03:00:00 4 2012-01-01 04:00:00 date 2 2012-01-01 02:00:00 3 2012-01-01 03:00:00 4 2012-01-01 04:00:00 5 2012-01-01 05:00:00 //Timestamps in the given range 6 2012-01-01 06:00:00 7 2012-01-01 07:00:00 8 2012-01-01 08:00:00 9 2012-01-01 09:00:00 10 2012-01-01 10:00:00 11 2012-01-01 11:00:00 Method #2: If the dataset is indexed with time Python3 # Load libraryimport pandas as pd # Create data framedf = pd.DataFrame() # Create datetimesdf['date'] = pd.date_range('1/1/2012', periods = 1000, freq ='H') # Set indexdf = df.set_index(df['date']) print(df.head(5)) # Select observations between two datetimesx = df.loc['2012-1-1 04:00:00':'2012-1-1 12:00:00'] print(x) Output: date date 2012-01-01 00:00:00 2012-01-01 00:00:00 2012-01-01 01:00:00 2012-01-01 01:00:00 2012-01-01 02:00:00 2012-01-01 02:00:00 2012-01-01 03:00:00 2012-01-01 03:00:00 // 5 rows of Timestamps out of 1000 2012-01-01 04:00:00 2012-01-01 04:00:00 date date 2012-01-01 04:00:00 2012-01-01 04:00:00 2012-01-01 05:00:00 2012-01-01 05:00:00 2012-01-01 06:00:00 2012-01-01 06:00:00 2012-01-01 07:00:00 2012-01-01 07:00:00 2012-01-01 08:00:00 2012-01-01 08:00:00 2012-01-01 09:00:00 2012-01-01 09:00:00 //Timestamps in the given range 2012-01-01 10:00:00 2012-01-01 10:00:00 2012-01-01 11:00:00 2012-01-01 11:00:00 2012-01-01 12:00:00 2012-01-01 12:00:00 kashishsoda Picked Python pandas-datetime Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2022" }, { "code": null, "e": 393, "s": 28, "text": "Pandas was created with regards to financial modeling, so as you may expect, it contains a genuinely ample number of tools for working with dates and times. Sometimes the given format of the date and time in our dataset cannot be directly used for analysis, so we pre-process these time values to obtain features like date, month, year, hours, minutes and seconds." }, { "code": null, "e": 478, "s": 393, "text": "Let’s discuss all the different ways to process date and time with Pandas dataframe." }, { "code": null, "e": 689, "s": 478, "text": "Divide date and time into multiple features:Create five dates and time using pd.date_range which generate sequences of fixed-frequency dates and time spans. Then we use pandas.Series.dt to extract the features." }, { "code": null, "e": 697, "s": 689, "text": "Python3" }, { "code": "# Load libraryimport pandas as pd # calling DataFrame constructordf = pd.DataFrame() # Create 6 datesdf['time'] = pd.date_range('2/5/2019', periods = 6, freq ='2H')print(df['time']) # print dataframe # Extract features - year, month, day, hour, and minutedf['year'] = df['time'].dt.yeardf['month'] = df['time'].dt.monthdf['day'] = df['time'].dt.daydf['hour'] = df['time'].dt.hourdf['minute'] = df['time'].dt.minute # Show six rowsdf.head(6)", "e": 1143, "s": 697, "text": null }, { "code": null, "e": 1701, "s": 1143, "text": "0 2019-02-05 00:00:00\n1 2019-02-05 02:00:00\n2 2019-02-05 04:00:00\n3 2019-02-05 06:00:00\n4 2019-02-05 08:00:00\n5 2019-02-05 10:00:00\nName: time, dtype: datetime64[ns]\n\n\n time year month day hour minute\n0 2019-02-05 00:00:00 2019 2 5 0 0\n1 2019-02-05 02:00:00 2019 2 5 2 0\n2 2019-02-05 04:00:00 2019 2 5 4 0\n3 2019-02-05 06:00:00 2019 2 5 6 0\n4 2019-02-05 08:00:00 2019 2 5 8 0\n5 2019-02-05 10:00:00 2019 2 5 10 0\n" }, { "code": null, "e": 1882, "s": 1701, "text": " Convert strings to Timestamps:We convert the given strings to datetime format using pd.to_datetime and then we can extract different features from the datetime using first method." }, { "code": null, "e": 1890, "s": 1882, "text": "Python3" }, { "code": "# Load librariesimport numpy as npimport pandas as pd # Create time Stringsdt_strings = np.array(['04-03-2019 12:35 PM', '22-06-2017 11:01 AM', '05-09-2009 07:09 PM']) # Convert to datetime formattimestamps = [pd.to_datetime(date, format =\"%d-%m-%Y%I:%M %p\", errors =\"coerce\") for date in dt_strings] # Convert to datetimestimestamps = [pd.to_datetime(date, format =\"%d-%m-%Y %I:%M %p\", errors =\"coerce\") for date in dt_strings]", "e": 2407, "s": 1890, "text": null }, { "code": null, "e": 2415, "s": 2407, "text": "Output:" }, { "code": null, "e": 2518, "s": 2415, "text": "[Timestamp(‘2019-03-04 12:35:00’), Timestamp(‘2017-06-22 11:01:00’), Timestamp(‘2009-09-05 19:09:00’)]" }, { "code": null, "e": 2649, "s": 2518, "text": " Extract Days Of the Week from the given Date:We use Series.dt.weekday_name to find name of the day in a week from the given Date." }, { "code": null, "e": 2657, "s": 2649, "text": "Python3" }, { "code": "# Load libraryimport pandas as pddf = pd.DataFrame() # Create 6 datesdates = pd.pd.Series(date_range('2/5/2019', periods = 6, freq ='M')) print(dates) # Extract days of week and then printprint(dates.dt.weekday_name)", "e": 2877, "s": 2657, "text": null }, { "code": null, "e": 3094, "s": 2877, "text": "0 2019-02-28\n1 2019-03-31\n2 2019-04-30\n3 2019-05-31\n4 2019-06-30\n5 2019-07-31\ndtype: datetime64[ns]\n0 Thursday\n1 Sunday\n2 Tuesday\n3 Friday\n4 Sunday\n5 Wednesday\ndtype: object\n" }, { "code": null, "e": 3213, "s": 3094, "text": " Extract Data in Date and Time Ranges:We can obtain the rows that lie in particular time range from the given dataset." }, { "code": null, "e": 3265, "s": 3213, "text": "Method #1: If the dataset is not indexed with time." }, { "code": null, "e": 3273, "s": 3265, "text": "Python3" }, { "code": "# Load libraryimport pandas as pd # Create data framedf = pd.DataFrame() # Create datetimesdf['date'] = pd.date_range('1/1/2012', periods = 1000, freq ='H') print(df.head(5)) # Select observations between two datetimesx = df[(df['date'] > '2012-1-1 01:00:00') & (df['date'] <= '2012-1-1 11:00:00')] print(x)", "e": 3592, "s": 3273, "text": null }, { "code": null, "e": 3600, "s": 3592, "text": "Output:" }, { "code": null, "e": 4084, "s": 3600, "text": " date\n0 2012-01-01 00:00:00\n1 2012-01-01 01:00:00 // 5 rows of Timestamps out of 1000\n2 2012-01-01 02:00:00\n3 2012-01-01 03:00:00\n4 2012-01-01 04:00:00\n\n\n date\n2 2012-01-01 02:00:00\n3 2012-01-01 03:00:00\n4 2012-01-01 04:00:00\n5 2012-01-01 05:00:00 //Timestamps in the given range\n6 2012-01-01 06:00:00\n7 2012-01-01 07:00:00\n8 2012-01-01 08:00:00\n9 2012-01-01 09:00:00\n10 2012-01-01 10:00:00\n11 2012-01-01 11:00:00\n" }, { "code": null, "e": 4131, "s": 4084, "text": "Method #2: If the dataset is indexed with time" }, { "code": null, "e": 4139, "s": 4131, "text": "Python3" }, { "code": "# Load libraryimport pandas as pd # Create data framedf = pd.DataFrame() # Create datetimesdf['date'] = pd.date_range('1/1/2012', periods = 1000, freq ='H') # Set indexdf = df.set_index(df['date']) print(df.head(5)) # Select observations between two datetimesx = df.loc['2012-1-1 04:00:00':'2012-1-1 12:00:00'] print(x)", "e": 4465, "s": 4139, "text": null }, { "code": null, "e": 4473, "s": 4465, "text": "Output:" }, { "code": null, "e": 5291, "s": 4473, "text": " date\ndate \n2012-01-01 00:00:00 2012-01-01 00:00:00\n2012-01-01 01:00:00 2012-01-01 01:00:00\n2012-01-01 02:00:00 2012-01-01 02:00:00\n2012-01-01 03:00:00 2012-01-01 03:00:00 // 5 rows of Timestamps out of 1000\n2012-01-01 04:00:00 2012-01-01 04:00:00\n date\ndate \n2012-01-01 04:00:00 2012-01-01 04:00:00\n2012-01-01 05:00:00 2012-01-01 05:00:00\n2012-01-01 06:00:00 2012-01-01 06:00:00\n2012-01-01 07:00:00 2012-01-01 07:00:00\n2012-01-01 08:00:00 2012-01-01 08:00:00\n2012-01-01 09:00:00 2012-01-01 09:00:00 //Timestamps in the given range\n2012-01-01 10:00:00 2012-01-01 10:00:00\n2012-01-01 11:00:00 2012-01-01 11:00:00\n2012-01-01 12:00:00 2012-01-01 12:00:00\n" }, { "code": null, "e": 5303, "s": 5291, "text": "kashishsoda" }, { "code": null, "e": 5310, "s": 5303, "text": "Picked" }, { "code": null, "e": 5333, "s": 5310, "text": "Python pandas-datetime" }, { "code": null, "e": 5347, "s": 5333, "text": "Python-pandas" }, { "code": null, "e": 5354, "s": 5347, "text": "Python" }, { "code": null, "e": 5452, "s": 5354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5470, "s": 5452, "text": "Python Dictionary" }, { "code": null, "e": 5512, "s": 5470, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5534, "s": 5512, "text": "Enumerate() in Python" }, { "code": null, "e": 5566, "s": 5534, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5595, "s": 5566, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5622, "s": 5595, "text": "Python Classes and Objects" }, { "code": null, "e": 5643, "s": 5622, "text": "Python OOPs Concepts" }, { "code": null, "e": 5666, "s": 5643, "text": "Introduction To PYTHON" }, { "code": null, "e": 5702, "s": 5666, "text": "Convert integer to string in Python" } ]
k-th missing element in sorted array
10 Jun, 2022 Given an increasing sequence a[], we need to find the K-th missing contiguous element in the increasing sequence which is not present in the sequence. If no k-th missing element is there output -1. Examples : Input : a[] = {2, 3, 5, 9, 10}; k = 1; Output : 1 Explanation: Missing Element in the increasing sequence are {1,4, 6, 7, 8}. So k-th missing element is 1 Input : a[] = {2, 3, 5, 9, 10, 11, 12}; k = 4; Output : 7 Explanation: missing element in the increasing sequence are {1, 4, 6, 7, 8} so k-th missing element is 7 Approach 1: Start iterating over the array elements, and for every element check if the next element is consecutive or not, if not, then take the difference between these two, and check if the difference is greater than or equal to given k, then calculate ans = a[i] + count, else iterate for next element. C++ Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; // Function to find k-th// missing elementint missingK(int a[], int k, int n){ int difference = 0, ans = 0, count = k; bool flag = 0; //case when first number is not 1 if (a[0] != 1){ difference = a[0]-1; if (difference >= count) return count; count -= difference; } // iterating over the array for(int i = 0 ; i < n - 1; i++) { difference = 0; // check if i-th and // (i + 1)-th element // are not consecutive if ((a[i] + 1) != a[i + 1]) { // save their difference difference += (a[i + 1] - a[i]) - 1; // check for difference // and given k if (difference >= count) { ans = a[i] + count; flag = 1; break; } else count -= difference; } } // if found if(flag) return ans; else return -1;} // Driver codeint main(){ // Input array int a[] = {1, 5, 11, 19}; // k-th missing element // to be found in the array int k = 11; int n = sizeof(a) / sizeof(a[0]); // calling function to // find missing element int missing = missingK(a, k, n); cout << missing << endl; return 0;} // Java program to check for// even or oddimport java.io.*;import java.util.*; public class GFG { // Function to find k-th // missing element static int missingK(int []a, int k, int n) { int difference = 0, ans = 0, count = k; boolean flag = false; //case when first number is not 1 if (a[0] != 1){ difference = a[0]-1; if (difference >= count) return count; count -= difference; } // iterating over the array for(int i = 0 ; i < n - 1; i++) { difference = 0; // check if i-th and // (i + 1)-th element // are not consecutive if ((a[i] + 1) != a[i + 1]) { // save their difference difference += (a[i + 1] - a[i]) - 1; // check for difference // and given k if (difference >= count) { ans = a[i] + count; flag = true; break; } else count -= difference; } } // if found if(flag) return ans; else return -1; } // Driver code public static void main(String args[]) { // Input array int []a = {1, 5, 11, 19}; // k-th missing element // to be found in the array int k = 11; int n = a.length; // calling function to // find missing element int missing = missingK(a, k, n); System.out.print(missing); } } // This code is contributed by// Manish Shaw (manishshaw1) # Function to find k-th# missing elementdef missingK(a, k, n) : difference = 0 ans = 0 count = k flag = 0 #case when first number is not 1 if a[0] != 1: difference = a[0]-1 if difference >= count: return count count -= difference # iterating over the array for i in range (0, n-1) : difference = 0 # check if i-th and # (i + 1)-th element # are not consecutive if ((a[i] + 1) != a[i + 1]) : # save their difference difference += (a[i + 1] - a[i]) - 1 # check for difference # and given k if (difference >= count) : ans = a[i] + count flag = 1 break else : count -= difference # if found if(flag) : return ans else : return -1 # Driver code# Input arraya = [1, 5, 11, 19] # k-th missing element# to be found in the arrayk = 11n = len(a) # calling function to# find missing elementmissing = missingK(a, k, n) print(missing) # This code is contributed by# Manish Shaw (manishshaw1) // C# program to check for// even or oddusing System;using System.Collections.Generic; class GFG { // Function to find k-th // missing element static int missingK(int []a, int k, int n) { int difference = 0, ans = 0, count = k; bool flag = false; //case when first number is not 1 if (a[0] != 1){ difference = a[0]-1; if (difference >= count) return count; count -= difference; } // iterating over the array for(int i = 0 ; i < n - 1; i++) { difference = 0; // check if i-th and // (i + 1)-th element // are not consecutive if ((a[i] + 1) != a[i + 1]) { // save their difference difference += (a[i + 1] - a[i]) - 1; // check for difference // and given k if (difference >= count) { ans = a[i] + count; flag = true; break; } else count -= difference; } } // if found if(flag) return ans; else return -1; } // Driver code public static void Main() { // Input array int []a = {1, 5, 11, 19}; // k-th missing element // to be found in the array int k = 11; int n = a.Length; // calling function to // find missing element int missing = missingK(a, k, n); Console.Write(missing); } } // This code is contributed by// Manish Shaw (manishshaw1) <?php// Function to find k-th// missing elementfunction missingK(&$a, $k, $n){ $difference = 0; $ans = 0; $count = $k; $flag = 0; // iterating over the array for($i = 0 ; $i < $n - 1; $i++) { $difference = 0; // check if i-th and // (i + 1)-th element // are not consecutive if (($a[$i] + 1) != $a[$i + 1]) { // save their difference $difference += ($a[$i + 1] - $a[$i]) - 1; // check for difference // and given k if ($difference >= $count) { $ans = $a[$i] + $count; $flag = 1; break; } else $count -= $difference; } } // if found if($flag) return $ans; else return -1;} // Driver Code // Input array$a = array(1, 5, 11, 19); // k-th missing element// to be found in the array$k = 11;$n = count($a); // calling function to// find missing element$missing = missingK($a, $k, $n); echo $missing; // This code is contributed by Manish Shaw// (manishshaw1)?> <script> // Javascript program to check for// even or odd // Function to find k-th// missing elementfunction missingK(a, k, n){ let difference = 0, ans = 0, count = k; let flag = false; //case when first number is not 1 if (a[0] != 1){ difference = a[0]-1; if (difference >= count){ return count; } count -= difference; } // iterating over the array for(let i = 0 ; i < n - 1; i++) { difference = 0; // Check if i-th and // (i + 1)-th element // are not consecutive if ((a[i] + 1) != a[i + 1]) { // Save their difference difference += (a[i + 1] - a[i]) - 1; // Check for difference // and given k if (difference >= count) { ans = a[i] + count; flag = true; break; } else count -= difference; } } // If found if (flag) return ans; else return -1;} // Driver code // Input arraylet a = [ 1, 5, 11, 19 ]; // k-th missing element// to be found in the arraylet k = 11;let n = a.length; // Calling function to// find missing elementlet missing = missingK(a, k, n); document.write(missing); // This code is contributed by suresh07 </script> 14 Time Complexity :O(n), where n is the number of elements in the array. Approach 2: Apply a binary search. Since the array is sorted we can find at any given index how many numbers are missing as arr[index] – (index+1). We would leverage this knowledge and apply binary search to narrow down our hunt to find that index from which getting the missing number is easier. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program for above approach#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to find// kth missing numberint missingK(vector<int>& arr, int k){ int n = arr.size(); int l = 0, u = n - 1, mid; while(l <= u) { mid = (l + u)/2; int numbers_less_than_mid = arr[mid] - (mid + 1); // If the total missing number // count is equal to k we can iterate // backwards for the first missing number // and that will be the answer. if(numbers_less_than_mid == k) { // To further optimize we check // if the previous element's // missing number count is equal // to k. Eg: arr = [4,5,6,7,8] // If you observe in the example array, // the total count of missing numbers for all // the indices are same, and we are // aiming to narrow down the // search window and achieve O(logn) // time complexity which // otherwise would've been O(n). if(mid > 0 && (arr[mid - 1] - (mid)) == k) { u = mid - 1; continue; } // Else we return arr[mid] - 1. return arr[mid]-1; } // Here we appropriately // narrow down the search window. if(numbers_less_than_mid < k) { l = mid + 1; } else if(k < numbers_less_than_mid) { u = mid - 1; } } // In case the upper limit is -ve // it means the missing number set // is 1,2,..,k and hence we directly return k. if(u < 0) return k; // Else we find the residual count // of numbers which we'd then add to // arr[u] and get the missing kth number. int less = arr[u] - (u + 1); k -= less; // Return arr[u] + k return arr[u] + k;} // Driver Codeint main(){ vector<int> arr = {2,3,4,7,11}; int k = 5; // Function Call cout <<"Missing kth number = "<< missingK(arr, k)<<endl; return 0;} // Java program for above approachpublic class GFG{ // Function to find // kth missing number static int missingK(int[] arr, int k) { int n = arr.length; int l = 0, u = n - 1, mid; while(l <= u) { mid = (l + u)/2; int numbers_less_than_mid = arr[mid] - (mid + 1); // If the total missing number // count is equal to k we can iterate // backwards for the first missing number // and that will be the answer. if(numbers_less_than_mid == k) { // To further optimize we check // if the previous element's // missing number count is equal // to k. Eg: arr = [4,5,6,7,8] // If you observe in the example array, // the total count of missing numbers for all // the indices are same, and we are // aiming to narrow down the // search window and achieve O(logn) // time complexity which // otherwise would've been O(n). if(mid > 0 && (arr[mid - 1] - (mid)) == k) { u = mid - 1; continue; } // Else we return arr[mid] - 1. return arr[mid] - 1; } // Here we appropriately // narrow down the search window. if(numbers_less_than_mid < k) { l = mid + 1; } else if(k < numbers_less_than_mid) { u = mid - 1; } } // In case the upper limit is -ve // it means the missing number set // is 1,2,..,k and hence we directly return k. if(u < 0) return k; // Else we find the residual count // of numbers which we'd then add to // arr[u] and get the missing kth number. int less = arr[u] - (u + 1); k -= less; // Return arr[u] + k return arr[u] + k; } // Driver code public static void main(String[] args) { int[] arr = {2,3,4,7,11}; int k = 5; // Function Call System.out.println("Missing kth number = "+ missingK(arr, k)); }} // This code is contributed by divyesh072019. # Python3 program for above approach # Function to find# kth missing numberdef missingK(arr, k): n = len(arr) l = 0 u = n - 1 mid = 0 while(l <= u): mid = (l + u)//2; numbers_less_than_mid = arr[mid] - (mid + 1); # If the total missing number # count is equal to k we can iterate # backwards for the first missing number # and that will be the answer. if(numbers_less_than_mid == k): # To further optimize we check # if the previous element's # missing number count is equal # to k. Eg: arr = [4,5,6,7,8] # If you observe in the example array, # the total count of missing numbers for all # the indices are same, and we are # aiming to narrow down the # search window and achieve O(logn) # time complexity which # otherwise would've been O(n). if(mid > 0 and (arr[mid - 1] - (mid)) == k): u = mid - 1; continue; # Else we return arr[mid] - 1. return arr[mid]-1; # Here we appropriately # narrow down the search window. if(numbers_less_than_mid < k): l = mid + 1; elif(k < numbers_less_than_mid): u = mid - 1; # In case the upper limit is -ve # it means the missing number set # is 1,2,..,k and hence we directly return k. if(u < 0): return k; # Else we find the residual count # of numbers which we'd then add to # arr[u] and get the missing kth number. less = arr[u] - (u + 1); k -= less; # Return arr[u] + k return arr[u] + k; # Driver Codeif __name__=='__main__': arr = [2,3,4,7,11]; k = 5; # Function Call print("Missing kth number = "+ str(missingK(arr, k))) # This code is contributed by rutvik_56. // C# program for above approachusing System;class GFG { // Function to find // kth missing number static int missingK(int[] arr, int k) { int n = arr.Length; int l = 0, u = n - 1, mid; while(l <= u) { mid = (l + u)/2; int numbers_less_than_mid = arr[mid] - (mid + 1); // If the total missing number // count is equal to k we can iterate // backwards for the first missing number // and that will be the answer. if(numbers_less_than_mid == k) { // To further optimize we check // if the previous element's // missing number count is equal // to k. Eg: arr = [4,5,6,7,8] // If you observe in the example array, // the total count of missing numbers for all // the indices are same, and we are // aiming to narrow down the // search window and achieve O(logn) // time complexity which // otherwise would've been O(n). if(mid > 0 && (arr[mid - 1] - (mid)) == k) { u = mid - 1; continue; } // Else we return arr[mid] - 1. return arr[mid] - 1; } // Here we appropriately // narrow down the search window. if(numbers_less_than_mid < k) { l = mid + 1; } else if(k < numbers_less_than_mid) { u = mid - 1; } } // In case the upper limit is -ve // it means the missing number set // is 1,2,..,k and hence we directly return k. if(u < 0) return k; // Else we find the residual count // of numbers which we'd then add to // arr[u] and get the missing kth number. int less = arr[u] - (u + 1); k -= less; // Return arr[u] + k return arr[u] + k; } // Driver code static void Main() { int[] arr = {2,3,4,7,11}; int k = 5; // Function Call Console.WriteLine("Missing kth number = "+ missingK(arr, k)); }} // This code is contributed by divyeshrabadiya07. <script>// JavaScript program for above approach // Function to find // kth missing number function missingK(arr, k) { var n = arr.length; var l = 0, u = n - 1, mid; while(l <= u) { mid = (l + u)/2; var numbers_less_than_mid = arr[mid] - (mid + 1); // If the total missing number // count is equal to k we can iterate // backwards for the first missing number // and that will be the answer. if(numbers_less_than_mid == k) { // To further optimize we check // if the previous element's // missing number count is equal // to k. Eg: arr = [4,5,6,7,8] // If you observe in the example array, // the total count of missing numbers for all // the indices are same, and we are // aiming to narrow down the // search window and achieve O(logn) // time complexity which // otherwise would've been O(n). if(mid > 0 && (arr[mid - 1] - (mid)) == k) { u = mid - 1; continue; } // Else we return arr[mid] - 1. return arr[mid] - 1; } // Here we appropriately // narrow down the search window. if(numbers_less_than_mid < k) { l = mid + 1; } else if(k < numbers_less_than_mid) { u = mid - 1; } } // In case the upper limit is -ve // it means the missing number set // is 1,2,..,k and hence we directly return k. if(u < 0) return k; // Else we find the residual count // of numbers which we'd then add to // arr[u] and get the missing kth number. var less = arr[u] - (u + 1); k -= less; // Return arr[u] + k return arr[u] + k; } // Driver code var arr = [2,3,4,7,11]; var k = 5; // Function Call document.write("Missing kth number = "+ missingK(arr, k)); // This code is contributed by shivanisinghss2110 </script> Missing kth number = 9 Time Complexity: O(logn), where n is the number of elements in the array. Approach 3 (Using Map): We will traverse the array and mark each of the elements as visited in the map and we will also keep track of the min and max element present so that we know the lower and upper bound for the given particular input. Then we start a loop from lower to upper bound and maintain a count variable. As soon we found an element that is not present in the map we increment the count and until the count becomes equal to k. C++14 Java Python3 C# Javascript #include <iostream>#include <unordered_map>using namespace std; int solve(int arr[] , int k , int n){ unordered_map<int ,int> umap; int mins = 99999; int maxs = -99999; for(int i=0 ; i<n ; i++) { umap[arr[i]] = 1; //mark each element of array in map if(mins > arr[i]) mins = arr[i]; //keeping track of minimum element if(maxs < arr[i]) maxs = arr[i]; //keeping track of maximum element i.e. upper bound } int counts = 0; //iterate from lower to upper bound for(int i=mins ; i<=maxs ; i++) { if(umap[i] == 0) counts++; if(counts == k) return i; } return -1;}int main() { int arr[] = {2, 3, 5, 9, 10, 11, 12} ; int k = 4; cout << solve(arr , k , 7) ; //(array , k , size of array) return 0;} // Java approach // Importing HashMap classimport java.util.HashMap;class GFG { public static int solve(int arr[] , int k , int n) { HashMap<Integer, Integer> umap = new HashMap<Integer, Integer>(); int mins = 99999; int maxs = -99999; for(int i = 0; i < n; i++) { umap.put(arr[i], 1); // mark each element of array in map if(mins > arr[i]) mins = arr[i]; // keeping track of minimum element if(maxs < arr[i]) maxs = arr[i]; // keeping track of maximum element i.e. upper bound } int counts = 0; // iterate from lower to upper bound for(int i = mins; i <= maxs; i++) { if(umap.get(i) == null) counts++; if(counts == k) return i; } return -1; } public static void main (String[] args) { int arr[] = {2, 3, 5, 9, 10, 11, 12} ; int k = 4; System.out.println(solve(arr , k , 7)); //(array , k , size of array) }} // This code is contributed by Shubham Singh # Python approachdef solve( arr , k , n): umap = {} mins = 99999 maxs = -99999 for i in range(n): umap[arr[i]] = 1 #mark each element of array in map if(mins > arr[i]): mins = arr[i] #keeping track of minimum element if(maxs < arr[i]): maxs = arr[i] #keeping track of maximum element i.e. upper bound counts = 0 # iterate from lower to upper bound for i in range(mins, maxs+1): if(i not in umap): counts += 1 if(counts == k): return i return -1 arr = [2, 3, 5, 9, 10, 11, 12]k = 4print(solve(arr , k , 7)) #(array , k , size of array) # This code is contributed# by Shubham Singh // C# program for above approachusing System;using System.Collections.Generic;class GFG { // Function to find // kth missing number static int solve(int[] arr, int k, int n) { Dictionary < int, int > umap = new Dictionary < int, int > (); int mins = 99999; int maxs = -99999; for(int i=0 ; i<n ; i++) { umap.Add(arr[i], 1); //mark each element of array in map if(mins > arr[i]) mins = arr[i]; //keeping track of minimum element if(maxs < arr[i]) maxs = arr[i]; //keeping track of maximum element i.e. upper bound } int counts = 0; //iterate from lower to upper bound for(int i=mins ; i<=maxs ; i++) { if(!umap.ContainsKey(i)) counts++; if(counts == k) return i; } return -1; } // Driver codestatic void Main(){ int[] arr = {2, 3, 5, 9, 10, 11, 12}; int k = 4; int n = arr.Length; // Function Call Console.WriteLine("Missing kth number = "+ solve(arr , k , n)) ; //(array , k , size of array));}} // This code is contributed by Aarti_Rathi <script> // JavaScript programfunction solve(arr ,k ,n){ let umap = new Map() let mins = 99999 let maxs = -99999 for(let i = 0; i < n; i++){ umap.set(arr[i] , 1) //mark each element of array in map if(mins > arr[i]) mins = arr[i] //keeping track of minimum element if(maxs < arr[i]) maxs = arr[i] //keeping track of maximum element i.e. upper bound } let counts = 0 // iterate from lower to upper bound for(let i = mins; i < maxs + 1; i++){ if(!umap.has(i)) counts += 1 if(counts == k) return i } return -1} // driver code let arr = [2, 3, 5, 9, 10, 11, 12]let k = 4document.write(solve(arr , k , 7),"</br>") //(array , k , size of array) // This code is contributed by shinjanpatra </script> 8 manishshaw1 abhishekv divyeshrabadiya07 divyesh072019 rutvik_56 suresh07 kaivalyamanit mishravishal2810 RishMeh19 sagartomar9927 shivanisinghss2110 SHUBHAMSINGH10 codewithrathi shinjanpatra Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jun, 2022" }, { "code": null, "e": 253, "s": 54, "text": "Given an increasing sequence a[], we need to find the K-th missing contiguous element in the increasing sequence which is not present in the sequence. If no k-th missing element is there output -1. " }, { "code": null, "e": 265, "s": 253, "text": "Examples : " }, { "code": null, "e": 614, "s": 265, "text": "Input : a[] = {2, 3, 5, 9, 10}; \n k = 1;\nOutput : 1\nExplanation: Missing Element in the increasing \nsequence are {1,4, 6, 7, 8}. So k-th missing element\nis 1\n\nInput : a[] = {2, 3, 5, 9, 10, 11, 12}; \n k = 4;\nOutput : 7\nExplanation: missing element in the increasing \nsequence are {1, 4, 6, 7, 8} so k-th missing \nelement is 7" }, { "code": null, "e": 921, "s": 614, "text": "Approach 1: Start iterating over the array elements, and for every element check if the next element is consecutive or not, if not, then take the difference between these two, and check if the difference is greater than or equal to given k, then calculate ans = a[i] + count, else iterate for next element." }, { "code": null, "e": 925, "s": 921, "text": "C++" }, { "code": null, "e": 930, "s": 925, "text": "Java" }, { "code": null, "e": 938, "s": 930, "text": "Python3" }, { "code": null, "e": 941, "s": 938, "text": "C#" }, { "code": null, "e": 945, "s": 941, "text": "PHP" }, { "code": null, "e": 956, "s": 945, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to find k-th// missing elementint missingK(int a[], int k, int n){ int difference = 0, ans = 0, count = k; bool flag = 0; //case when first number is not 1 if (a[0] != 1){ difference = a[0]-1; if (difference >= count) return count; count -= difference; } // iterating over the array for(int i = 0 ; i < n - 1; i++) { difference = 0; // check if i-th and // (i + 1)-th element // are not consecutive if ((a[i] + 1) != a[i + 1]) { // save their difference difference += (a[i + 1] - a[i]) - 1; // check for difference // and given k if (difference >= count) { ans = a[i] + count; flag = 1; break; } else count -= difference; } } // if found if(flag) return ans; else return -1;} // Driver codeint main(){ // Input array int a[] = {1, 5, 11, 19}; // k-th missing element // to be found in the array int k = 11; int n = sizeof(a) / sizeof(a[0]); // calling function to // find missing element int missing = missingK(a, k, n); cout << missing << endl; return 0;}", "e": 2401, "s": 956, "text": null }, { "code": "// Java program to check for// even or oddimport java.io.*;import java.util.*; public class GFG { // Function to find k-th // missing element static int missingK(int []a, int k, int n) { int difference = 0, ans = 0, count = k; boolean flag = false; //case when first number is not 1 if (a[0] != 1){ difference = a[0]-1; if (difference >= count) return count; count -= difference; } // iterating over the array for(int i = 0 ; i < n - 1; i++) { difference = 0; // check if i-th and // (i + 1)-th element // are not consecutive if ((a[i] + 1) != a[i + 1]) { // save their difference difference += (a[i + 1] - a[i]) - 1; // check for difference // and given k if (difference >= count) { ans = a[i] + count; flag = true; break; } else count -= difference; } } // if found if(flag) return ans; else return -1; } // Driver code public static void main(String args[]) { // Input array int []a = {1, 5, 11, 19}; // k-th missing element // to be found in the array int k = 11; int n = a.length; // calling function to // find missing element int missing = missingK(a, k, n); System.out.print(missing); } } // This code is contributed by// Manish Shaw (manishshaw1)", "e": 4290, "s": 2401, "text": null }, { "code": "# Function to find k-th# missing elementdef missingK(a, k, n) : difference = 0 ans = 0 count = k flag = 0 #case when first number is not 1 if a[0] != 1: difference = a[0]-1 if difference >= count: return count count -= difference # iterating over the array for i in range (0, n-1) : difference = 0 # check if i-th and # (i + 1)-th element # are not consecutive if ((a[i] + 1) != a[i + 1]) : # save their difference difference += (a[i + 1] - a[i]) - 1 # check for difference # and given k if (difference >= count) : ans = a[i] + count flag = 1 break else : count -= difference # if found if(flag) : return ans else : return -1 # Driver code# Input arraya = [1, 5, 11, 19] # k-th missing element# to be found in the arrayk = 11n = len(a) # calling function to# find missing elementmissing = missingK(a, k, n) print(missing) # This code is contributed by# Manish Shaw (manishshaw1)", "e": 5475, "s": 4290, "text": null }, { "code": "// C# program to check for// even or oddusing System;using System.Collections.Generic; class GFG { // Function to find k-th // missing element static int missingK(int []a, int k, int n) { int difference = 0, ans = 0, count = k; bool flag = false; //case when first number is not 1 if (a[0] != 1){ difference = a[0]-1; if (difference >= count) return count; count -= difference; } // iterating over the array for(int i = 0 ; i < n - 1; i++) { difference = 0; // check if i-th and // (i + 1)-th element // are not consecutive if ((a[i] + 1) != a[i + 1]) { // save their difference difference += (a[i + 1] - a[i]) - 1; // check for difference // and given k if (difference >= count) { ans = a[i] + count; flag = true; break; } else count -= difference; } } // if found if(flag) return ans; else return -1; } // Driver code public static void Main() { // Input array int []a = {1, 5, 11, 19}; // k-th missing element // to be found in the array int k = 11; int n = a.Length; // calling function to // find missing element int missing = missingK(a, k, n); Console.Write(missing); } } // This code is contributed by// Manish Shaw (manishshaw1)", "e": 7333, "s": 5475, "text": null }, { "code": "<?php// Function to find k-th// missing elementfunction missingK(&$a, $k, $n){ $difference = 0; $ans = 0; $count = $k; $flag = 0; // iterating over the array for($i = 0 ; $i < $n - 1; $i++) { $difference = 0; // check if i-th and // (i + 1)-th element // are not consecutive if (($a[$i] + 1) != $a[$i + 1]) { // save their difference $difference += ($a[$i + 1] - $a[$i]) - 1; // check for difference // and given k if ($difference >= $count) { $ans = $a[$i] + $count; $flag = 1; break; } else $count -= $difference; } } // if found if($flag) return $ans; else return -1;} // Driver Code // Input array$a = array(1, 5, 11, 19); // k-th missing element// to be found in the array$k = 11;$n = count($a); // calling function to// find missing element$missing = missingK($a, $k, $n); echo $missing; // This code is contributed by Manish Shaw// (manishshaw1)?>", "e": 8524, "s": 7333, "text": null }, { "code": "<script> // Javascript program to check for// even or odd // Function to find k-th// missing elementfunction missingK(a, k, n){ let difference = 0, ans = 0, count = k; let flag = false; //case when first number is not 1 if (a[0] != 1){ difference = a[0]-1; if (difference >= count){ return count; } count -= difference; } // iterating over the array for(let i = 0 ; i < n - 1; i++) { difference = 0; // Check if i-th and // (i + 1)-th element // are not consecutive if ((a[i] + 1) != a[i + 1]) { // Save their difference difference += (a[i + 1] - a[i]) - 1; // Check for difference // and given k if (difference >= count) { ans = a[i] + count; flag = true; break; } else count -= difference; } } // If found if (flag) return ans; else return -1;} // Driver code // Input arraylet a = [ 1, 5, 11, 19 ]; // k-th missing element// to be found in the arraylet k = 11;let n = a.length; // Calling function to// find missing elementlet missing = missingK(a, k, n); document.write(missing); // This code is contributed by suresh07 </script>", "e": 9900, "s": 8524, "text": null }, { "code": null, "e": 9903, "s": 9900, "text": "14" }, { "code": null, "e": 9975, "s": 9903, "text": "Time Complexity :O(n), where n is the number of elements in the array. " }, { "code": null, "e": 9988, "s": 9975, "text": "Approach 2: " }, { "code": null, "e": 10273, "s": 9988, "text": "Apply a binary search. Since the array is sorted we can find at any given index how many numbers are missing as arr[index] – (index+1). We would leverage this knowledge and apply binary search to narrow down our hunt to find that index from which getting the missing number is easier." }, { "code": null, "e": 10324, "s": 10273, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 10328, "s": 10324, "text": "C++" }, { "code": null, "e": 10333, "s": 10328, "text": "Java" }, { "code": null, "e": 10341, "s": 10333, "text": "Python3" }, { "code": null, "e": 10344, "s": 10341, "text": "C#" }, { "code": null, "e": 10355, "s": 10344, "text": "Javascript" }, { "code": "// CPP program for above approach#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to find// kth missing numberint missingK(vector<int>& arr, int k){ int n = arr.size(); int l = 0, u = n - 1, mid; while(l <= u) { mid = (l + u)/2; int numbers_less_than_mid = arr[mid] - (mid + 1); // If the total missing number // count is equal to k we can iterate // backwards for the first missing number // and that will be the answer. if(numbers_less_than_mid == k) { // To further optimize we check // if the previous element's // missing number count is equal // to k. Eg: arr = [4,5,6,7,8] // If you observe in the example array, // the total count of missing numbers for all // the indices are same, and we are // aiming to narrow down the // search window and achieve O(logn) // time complexity which // otherwise would've been O(n). if(mid > 0 && (arr[mid - 1] - (mid)) == k) { u = mid - 1; continue; } // Else we return arr[mid] - 1. return arr[mid]-1; } // Here we appropriately // narrow down the search window. if(numbers_less_than_mid < k) { l = mid + 1; } else if(k < numbers_less_than_mid) { u = mid - 1; } } // In case the upper limit is -ve // it means the missing number set // is 1,2,..,k and hence we directly return k. if(u < 0) return k; // Else we find the residual count // of numbers which we'd then add to // arr[u] and get the missing kth number. int less = arr[u] - (u + 1); k -= less; // Return arr[u] + k return arr[u] + k;} // Driver Codeint main(){ vector<int> arr = {2,3,4,7,11}; int k = 5; // Function Call cout <<\"Missing kth number = \"<< missingK(arr, k)<<endl; return 0;}", "e": 12260, "s": 10355, "text": null }, { "code": "// Java program for above approachpublic class GFG{ // Function to find // kth missing number static int missingK(int[] arr, int k) { int n = arr.length; int l = 0, u = n - 1, mid; while(l <= u) { mid = (l + u)/2; int numbers_less_than_mid = arr[mid] - (mid + 1); // If the total missing number // count is equal to k we can iterate // backwards for the first missing number // and that will be the answer. if(numbers_less_than_mid == k) { // To further optimize we check // if the previous element's // missing number count is equal // to k. Eg: arr = [4,5,6,7,8] // If you observe in the example array, // the total count of missing numbers for all // the indices are same, and we are // aiming to narrow down the // search window and achieve O(logn) // time complexity which // otherwise would've been O(n). if(mid > 0 && (arr[mid - 1] - (mid)) == k) { u = mid - 1; continue; } // Else we return arr[mid] - 1. return arr[mid] - 1; } // Here we appropriately // narrow down the search window. if(numbers_less_than_mid < k) { l = mid + 1; } else if(k < numbers_less_than_mid) { u = mid - 1; } } // In case the upper limit is -ve // it means the missing number set // is 1,2,..,k and hence we directly return k. if(u < 0) return k; // Else we find the residual count // of numbers which we'd then add to // arr[u] and get the missing kth number. int less = arr[u] - (u + 1); k -= less; // Return arr[u] + k return arr[u] + k; } // Driver code public static void main(String[] args) { int[] arr = {2,3,4,7,11}; int k = 5; // Function Call System.out.println(\"Missing kth number = \"+ missingK(arr, k)); }} // This code is contributed by divyesh072019.", "e": 14240, "s": 12260, "text": null }, { "code": "# Python3 program for above approach # Function to find# kth missing numberdef missingK(arr, k): n = len(arr) l = 0 u = n - 1 mid = 0 while(l <= u): mid = (l + u)//2; numbers_less_than_mid = arr[mid] - (mid + 1); # If the total missing number # count is equal to k we can iterate # backwards for the first missing number # and that will be the answer. if(numbers_less_than_mid == k): # To further optimize we check # if the previous element's # missing number count is equal # to k. Eg: arr = [4,5,6,7,8] # If you observe in the example array, # the total count of missing numbers for all # the indices are same, and we are # aiming to narrow down the # search window and achieve O(logn) # time complexity which # otherwise would've been O(n). if(mid > 0 and (arr[mid - 1] - (mid)) == k): u = mid - 1; continue; # Else we return arr[mid] - 1. return arr[mid]-1; # Here we appropriately # narrow down the search window. if(numbers_less_than_mid < k): l = mid + 1; elif(k < numbers_less_than_mid): u = mid - 1; # In case the upper limit is -ve # it means the missing number set # is 1,2,..,k and hence we directly return k. if(u < 0): return k; # Else we find the residual count # of numbers which we'd then add to # arr[u] and get the missing kth number. less = arr[u] - (u + 1); k -= less; # Return arr[u] + k return arr[u] + k; # Driver Codeif __name__=='__main__': arr = [2,3,4,7,11]; k = 5; # Function Call print(\"Missing kth number = \"+ str(missingK(arr, k))) # This code is contributed by rutvik_56.", "e": 15950, "s": 14240, "text": null }, { "code": "// C# program for above approachusing System;class GFG { // Function to find // kth missing number static int missingK(int[] arr, int k) { int n = arr.Length; int l = 0, u = n - 1, mid; while(l <= u) { mid = (l + u)/2; int numbers_less_than_mid = arr[mid] - (mid + 1); // If the total missing number // count is equal to k we can iterate // backwards for the first missing number // and that will be the answer. if(numbers_less_than_mid == k) { // To further optimize we check // if the previous element's // missing number count is equal // to k. Eg: arr = [4,5,6,7,8] // If you observe in the example array, // the total count of missing numbers for all // the indices are same, and we are // aiming to narrow down the // search window and achieve O(logn) // time complexity which // otherwise would've been O(n). if(mid > 0 && (arr[mid - 1] - (mid)) == k) { u = mid - 1; continue; } // Else we return arr[mid] - 1. return arr[mid] - 1; } // Here we appropriately // narrow down the search window. if(numbers_less_than_mid < k) { l = mid + 1; } else if(k < numbers_less_than_mid) { u = mid - 1; } } // In case the upper limit is -ve // it means the missing number set // is 1,2,..,k and hence we directly return k. if(u < 0) return k; // Else we find the residual count // of numbers which we'd then add to // arr[u] and get the missing kth number. int less = arr[u] - (u + 1); k -= less; // Return arr[u] + k return arr[u] + k; } // Driver code static void Main() { int[] arr = {2,3,4,7,11}; int k = 5; // Function Call Console.WriteLine(\"Missing kth number = \"+ missingK(arr, k)); }} // This code is contributed by divyeshrabadiya07.", "e": 18143, "s": 15950, "text": null }, { "code": "<script>// JavaScript program for above approach // Function to find // kth missing number function missingK(arr, k) { var n = arr.length; var l = 0, u = n - 1, mid; while(l <= u) { mid = (l + u)/2; var numbers_less_than_mid = arr[mid] - (mid + 1); // If the total missing number // count is equal to k we can iterate // backwards for the first missing number // and that will be the answer. if(numbers_less_than_mid == k) { // To further optimize we check // if the previous element's // missing number count is equal // to k. Eg: arr = [4,5,6,7,8] // If you observe in the example array, // the total count of missing numbers for all // the indices are same, and we are // aiming to narrow down the // search window and achieve O(logn) // time complexity which // otherwise would've been O(n). if(mid > 0 && (arr[mid - 1] - (mid)) == k) { u = mid - 1; continue; } // Else we return arr[mid] - 1. return arr[mid] - 1; } // Here we appropriately // narrow down the search window. if(numbers_less_than_mid < k) { l = mid + 1; } else if(k < numbers_less_than_mid) { u = mid - 1; } } // In case the upper limit is -ve // it means the missing number set // is 1,2,..,k and hence we directly return k. if(u < 0) return k; // Else we find the residual count // of numbers which we'd then add to // arr[u] and get the missing kth number. var less = arr[u] - (u + 1); k -= less; // Return arr[u] + k return arr[u] + k; } // Driver code var arr = [2,3,4,7,11]; var k = 5; // Function Call document.write(\"Missing kth number = \"+ missingK(arr, k)); // This code is contributed by shivanisinghss2110 </script>", "e": 20072, "s": 18143, "text": null }, { "code": null, "e": 20095, "s": 20072, "text": "Missing kth number = 9" }, { "code": null, "e": 20169, "s": 20095, "text": "Time Complexity: O(logn), where n is the number of elements in the array." }, { "code": null, "e": 20609, "s": 20169, "text": "Approach 3 (Using Map): We will traverse the array and mark each of the elements as visited in the map and we will also keep track of the min and max element present so that we know the lower and upper bound for the given particular input. Then we start a loop from lower to upper bound and maintain a count variable. As soon we found an element that is not present in the map we increment the count and until the count becomes equal to k." }, { "code": null, "e": 20615, "s": 20609, "text": "C++14" }, { "code": null, "e": 20620, "s": 20615, "text": "Java" }, { "code": null, "e": 20628, "s": 20620, "text": "Python3" }, { "code": null, "e": 20631, "s": 20628, "text": "C#" }, { "code": null, "e": 20642, "s": 20631, "text": "Javascript" }, { "code": "#include <iostream>#include <unordered_map>using namespace std; int solve(int arr[] , int k , int n){ unordered_map<int ,int> umap; int mins = 99999; int maxs = -99999; for(int i=0 ; i<n ; i++) { umap[arr[i]] = 1; //mark each element of array in map if(mins > arr[i]) mins = arr[i]; //keeping track of minimum element if(maxs < arr[i]) maxs = arr[i]; //keeping track of maximum element i.e. upper bound } int counts = 0; //iterate from lower to upper bound for(int i=mins ; i<=maxs ; i++) { if(umap[i] == 0) counts++; if(counts == k) return i; } return -1;}int main() { int arr[] = {2, 3, 5, 9, 10, 11, 12} ; int k = 4; cout << solve(arr , k , 7) ; //(array , k , size of array) return 0;}", "e": 21480, "s": 20642, "text": null }, { "code": "// Java approach // Importing HashMap classimport java.util.HashMap;class GFG { public static int solve(int arr[] , int k , int n) { HashMap<Integer, Integer> umap = new HashMap<Integer, Integer>(); int mins = 99999; int maxs = -99999; for(int i = 0; i < n; i++) { umap.put(arr[i], 1); // mark each element of array in map if(mins > arr[i]) mins = arr[i]; // keeping track of minimum element if(maxs < arr[i]) maxs = arr[i]; // keeping track of maximum element i.e. upper bound } int counts = 0; // iterate from lower to upper bound for(int i = mins; i <= maxs; i++) { if(umap.get(i) == null) counts++; if(counts == k) return i; } return -1; } public static void main (String[] args) { int arr[] = {2, 3, 5, 9, 10, 11, 12} ; int k = 4; System.out.println(solve(arr , k , 7)); //(array , k , size of array) }} // This code is contributed by Shubham Singh", "e": 22441, "s": 21480, "text": null }, { "code": "# Python approachdef solve( arr , k , n): umap = {} mins = 99999 maxs = -99999 for i in range(n): umap[arr[i]] = 1 #mark each element of array in map if(mins > arr[i]): mins = arr[i] #keeping track of minimum element if(maxs < arr[i]): maxs = arr[i] #keeping track of maximum element i.e. upper bound counts = 0 # iterate from lower to upper bound for i in range(mins, maxs+1): if(i not in umap): counts += 1 if(counts == k): return i return -1 arr = [2, 3, 5, 9, 10, 11, 12]k = 4print(solve(arr , k , 7)) #(array , k , size of array) # This code is contributed# by Shubham Singh", "e": 23146, "s": 22441, "text": null }, { "code": "// C# program for above approachusing System;using System.Collections.Generic;class GFG { // Function to find // kth missing number static int solve(int[] arr, int k, int n) { Dictionary < int, int > umap = new Dictionary < int, int > (); int mins = 99999; int maxs = -99999; for(int i=0 ; i<n ; i++) { umap.Add(arr[i], 1); //mark each element of array in map if(mins > arr[i]) mins = arr[i]; //keeping track of minimum element if(maxs < arr[i]) maxs = arr[i]; //keeping track of maximum element i.e. upper bound } int counts = 0; //iterate from lower to upper bound for(int i=mins ; i<=maxs ; i++) { if(!umap.ContainsKey(i)) counts++; if(counts == k) return i; } return -1; } // Driver codestatic void Main(){ int[] arr = {2, 3, 5, 9, 10, 11, 12}; int k = 4; int n = arr.Length; // Function Call Console.WriteLine(\"Missing kth number = \"+ solve(arr , k , n)) ; //(array , k , size of array));}} // This code is contributed by Aarti_Rathi", "e": 24338, "s": 23146, "text": null }, { "code": "<script> // JavaScript programfunction solve(arr ,k ,n){ let umap = new Map() let mins = 99999 let maxs = -99999 for(let i = 0; i < n; i++){ umap.set(arr[i] , 1) //mark each element of array in map if(mins > arr[i]) mins = arr[i] //keeping track of minimum element if(maxs < arr[i]) maxs = arr[i] //keeping track of maximum element i.e. upper bound } let counts = 0 // iterate from lower to upper bound for(let i = mins; i < maxs + 1; i++){ if(!umap.has(i)) counts += 1 if(counts == k) return i } return -1} // driver code let arr = [2, 3, 5, 9, 10, 11, 12]let k = 4document.write(solve(arr , k , 7),\"</br>\") //(array , k , size of array) // This code is contributed by shinjanpatra </script>", "e": 25161, "s": 24338, "text": null }, { "code": null, "e": 25163, "s": 25161, "text": "8" }, { "code": null, "e": 25175, "s": 25163, "text": "manishshaw1" }, { "code": null, "e": 25185, "s": 25175, "text": "abhishekv" }, { "code": null, "e": 25203, "s": 25185, "text": "divyeshrabadiya07" }, { "code": null, "e": 25217, "s": 25203, "text": "divyesh072019" }, { "code": null, "e": 25227, "s": 25217, "text": "rutvik_56" }, { "code": null, "e": 25236, "s": 25227, "text": "suresh07" }, { "code": null, "e": 25250, "s": 25236, "text": "kaivalyamanit" }, { "code": null, "e": 25267, "s": 25250, "text": "mishravishal2810" }, { "code": null, "e": 25277, "s": 25267, "text": "RishMeh19" }, { "code": null, "e": 25292, "s": 25277, "text": "sagartomar9927" }, { "code": null, "e": 25311, "s": 25292, "text": "shivanisinghss2110" }, { "code": null, "e": 25326, "s": 25311, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 25340, "s": 25326, "text": "codewithrathi" }, { "code": null, "e": 25353, "s": 25340, "text": "shinjanpatra" }, { "code": null, "e": 25360, "s": 25353, "text": "Arrays" }, { "code": null, "e": 25370, "s": 25360, "text": "Searching" }, { "code": null, "e": 25377, "s": 25370, "text": "Arrays" }, { "code": null, "e": 25387, "s": 25377, "text": "Searching" }, { "code": null, "e": 25485, "s": 25387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25553, "s": 25485, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 25597, "s": 25553, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 25629, "s": 25597, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 25677, "s": 25629, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 25691, "s": 25677, "text": "Linear Search" }, { "code": null, "e": 25705, "s": 25691, "text": "Binary Search" }, { "code": null, "e": 25773, "s": 25705, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 25787, "s": 25773, "text": "Linear Search" }, { "code": null, "e": 25843, "s": 25787, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
Hypothesis Testing in R Programming
22 Jun, 2020 A hypothesis is made by the researchers about the data collected for any experiment or data set. A hypothesis is an assumption made by the researchers that are not mandatory true. In simple words, a hypothesis is a decision taken by the researchers based on the data of the population collected. Hypothesis Testing in R Programming is a process of testing the hypothesis made by the researcher or to validate the hypothesis. To perform hypothesis testing, a random sample of data from the population is taken and testing is performed. Based on the results of testing, the hypothesis is either selected or rejected. This concept is known as Statistical Inference. In this article, we’ll discuss the four-step process of hypothesis testing, One sample T-Testing, Two-sample T-Testing, Directional Hypothesis, one sample -test, two sample -test and correlation test in R programming. There are 4 major steps in hypothesis testing: State the hypothesis- This step is started by stating null and alternative hypothesis which is presumed as true. Formulate an analysis plan and set the criteria for decision- In this step, significance level of test is set. The significance level is the probability of a false rejection in a hypothesis test. Analyze sample data- In this, a test statistic is used to formulate the statistical comparison between the sample mean and the mean of the population or standard deviation of the sample and standard deviation of the population. Interpret decision- The value of the test statistic is used to make the decision based on the significance level. For example, if the significance level is set to 0.1 probability, then the sample mean less than 10% will be rejected. Otherwise, the hypothesis is retained to be true. One sample T-Testing approach collects a huge amount of data and tests it on random samples. To perform T-Test in R, normally distributed data is required. This test is used to test the mean of the sample with the population. For example, the height of persons living in an area is different or identical to other persons living in other areas. Syntax: t.test(x, mu) Parameters:x: represents numeric vector of data mu: represents true value of the mean To know about more optional parameters of t.test(), try below command: help("t.test") Example: # Defining sample vectorx <- rnorm(100) # One Sample T-Testt.test(x, mu = 5) Output: One Sample t-test data: x t = -49.504, df = 99, p-value < 2.2e-16 alternative hypothesis: true mean is not equal to 5 95 percent confidence interval: -0.1910645 0.2090349 sample estimates: mean of x 0.008985172 In two sample T-Testing, the sample vectors are compared. If var.equal = TRUE, the test assumes that the variances of both the samples are equal. Syntax: t.test(x, y) Parameters:x and y: Numeric vectors Example: # Defining sample vectorx <- rnorm(100)y <- rnorm(100) # Two Sample T-Testt.test(x, y) Output: Welch Two Sample t-test data: x and y t = -1.0601, df = 197.86, p-value = 0.2904 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -0.4362140 0.1311918 sample estimates: mean of x mean of y -0.05075633 0.10175478 Using the directional hypothesis, the direction of the hypothesis can be specified like, if the user wants to know the sample mean is lower or greater than another mean sample of the data. Syntax: t.test(x, mu, alternative) Parameters:x: represents numeric vector data mu: represents mean against which sample data has to be tested alternative: sets the alternative hypothesis Example: # Defining sample vectorx <- rnorm(100) # Directional hypothesis testingt.test(x, mu = 2, alternative = 'greater') Output: One Sample t-test data: x t = -20.708, df = 99, p-value = 1 alternative hypothesis: true mean is greater than 2 95 percent confidence interval: -0.2307534 Inf sample estimates: mean of x -0.0651628 This type of test is used when comparison has to computed on one sample and the data is non-parametric. It is performed using wilcox.test() function in R programming. Syntax: wilcox.test(x, y, exact = NULL) Parameters:x and y: represents numeric vector exact: represents logical value which indicates whether p-value be computed To know about more optional parameters of wilcox.test(), use below command: help("wilcox.test") Example: # Define vectorx <- rnorm(100) # one sample testwilcox.test(x, exact = FALSE) Output: Wilcoxon signed rank test with continuity correction data: x V = 2555, p-value = 0.9192 alternative hypothesis: true location is not equal to 0 This test is performed to compare two samples of data. Example: # Define vectorsx <- rnorm(100)y <- rnorm(100) # Two sample testwilcox.test(x, y) Output: Wilcoxon rank sum test with continuity correction data: x and y W = 5300, p-value = 0.4643 alternative hypothesis: true location shift is not equal to 0 This test is used to compare the correlation of the two vectors provided in the function call or to test for the association between the paired samples. Syntax: cor.test(x, y) Parameters:x and y: represents numeric data vectors To know about more optional parameters in cor.test() function, use below command: help("cor.test") Example: # Using mtcars dataset in Rcor.test(mtcars$mpg, mtcars$hp) Output: Pearson's product-moment correlation data: mtcars$mpg and mtcars$hp t = -6.7424, df = 30, p-value = 1.788e-07 alternative hypothesis: true correlation is not equal to 0 95 percent confidence interval: -0.8852686 -0.5860994 sample estimates: cor -0.7761684 R-Mathematics 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": "\n22 Jun, 2020" }, { "code": null, "e": 909, "s": 28, "text": "A hypothesis is made by the researchers about the data collected for any experiment or data set. A hypothesis is an assumption made by the researchers that are not mandatory true. In simple words, a hypothesis is a decision taken by the researchers based on the data of the population collected. Hypothesis Testing in R Programming is a process of testing the hypothesis made by the researcher or to validate the hypothesis. To perform hypothesis testing, a random sample of data from the population is taken and testing is performed. Based on the results of testing, the hypothesis is either selected or rejected. This concept is known as Statistical Inference. In this article, we’ll discuss the four-step process of hypothesis testing, One sample T-Testing, Two-sample T-Testing, Directional Hypothesis, one sample -test, two sample -test and correlation test in R programming." }, { "code": null, "e": 956, "s": 909, "text": "There are 4 major steps in hypothesis testing:" }, { "code": null, "e": 1069, "s": 956, "text": "State the hypothesis- This step is started by stating null and alternative hypothesis which is presumed as true." }, { "code": null, "e": 1265, "s": 1069, "text": "Formulate an analysis plan and set the criteria for decision- In this step, significance level of test is set. The significance level is the probability of a false rejection in a hypothesis test." }, { "code": null, "e": 1493, "s": 1265, "text": "Analyze sample data- In this, a test statistic is used to formulate the statistical comparison between the sample mean and the mean of the population or standard deviation of the sample and standard deviation of the population." }, { "code": null, "e": 1776, "s": 1493, "text": "Interpret decision- The value of the test statistic is used to make the decision based on the significance level. For example, if the significance level is set to 0.1 probability, then the sample mean less than 10% will be rejected. Otherwise, the hypothesis is retained to be true." }, { "code": null, "e": 2121, "s": 1776, "text": "One sample T-Testing approach collects a huge amount of data and tests it on random samples. To perform T-Test in R, normally distributed data is required. This test is used to test the mean of the sample with the population. For example, the height of persons living in an area is different or identical to other persons living in other areas." }, { "code": null, "e": 2143, "s": 2121, "text": "Syntax: t.test(x, mu)" }, { "code": null, "e": 2191, "s": 2143, "text": "Parameters:x: represents numeric vector of data" }, { "code": null, "e": 2229, "s": 2191, "text": "mu: represents true value of the mean" }, { "code": null, "e": 2300, "s": 2229, "text": "To know about more optional parameters of t.test(), try below command:" }, { "code": null, "e": 2316, "s": 2300, "text": "help(\"t.test\")\n" }, { "code": null, "e": 2325, "s": 2316, "text": "Example:" }, { "code": "# Defining sample vectorx <- rnorm(100) # One Sample T-Testt.test(x, mu = 5)", "e": 2403, "s": 2325, "text": null }, { "code": null, "e": 2411, "s": 2403, "text": "Output:" }, { "code": null, "e": 2635, "s": 2411, "text": " One Sample t-test\n\ndata: x\nt = -49.504, df = 99, p-value < 2.2e-16\nalternative hypothesis: true mean is not equal to 5\n95 percent confidence interval:\n -0.1910645 0.2090349\nsample estimates:\n mean of x \n0.008985172 \n" }, { "code": null, "e": 2781, "s": 2635, "text": "In two sample T-Testing, the sample vectors are compared. If var.equal = TRUE, the test assumes that the variances of both the samples are equal." }, { "code": null, "e": 2802, "s": 2781, "text": "Syntax: t.test(x, y)" }, { "code": null, "e": 2838, "s": 2802, "text": "Parameters:x and y: Numeric vectors" }, { "code": null, "e": 2847, "s": 2838, "text": "Example:" }, { "code": "# Defining sample vectorx <- rnorm(100)y <- rnorm(100) # Two Sample T-Testt.test(x, y)", "e": 2935, "s": 2847, "text": null }, { "code": null, "e": 2943, "s": 2935, "text": "Output:" }, { "code": null, "e": 3225, "s": 2943, "text": " Welch Two Sample t-test\n\ndata: x and y\nt = -1.0601, df = 197.86, p-value = 0.2904\nalternative hypothesis: true difference in means is not equal to 0\n95 percent confidence interval:\n -0.4362140 0.1311918\nsample estimates:\n mean of x mean of y \n-0.05075633 0.10175478 \n" }, { "code": null, "e": 3414, "s": 3225, "text": "Using the directional hypothesis, the direction of the hypothesis can be specified like, if the user wants to know the sample mean is lower or greater than another mean sample of the data." }, { "code": null, "e": 3449, "s": 3414, "text": "Syntax: t.test(x, mu, alternative)" }, { "code": null, "e": 3494, "s": 3449, "text": "Parameters:x: represents numeric vector data" }, { "code": null, "e": 3557, "s": 3494, "text": "mu: represents mean against which sample data has to be tested" }, { "code": null, "e": 3602, "s": 3557, "text": "alternative: sets the alternative hypothesis" }, { "code": null, "e": 3611, "s": 3602, "text": "Example:" }, { "code": "# Defining sample vectorx <- rnorm(100) # Directional hypothesis testingt.test(x, mu = 2, alternative = 'greater')", "e": 3727, "s": 3611, "text": null }, { "code": null, "e": 3735, "s": 3727, "text": "Output:" }, { "code": null, "e": 3955, "s": 3735, "text": " One Sample t-test\n\ndata: x\nt = -20.708, df = 99, p-value = 1\nalternative hypothesis: true mean is greater than 2\n95 percent confidence interval:\n -0.2307534 Inf\nsample estimates:\n mean of x \n-0.0651628 \n" }, { "code": null, "e": 4122, "s": 3955, "text": "This type of test is used when comparison has to computed on one sample and the data is non-parametric. It is performed using wilcox.test() function in R programming." }, { "code": null, "e": 4162, "s": 4122, "text": "Syntax: wilcox.test(x, y, exact = NULL)" }, { "code": null, "e": 4208, "s": 4162, "text": "Parameters:x and y: represents numeric vector" }, { "code": null, "e": 4284, "s": 4208, "text": "exact: represents logical value which indicates whether p-value be computed" }, { "code": null, "e": 4360, "s": 4284, "text": "To know about more optional parameters of wilcox.test(), use below command:" }, { "code": null, "e": 4381, "s": 4360, "text": "help(\"wilcox.test\")\n" }, { "code": null, "e": 4390, "s": 4381, "text": "Example:" }, { "code": "# Define vectorx <- rnorm(100) # one sample testwilcox.test(x, exact = FALSE)", "e": 4469, "s": 4390, "text": null }, { "code": null, "e": 4477, "s": 4469, "text": "Output:" }, { "code": null, "e": 4632, "s": 4477, "text": " Wilcoxon signed rank test with continuity correction\n\ndata: x\nV = 2555, p-value = 0.9192\nalternative hypothesis: true location is not equal to 0\n" }, { "code": null, "e": 4687, "s": 4632, "text": "This test is performed to compare two samples of data." }, { "code": null, "e": 4696, "s": 4687, "text": "Example:" }, { "code": "# Define vectorsx <- rnorm(100)y <- rnorm(100) # Two sample testwilcox.test(x, y)", "e": 4779, "s": 4696, "text": null }, { "code": null, "e": 4787, "s": 4779, "text": "Output:" }, { "code": null, "e": 4951, "s": 4787, "text": " Wilcoxon rank sum test with continuity correction\n\ndata: x and y\nW = 5300, p-value = 0.4643\nalternative hypothesis: true location shift is not equal to 0\n" }, { "code": null, "e": 5104, "s": 4951, "text": "This test is used to compare the correlation of the two vectors provided in the function call or to test for the association between the paired samples." }, { "code": null, "e": 5127, "s": 5104, "text": "Syntax: cor.test(x, y)" }, { "code": null, "e": 5179, "s": 5127, "text": "Parameters:x and y: represents numeric data vectors" }, { "code": null, "e": 5261, "s": 5179, "text": "To know about more optional parameters in cor.test() function, use below command:" }, { "code": null, "e": 5278, "s": 5261, "text": "help(\"cor.test\")" }, { "code": null, "e": 5287, "s": 5278, "text": "Example:" }, { "code": "# Using mtcars dataset in Rcor.test(mtcars$mpg, mtcars$hp)", "e": 5346, "s": 5287, "text": null }, { "code": null, "e": 5354, "s": 5346, "text": "Output:" }, { "code": null, "e": 5629, "s": 5354, "text": " Pearson's product-moment correlation\n\ndata: mtcars$mpg and mtcars$hp\nt = -6.7424, df = 30, p-value = 1.788e-07\nalternative hypothesis: true correlation is not equal to 0\n95 percent confidence interval:\n -0.8852686 -0.5860994\nsample estimates:\n cor \n-0.7761684" }, { "code": null, "e": 5643, "s": 5629, "text": "R-Mathematics" }, { "code": null, "e": 5656, "s": 5643, "text": "R-Statistics" }, { "code": null, "e": 5667, "s": 5656, "text": "R Language" } ]
CSS | border-inline-style Property
18 Mar, 2020 The border-inline-style property is an inbuilt property in CSS which is used to set the individual logical block inline-border-style property values in a single place in the style sheet. It sets the inline border-style top(left), and bottom(right) of the defining border element. Syntax: border-inline-style: style; Property values: style: This property holds the style of the border dashed, border, dotted, etc. Below examples illustrate the border-inline-style property in the CSS:Example 1: <!DOCTYPE html><html> <head> <title>CSS | border-inline-style Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 220px; height: 40px; } .one { border: 5px solid cyan; border-inline-style: dashed; background-color: purple; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | border-inline-style Property</b> <br><br> <div class="one">A Computer Science Portal</div> </center></body> </html> Output: Example 2: <!DOCTYPE html><html> <head> <title>CSS | border-inline-style Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 220px; height: 40px; } .one { border: 5px dotted cyan; border-inline-style: solid; background-color: purple; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | border-inline-style Property</b> <br><br> <div class="one">A Computer Science Portal</div> </center></body> </html> Output: Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-style#:~:text=The%20border%2Dinline%2Dstyle%20CSS,%2C%20directionality%2C%20and%20text%20orientation. Supported Browsers: The browser supported by border-inline-style property are listed below: Firefox Opera Edge CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Mar, 2020" }, { "code": null, "e": 308, "s": 28, "text": "The border-inline-style property is an inbuilt property in CSS which is used to set the individual logical block inline-border-style property values in a single place in the style sheet. It sets the inline border-style top(left), and bottom(right) of the defining border element." }, { "code": null, "e": 316, "s": 308, "text": "Syntax:" }, { "code": null, "e": 344, "s": 316, "text": "border-inline-style: style;" }, { "code": null, "e": 361, "s": 344, "text": "Property values:" }, { "code": null, "e": 441, "s": 361, "text": "style: This property holds the style of the border dashed, border, dotted, etc." }, { "code": null, "e": 522, "s": 441, "text": "Below examples illustrate the border-inline-style property in the CSS:Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS | border-inline-style Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 220px; height: 40px; } .one { border: 5px solid cyan; border-inline-style: dashed; background-color: purple; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | border-inline-style Property</b> <br><br> <div class=\"one\">A Computer Science Portal</div> </center></body> </html> ", "e": 1165, "s": 522, "text": null }, { "code": null, "e": 1173, "s": 1165, "text": "Output:" }, { "code": null, "e": 1184, "s": 1173, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS | border-inline-style Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 220px; height: 40px; } .one { border: 5px dotted cyan; border-inline-style: solid; background-color: purple; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | border-inline-style Property</b> <br><br> <div class=\"one\">A Computer Science Portal</div> </center></body> </html> ", "e": 1827, "s": 1184, "text": null }, { "code": null, "e": 1835, "s": 1827, "text": "Output:" }, { "code": null, "e": 2011, "s": 1835, "text": "Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/border-inline-style#:~:text=The%20border%2Dinline%2Dstyle%20CSS,%2C%20directionality%2C%20and%20text%20orientation." }, { "code": null, "e": 2103, "s": 2011, "text": "Supported Browsers: The browser supported by border-inline-style property are listed below:" }, { "code": null, "e": 2111, "s": 2103, "text": "Firefox" }, { "code": null, "e": 2117, "s": 2111, "text": "Opera" }, { "code": null, "e": 2122, "s": 2117, "text": "Edge" }, { "code": null, "e": 2137, "s": 2122, "text": "CSS-Properties" }, { "code": null, "e": 2141, "s": 2137, "text": "CSS" }, { "code": null, "e": 2158, "s": 2141, "text": "Web Technologies" } ]
Color game using Tkinter in Python
16 Jul, 2020 Prerequisite : Python GUI Tkinter TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games. Let’s try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to play this game is 30 seconds. Colors used in this game are Red, Blue, Green, Pink, Black, Yellow, Orange, White, Purple and Brown. Interface will display name of different colors in different colors. Player has to identify the color and enter the correct color name to win the game. Below is the implementation of above game : # import the modules import tkinterimport random # list of possible colour.colours = ['Red','Blue','Green','Pink','Black', 'Yellow','Orange','White','Purple','Brown']score = 0 # the game time left, initially 30 seconds.timeleft = 30 # function that will start the game.def startGame(event): if timeleft == 30: # start the countdown timer. countdown() # run the function to # choose the next colour. nextColour() # Function to choose and# display the next colour.def nextColour(): # use the globally declared 'score' # and 'play' variables above. global score global timeleft # if a game is currently in play if timeleft > 0: # make the text entry box active. e.focus_set() # if the colour typed is equal # to the colour of the text if e.get().lower() == colours[1].lower(): score += 1 # clear the text entry box. e.delete(0, tkinter.END) random.shuffle(colours) # change the colour to type, by changing the # text _and_ the colour to a random colour value label.config(fg = str(colours[1]), text = str(colours[0])) # update the score. scoreLabel.config(text = "Score: " + str(score)) # Countdown timer function def countdown(): global timeleft # if a game is in play if timeleft > 0: # decrement the timer. timeleft -= 1 # update the time left label timeLabel.config(text = "Time left: " + str(timeleft)) # run the function again after 1 second. timeLabel.after(1000, countdown) # Driver Code # create a GUI windowroot = tkinter.Tk() # set the titleroot.title("COLORGAME") # set the sizeroot.geometry("375x200") # add an instructions labelinstructions = tkinter.Label(root, text = "Type in the colour" "of the words, and not the word text!", font = ('Helvetica', 12))instructions.pack() # add a score labelscoreLabel = tkinter.Label(root, text = "Press enter to start", font = ('Helvetica', 12))scoreLabel.pack() # add a time left labeltimeLabel = tkinter.Label(root, text = "Time left: " + str(timeleft), font = ('Helvetica', 12)) timeLabel.pack() # add a label for displaying the colourslabel = tkinter.Label(root, font = ('Helvetica', 60))label.pack() # add a text entry box for# typing in colourse = tkinter.Entry(root) # run the 'startGame' function # when the enter key is pressedroot.bind('<Return>', startGame)e.pack() # set focus on the entry boxe.focus_set() # start the GUIroot.mainloop() Output : Note : Above code may not run on online IDE because of TKinter module. Python-projects Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Implementing Web Scraping in Python with BeautifulSoup OpenCV C++ Program for Face Detection 10 Best Web Development Projects For Your Resume Simple Chat Room using Python Twitter Sentiment Analysis using Python Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jul, 2020" }, { "code": null, "e": 87, "s": 53, "text": "Prerequisite : Python GUI Tkinter" }, { "code": null, "e": 214, "s": 87, "text": "TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games." }, { "code": null, "e": 715, "s": 214, "text": "Let’s try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to play this game is 30 seconds. Colors used in this game are Red, Blue, Green, Pink, Black, Yellow, Orange, White, Purple and Brown. Interface will display name of different colors in different colors. Player has to identify the color and enter the correct color name to win the game. Below is the implementation of above game :" }, { "code": "# import the modules import tkinterimport random # list of possible colour.colours = ['Red','Blue','Green','Pink','Black', 'Yellow','Orange','White','Purple','Brown']score = 0 # the game time left, initially 30 seconds.timeleft = 30 # function that will start the game.def startGame(event): if timeleft == 30: # start the countdown timer. countdown() # run the function to # choose the next colour. nextColour() # Function to choose and# display the next colour.def nextColour(): # use the globally declared 'score' # and 'play' variables above. global score global timeleft # if a game is currently in play if timeleft > 0: # make the text entry box active. e.focus_set() # if the colour typed is equal # to the colour of the text if e.get().lower() == colours[1].lower(): score += 1 # clear the text entry box. e.delete(0, tkinter.END) random.shuffle(colours) # change the colour to type, by changing the # text _and_ the colour to a random colour value label.config(fg = str(colours[1]), text = str(colours[0])) # update the score. scoreLabel.config(text = \"Score: \" + str(score)) # Countdown timer function def countdown(): global timeleft # if a game is in play if timeleft > 0: # decrement the timer. timeleft -= 1 # update the time left label timeLabel.config(text = \"Time left: \" + str(timeleft)) # run the function again after 1 second. timeLabel.after(1000, countdown) # Driver Code # create a GUI windowroot = tkinter.Tk() # set the titleroot.title(\"COLORGAME\") # set the sizeroot.geometry(\"375x200\") # add an instructions labelinstructions = tkinter.Label(root, text = \"Type in the colour\" \"of the words, and not the word text!\", font = ('Helvetica', 12))instructions.pack() # add a score labelscoreLabel = tkinter.Label(root, text = \"Press enter to start\", font = ('Helvetica', 12))scoreLabel.pack() # add a time left labeltimeLabel = tkinter.Label(root, text = \"Time left: \" + str(timeleft), font = ('Helvetica', 12)) timeLabel.pack() # add a label for displaying the colourslabel = tkinter.Label(root, font = ('Helvetica', 60))label.pack() # add a text entry box for# typing in colourse = tkinter.Entry(root) # run the 'startGame' function # when the enter key is pressedroot.bind('<Return>', startGame)e.pack() # set focus on the entry boxe.focus_set() # start the GUIroot.mainloop()", "e": 3528, "s": 715, "text": null }, { "code": null, "e": 3537, "s": 3528, "text": "Output :" }, { "code": null, "e": 3608, "s": 3537, "text": "Note : Above code may not run on online IDE because of TKinter module." }, { "code": null, "e": 3624, "s": 3608, "text": "Python-projects" }, { "code": null, "e": 3632, "s": 3624, "text": "Project" }, { "code": null, "e": 3639, "s": 3632, "text": "Python" }, { "code": null, "e": 3737, "s": 3639, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3792, "s": 3737, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 3830, "s": 3792, "text": "OpenCV C++ Program for Face Detection" }, { "code": null, "e": 3879, "s": 3830, "text": "10 Best Web Development Projects For Your Resume" }, { "code": null, "e": 3909, "s": 3879, "text": "Simple Chat Room using Python" }, { "code": null, "e": 3949, "s": 3909, "text": "Twitter Sentiment Analysis using Python" }, { "code": null, "e": 3977, "s": 3949, "text": "Read JSON file using Python" }, { "code": null, "e": 3999, "s": 3977, "text": "Python map() function" }, { "code": null, "e": 4049, "s": 3999, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4067, "s": 4049, "text": "Python Dictionary" } ]
HashMap size() Method in Java
26 Nov, 2018 The java.util.HashMap.size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map. Syntax: Hash_Map.size() Parameters: The method does not take any parameters. Return Value: The method returns the size of the map which also means the number of key-value pairs present in the map. Below programs illustrates the working of java.util.HashMap.size():Program 1: Mapping String Values to Integer Keys. // Java code to illustrate the size() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Displaying the size of the map System.out.println("The size of the map is " + hash_map.size()); }} Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} The size of the map is 5 Program 2: Mapping Integer Values to String Keys. // Java code to illustrate the size() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys hash_map.put("Geeks", 10); hash_map.put("4", 15); hash_map.put("Geeks", 20); hash_map.put("Welcomes", 25); hash_map.put("You", 30); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Displaying the size of the map System.out.println("The size of the map is " + hash_map.size()); }} Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25} The size of the map is 4 Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. Java - util package Java-Collections Java-Functions Java-HashMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Nov, 2018" }, { "code": null, "e": 214, "s": 53, "text": "The java.util.HashMap.size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map." }, { "code": null, "e": 222, "s": 214, "text": "Syntax:" }, { "code": null, "e": 238, "s": 222, "text": "Hash_Map.size()" }, { "code": null, "e": 291, "s": 238, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 411, "s": 291, "text": "Return Value: The method returns the size of the map which also means the number of key-value pairs present in the map." }, { "code": null, "e": 528, "s": 411, "text": "Below programs illustrates the working of java.util.HashMap.size():Program 1: Mapping String Values to Integer Keys." }, { "code": "// Java code to illustrate the size() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, \"Geeks\"); hash_map.put(15, \"4\"); hash_map.put(20, \"Geeks\"); hash_map.put(25, \"Welcomes\"); hash_map.put(30, \"You\"); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Displaying the size of the map System.out.println(\"The size of the map is \" + hash_map.size()); }}", "e": 1215, "s": 528, "text": null }, { "code": null, "e": 1311, "s": 1215, "text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nThe size of the map is 5\n" }, { "code": null, "e": 1361, "s": 1311, "text": "Program 2: Mapping Integer Values to String Keys." }, { "code": "// Java code to illustrate the size() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys hash_map.put(\"Geeks\", 10); hash_map.put(\"4\", 15); hash_map.put(\"Geeks\", 20); hash_map.put(\"Welcomes\", 25); hash_map.put(\"You\", 30); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Displaying the size of the map System.out.println(\"The size of the map is \" + hash_map.size()); }}", "e": 2048, "s": 1361, "text": null }, { "code": null, "e": 2134, "s": 2048, "text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nThe size of the map is 4\n" }, { "code": null, "e": 2258, "s": 2134, "text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types." }, { "code": null, "e": 2278, "s": 2258, "text": "Java - util package" }, { "code": null, "e": 2295, "s": 2278, "text": "Java-Collections" }, { "code": null, "e": 2310, "s": 2295, "text": "Java-Functions" }, { "code": null, "e": 2323, "s": 2310, "text": "Java-HashMap" }, { "code": null, "e": 2328, "s": 2323, "text": "Java" }, { "code": null, "e": 2333, "s": 2328, "text": "Java" }, { "code": null, "e": 2350, "s": 2333, "text": "Java-Collections" } ]
Check if a given string is a valid number (Integer or Floating Point) | SET 1(Basic approach)
10 Oct, 2019 Validate if a given string is numeric. Examples: Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false The following cases need to be handled in the code. Ignore the leading and trailing white spaces.Ignore the ‘+’, ‘-‘ and’.’ at the start.Ensure that the characters in the string belong to {+, -, ., e, [0-9]}Ensure that no ‘.’ comes after ‘e’.A dot character ‘.’ should be followed by a digit.The character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit. Ignore the leading and trailing white spaces. Ignore the ‘+’, ‘-‘ and’.’ at the start. Ensure that the characters in the string belong to {+, -, ., e, [0-9]} Ensure that no ‘.’ comes after ‘e’. A dot character ‘.’ should be followed by a digit. The character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit. Below is implementation of above steps. C++ Java Python3 C# // C++ program to check if input number// is a valid number#include <bits/stdc++.h>#include <iostream>using namespace std; int valid_number(string str){ int i = 0, j = str.length() - 1; // Handling whitespaces while (i < str.length() && str[i] == ' ') i++; while (j >= 0 && str[j] == ' ') j--; if (i > j) return 0; // if string is of length 1 and the only // character is not a digit if (i == j && !(str[i] >= '0' && str[i] <= '9')) return 0; // If the 1st char is not '+', '-', '.' or digit if (str[i] != '.' && str[i] != '+' && str[i] != '-' && !(str[i] >= '0' && str[i] <= '9')) return 0; // To check if a '.' or 'e' is found in given // string. We use this flag to make sure that // either of them appear only once. bool flagDotOrE = false; for (i; i <= j; i++) { // If any of the char does not belong to // {digit, +, -, ., e} if (str[i] != 'e' && str[i] != '.' && str[i] != '+' && str[i] != '-' && !(str[i] >= '0' && str[i] <= '9')) return 0; if (str[i] == '.') { // checks if the char 'e' has already // occurred before '.' If yes, return 0. if (flagDotOrE == true) return 0; // If '.' is the last character. if (i + 1 > str.length()) return 0; // if '.' is not followed by a digit. if (!(str[i + 1] >= '0' && str[i + 1] <= '9')) return 0; } else if (str[i] == 'e') { // set flagDotOrE = 1 when e is encountered. flagDotOrE = true; // if there is no digit before 'e'. if (!(str[i - 1] >= '0' && str[i - 1] <= '9')) return 0; // If 'e' is the last Character if (i + 1 > str.length()) return 0; // if e is not followed either by // '+', '-' or a digit if (str[i + 1] != '+' && str[i + 1] != '-' && (str[i + 1] >= '0' && str[i] <= '9')) return 0; } } /* If the string skips all above cases, then it is numeric*/ return 1;} // Driver codeint main(){ char str[] = "0.1e10"; if (valid_number(str)) cout << "true"; else cout << "false"; return 0;} // This code is contributed by rahulkumawat2107 // Java program to check if input number// is a valid numberimport java.io.*;import java.util.*; class GFG { public boolean isValidNumeric(String str) { str = str.trim(); // trims the white spaces. if (str.length() == 0) return false; // if string is of length 1 and the only // character is not a digit if (str.length() == 1 && !Character.isDigit(str.charAt(0))) return false; // If the 1st char is not '+', '-', '.' or digit if (str.charAt(0) != '+' && str.charAt(0) != '-' && !Character.isDigit(str.charAt(0)) && str.charAt(0) != '.') return false; // To check if a '.' or 'e' is found in given // string. We use this flag to make sure that // either of them appear only once. boolean flagDotOrE = false; for (int i = 1; i < str.length(); i++) { // If any of the char does not belong to // {digit, +, -, ., e} if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != 'e' && str.charAt(i) != '.' && str.charAt(i) != '+' && str.charAt(i) != '-') return false; if (str.charAt(i) == '.') { // checks if the char 'e' has already // occurred before '.' If yes, return 0. if (flagDotOrE == true) return false; // If '.' is the last character. if (i + 1 >= str.length()) return false; // if '.' is not followed by a digit. if (!Character.isDigit(str.charAt(i + 1))) return false; } else if (str.charAt(i) == 'e') { // set flagDotOrE = 1 when e is encountered. flagDotOrE = true; // if there is no digit before 'e'. if (!Character.isDigit(str.charAt(i - 1))) return false; // If 'e' is the last Character if (i + 1 >= str.length()) return false; // if e is not followed either by // '+', '-' or a digit if (!Character.isDigit(str.charAt(i + 1)) && str.charAt(i + 1) != '+' && str.charAt(i + 1) != '-') return false; } } /* If the string skips all above cases, then it is numeric*/ return true; } /* Driver Function to test isValidNumeric function */ public static void main(String[] args) { String input = "0.1e10"; GFG gfg = new GFG(); System.out.println(gfg.isValidNumeric(input)); }} [/sourcecode] # Python3 program to check if input number# is a valid numberdef valid_number(str): i = 0 j = len(str) - 1 # Handling whitespaces while i<len(str) and str[i] == ' ': i += 1 while j >= 0 and str[j] == ' ': j -= 1 if i > j: return False # if string is of length 1 and the only # character is not a digit if (i == j and not(str[i] >= '0' and str[i] <= '9')): return False # If the 1st char is not '+', '-', '.' or digit if (str[i] != '.' and str[i] != '+' and str[i] != '-' and not(str[i] >= '0' and str[i] <= '9')): return False # To check if a '.' or 'e' is found in given # string.We use this flag to make sure that # either of them appear only once. flagDotOrE = False for i in range(j + 1): # If any of the char does not belong to # {digit, +, -,., e} if (str[i] != 'e' and str[i] != '.' and str[i] != '+' and str[i] != '-' and not (str[i] >= '0' and str[i] <= '9')): return False if str[i] == '.': # check if the char e has already # occured before '.' If yes, return 0 if flagDotOrE: return False if i + 1 > len(str): return False if (not(str[i + 1] >= '0' and str[i + 1] <= '9')): return False elif str[i] == 'e': # set flagDotOrE = 1 when e is encountered. flagDotOrE = True # if there is no digit before e if (not(str[i - 1] >= '0' and str[i - 1] <= '9')): return False # if e is the last character if i + 1 > len(str): return False # if e is not followed by # '+', '-' or a digit if (str[i + 1] != '+' and str[i + 1] != '-' and (str[i + 1] >= '0' and str[i] <= '9')): return False # If the string skips all the # above cases, it must be a numeric string return True # Driver Codeif __name__ == '__main__': str = "0.1e10" if valid_number(str): print('true') else: print('false') # This code is contributed by# chaudhary_19 (Mayank Chaudhary) // C# program to check if input number// is a valid numberusing System; class GFG {public Boolean isValidNumeric(String str){str = str.Trim(); // trims the white spaces. if (str.Length == 0)return false; // if string is of length 1 and the only// character is not a digitif (str.Length == 1 && !char.IsDigit(str[0]))return false; // If the 1st char is not ‘+’, ‘-‘, ‘.’ or digitif (str[0] != ‘+’ && str[0] != ‘-‘&& !char.IsDigit(str[0]) && str[0] != ‘.’)return false; // To check if a ‘.’ or ‘e’ is found in given// string. We use this flag to make sure that// either of them appear only once.Boolean flagDotOrE = false; for (int i = 1; i < str.Length; i++) { // If any of the char does not belong to // {digit, +, -, ., e} if (!char.IsDigit(str[i]) && str[i] != 'e' && str[i] != '.' && str[i] != '+' && str[i] != '-') return false; if (str[i] == '.') { // checks if the char 'e' has already // occurred before '.' If yes, return 0. if (flagDotOrE == true) return false; // If '.' is the last character. if (i + 1 >= str.Length)return false; // if ‘.’ is not followed by a digit.if (!char.IsDigit(str[i + 1]))return false;} else if (str[i] == ‘e’) {// set flagDotOrE = 1 when e is encountered.flagDotOrE = true; // if there is no digit before ‘e’.if (!char.IsDigit(str[i – 1]))return false; // If ‘e’ is the last Characterif (i + 1 >= str.Length)return false; // if e is not followed either by// ‘+’, ‘-‘ or a digitif (!char.IsDigit(str[i + 1]) && str[i + 1] != ‘+’&& str[i + 1] != ‘-‘)return false;}} /* If the string skips all above cases,then it is numeric*/return true;} // Driver Codepublic static void Main(String[] args){String input = “0.1e10”;GFG gfg = new GFG();Console.WriteLine(gfg.isValidNumeric(input));}} // This code is contributed by Rajput-Ji true Time Complexity: O(n) This article is contributed by Saloni Baweja. 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. memcpycommand rahulkumawat2107 AdityaKakoti gp6 Rajput-Ji chaudhary_19 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find if a string is interleaved of two other strings | DP-33 Find the smallest window in a string containing all characters of another string Remove first and last character of a string in Java Convert character array to string in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Oct, 2019" }, { "code": null, "e": 93, "s": 54, "text": "Validate if a given string is numeric." }, { "code": null, "e": 103, "s": 93, "text": "Examples:" }, { "code": null, "e": 242, "s": 103, "text": "Input : str = \"11.5\"\nOutput : true\n\nInput : str = \"abc\"\nOutput : false\n\nInput : str = \"2e10\"\nOutput : true\n\nInput : 10e5.4\nOutput : false\n" }, { "code": null, "e": 294, "s": 242, "text": "The following cases need to be handled in the code." }, { "code": null, "e": 603, "s": 294, "text": "Ignore the leading and trailing white spaces.Ignore the ‘+’, ‘-‘ and’.’ at the start.Ensure that the characters in the string belong to {+, -, ., e, [0-9]}Ensure that no ‘.’ comes after ‘e’.A dot character ‘.’ should be followed by a digit.The character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit." }, { "code": null, "e": 649, "s": 603, "text": "Ignore the leading and trailing white spaces." }, { "code": null, "e": 690, "s": 649, "text": "Ignore the ‘+’, ‘-‘ and’.’ at the start." }, { "code": null, "e": 761, "s": 690, "text": "Ensure that the characters in the string belong to {+, -, ., e, [0-9]}" }, { "code": null, "e": 797, "s": 761, "text": "Ensure that no ‘.’ comes after ‘e’." }, { "code": null, "e": 848, "s": 797, "text": "A dot character ‘.’ should be followed by a digit." }, { "code": null, "e": 917, "s": 848, "text": "The character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit." }, { "code": null, "e": 957, "s": 917, "text": "Below is implementation of above steps." }, { "code": null, "e": 961, "s": 957, "text": "C++" }, { "code": null, "e": 966, "s": 961, "text": "Java" }, { "code": null, "e": 974, "s": 966, "text": "Python3" }, { "code": null, "e": 977, "s": 974, "text": "C#" }, { "code": "// C++ program to check if input number// is a valid number#include <bits/stdc++.h>#include <iostream>using namespace std; int valid_number(string str){ int i = 0, j = str.length() - 1; // Handling whitespaces while (i < str.length() && str[i] == ' ') i++; while (j >= 0 && str[j] == ' ') j--; if (i > j) return 0; // if string is of length 1 and the only // character is not a digit if (i == j && !(str[i] >= '0' && str[i] <= '9')) return 0; // If the 1st char is not '+', '-', '.' or digit if (str[i] != '.' && str[i] != '+' && str[i] != '-' && !(str[i] >= '0' && str[i] <= '9')) return 0; // To check if a '.' or 'e' is found in given // string. We use this flag to make sure that // either of them appear only once. bool flagDotOrE = false; for (i; i <= j; i++) { // If any of the char does not belong to // {digit, +, -, ., e} if (str[i] != 'e' && str[i] != '.' && str[i] != '+' && str[i] != '-' && !(str[i] >= '0' && str[i] <= '9')) return 0; if (str[i] == '.') { // checks if the char 'e' has already // occurred before '.' If yes, return 0. if (flagDotOrE == true) return 0; // If '.' is the last character. if (i + 1 > str.length()) return 0; // if '.' is not followed by a digit. if (!(str[i + 1] >= '0' && str[i + 1] <= '9')) return 0; } else if (str[i] == 'e') { // set flagDotOrE = 1 when e is encountered. flagDotOrE = true; // if there is no digit before 'e'. if (!(str[i - 1] >= '0' && str[i - 1] <= '9')) return 0; // If 'e' is the last Character if (i + 1 > str.length()) return 0; // if e is not followed either by // '+', '-' or a digit if (str[i + 1] != '+' && str[i + 1] != '-' && (str[i + 1] >= '0' && str[i] <= '9')) return 0; } } /* If the string skips all above cases, then it is numeric*/ return 1;} // Driver codeint main(){ char str[] = \"0.1e10\"; if (valid_number(str)) cout << \"true\"; else cout << \"false\"; return 0;} // This code is contributed by rahulkumawat2107", "e": 3393, "s": 977, "text": null }, { "code": "// Java program to check if input number// is a valid numberimport java.io.*;import java.util.*; class GFG { public boolean isValidNumeric(String str) { str = str.trim(); // trims the white spaces. if (str.length() == 0) return false; // if string is of length 1 and the only // character is not a digit if (str.length() == 1 && !Character.isDigit(str.charAt(0))) return false; // If the 1st char is not '+', '-', '.' or digit if (str.charAt(0) != '+' && str.charAt(0) != '-' && !Character.isDigit(str.charAt(0)) && str.charAt(0) != '.') return false; // To check if a '.' or 'e' is found in given // string. We use this flag to make sure that // either of them appear only once. boolean flagDotOrE = false; for (int i = 1; i < str.length(); i++) { // If any of the char does not belong to // {digit, +, -, ., e} if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != 'e' && str.charAt(i) != '.' && str.charAt(i) != '+' && str.charAt(i) != '-') return false; if (str.charAt(i) == '.') { // checks if the char 'e' has already // occurred before '.' If yes, return 0. if (flagDotOrE == true) return false; // If '.' is the last character. if (i + 1 >= str.length()) return false; // if '.' is not followed by a digit. if (!Character.isDigit(str.charAt(i + 1))) return false; } else if (str.charAt(i) == 'e') { // set flagDotOrE = 1 when e is encountered. flagDotOrE = true; // if there is no digit before 'e'. if (!Character.isDigit(str.charAt(i - 1))) return false; // If 'e' is the last Character if (i + 1 >= str.length()) return false; // if e is not followed either by // '+', '-' or a digit if (!Character.isDigit(str.charAt(i + 1)) && str.charAt(i + 1) != '+' && str.charAt(i + 1) != '-') return false; } } /* If the string skips all above cases, then it is numeric*/ return true; } /* Driver Function to test isValidNumeric function */ public static void main(String[] args) { String input = \"0.1e10\"; GFG gfg = new GFG(); System.out.println(gfg.isValidNumeric(input)); }}", "e": 6130, "s": 3393, "text": null }, { "code": null, "e": 6144, "s": 6130, "text": "[/sourcecode]" }, { "code": "# Python3 program to check if input number# is a valid numberdef valid_number(str): i = 0 j = len(str) - 1 # Handling whitespaces while i<len(str) and str[i] == ' ': i += 1 while j >= 0 and str[j] == ' ': j -= 1 if i > j: return False # if string is of length 1 and the only # character is not a digit if (i == j and not(str[i] >= '0' and str[i] <= '9')): return False # If the 1st char is not '+', '-', '.' or digit if (str[i] != '.' and str[i] != '+' and str[i] != '-' and not(str[i] >= '0' and str[i] <= '9')): return False # To check if a '.' or 'e' is found in given # string.We use this flag to make sure that # either of them appear only once. flagDotOrE = False for i in range(j + 1): # If any of the char does not belong to # {digit, +, -,., e} if (str[i] != 'e' and str[i] != '.' and str[i] != '+' and str[i] != '-' and not (str[i] >= '0' and str[i] <= '9')): return False if str[i] == '.': # check if the char e has already # occured before '.' If yes, return 0 if flagDotOrE: return False if i + 1 > len(str): return False if (not(str[i + 1] >= '0' and str[i + 1] <= '9')): return False elif str[i] == 'e': # set flagDotOrE = 1 when e is encountered. flagDotOrE = True # if there is no digit before e if (not(str[i - 1] >= '0' and str[i - 1] <= '9')): return False # if e is the last character if i + 1 > len(str): return False # if e is not followed by # '+', '-' or a digit if (str[i + 1] != '+' and str[i + 1] != '-' and (str[i + 1] >= '0' and str[i] <= '9')): return False # If the string skips all the # above cases, it must be a numeric string return True # Driver Codeif __name__ == '__main__': str = \"0.1e10\" if valid_number(str): print('true') else: print('false') # This code is contributed by# chaudhary_19 (Mayank Chaudhary)", "e": 8524, "s": 6144, "text": null }, { "code": null, "e": 8596, "s": 8524, "text": "// C# program to check if input number// is a valid numberusing System;" }, { "code": null, "e": 8694, "s": 8596, "text": "class GFG {public Boolean isValidNumeric(String str){str = str.Trim(); // trims the white spaces." }, { "code": null, "e": 8728, "s": 8694, "text": "if (str.Length == 0)return false;" }, { "code": null, "e": 8854, "s": 8728, "text": "// if string is of length 1 and the only// character is not a digitif (str.Length == 1 && !char.IsDigit(str[0]))return false;" }, { "code": null, "e": 8992, "s": 8854, "text": "// If the 1st char is not ‘+’, ‘-‘, ‘.’ or digitif (str[0] != ‘+’ && str[0] != ‘-‘&& !char.IsDigit(str[0]) && str[0] != ‘.’)return false;" }, { "code": null, "e": 9145, "s": 8992, "text": "// To check if a ‘.’ or ‘e’ is found in given// string. We use this flag to make sure that// either of them appear only once.Boolean flagDotOrE = false;" }, { "code": null, "e": 9566, "s": 9145, "text": "for (int i = 1; i < str.Length; i++) {\n// If any of the char does not belong to\n// {digit, +, -, ., e}\nif (!char.IsDigit(str[i]) && str[i] != 'e'\n&& str[i] != '.' && str[i] != '+'\n&& str[i] != '-')\nreturn false;\nif (str[i] == '.') {\n// checks if the char 'e' has already\n// occurred before '.' If yes, return 0.\nif (flagDotOrE == true)\nreturn false;\n// If '.' is the last character.\nif (i + 1 >= str.Length)return false;" }, { "code": null, "e": 9648, "s": 9566, "text": "// if ‘.’ is not followed by a digit.if (!char.IsDigit(str[i + 1]))return false;}" }, { "code": null, "e": 9736, "s": 9648, "text": "else if (str[i] == ‘e’) {// set flagDotOrE = 1 when e is encountered.flagDotOrE = true;" }, { "code": null, "e": 9815, "s": 9736, "text": "// if there is no digit before ‘e’.if (!char.IsDigit(str[i – 1]))return false;" }, { "code": null, "e": 9884, "s": 9815, "text": "// If ‘e’ is the last Characterif (i + 1 >= str.Length)return false;" }, { "code": null, "e": 10026, "s": 9884, "text": "// if e is not followed either by// ‘+’, ‘-‘ or a digitif (!char.IsDigit(str[i + 1]) && str[i + 1] != ‘+’&& str[i + 1] != ‘-‘)return false;}}" }, { "code": null, "e": 10099, "s": 10026, "text": "/* If the string skips all above cases,then it is numeric*/return true;}" }, { "code": null, "e": 10244, "s": 10099, "text": "// Driver Codepublic static void Main(String[] args){String input = “0.1e10”;GFG gfg = new GFG();Console.WriteLine(gfg.isValidNumeric(input));}}" }, { "code": null, "e": 10285, "s": 10244, "text": "// This code is contributed by Rajput-Ji" }, { "code": null, "e": 10291, "s": 10285, "text": "true\n" }, { "code": null, "e": 10313, "s": 10291, "text": "Time Complexity: O(n)" }, { "code": null, "e": 10614, "s": 10313, "text": "This article is contributed by Saloni Baweja. 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": 10739, "s": 10614, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 10753, "s": 10739, "text": "memcpycommand" }, { "code": null, "e": 10770, "s": 10753, "text": "rahulkumawat2107" }, { "code": null, "e": 10783, "s": 10770, "text": "AdityaKakoti" }, { "code": null, "e": 10787, "s": 10783, "text": "gp6" }, { "code": null, "e": 10797, "s": 10787, "text": "Rajput-Ji" }, { "code": null, "e": 10810, "s": 10797, "text": "chaudhary_19" }, { "code": null, "e": 10818, "s": 10810, "text": "Strings" }, { "code": null, "e": 10826, "s": 10818, "text": "Strings" }, { "code": null, "e": 10924, "s": 10826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10969, "s": 10924, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 11033, "s": 10969, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 11078, "s": 11033, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 11113, "s": 11078, "text": "Print all subsequences of a string" }, { "code": null, "e": 11178, "s": 11113, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 11207, "s": 11178, "text": "String class in Java | Set 1" }, { "code": null, "e": 11268, "s": 11207, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 11349, "s": 11268, "text": "Find the smallest window in a string containing all characters of another string" }, { "code": null, "e": 11401, "s": 11349, "text": "Remove first and last character of a string in Java" } ]
Use enumerate() and zip() together in Python
28 Nov, 2021 In this article, we will discuss how to use enumerate() and zip() functions in python. Python enumerate() is used to convert into a list of tuples using the list() method. Syntax: enumerate(iterable, start=0) Parameters: Iterable: any object that supports iteration Start: the index value from which the counter is to be started, by default it is 0 Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. Syntax: zip(*iterators) Using Both, we can iterate two/more lists/objects by using enumerate and zip functions at a time. Syntax: enumerate(zip(list1,list2,.,list n)) We can iterate this in for loop. Syntax: for var1,var2,.,var n in enumerate(zip(list1,list2,..,list n)) where, list1,list2 ,. are the input lists var1 , var2,... are the iterators to iterate the lists Example: Using enumerate() and zip() together in Python Python3 # create a list of namesnames = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh'] # create a list of subjectssubjects = ['java', 'python', 'R', 'cpp', 'bigdata'] # create a list of marksmarks = [78, 100, 97, 89, 80] # use enumerate() and zip() function# to iterate the listsfor i, (names, subjects, marks) in enumerate(zip(names, subjects, marks)): print(i, names, subjects, marks) Output: 0 sravan java 78 1 bobby python 100 2 ojaswi R 97 3 rohith cpp 89 4 gnanesh bigdata 80 We can also do this by using tuple(t) Syntax: for i, t in enumerate(zip(names, subjects,marks)) Its returns the data in the tuple format Example: Using enumerate() and zip() together in Python Python3 # create a list of namesnames = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh'] # create a list of subjectssubjects = ['java', 'python', 'R', 'cpp', 'bigdata'] # create a list of marksmarks = [78, 100, 97, 89, 80] # use enumerate() and zip() function# to iterate the lists with t functionfor i, t in enumerate(zip(names, subjects, marks)): print(i, t) Output: 0 ('sravan', 'java', 78) 1 ('bobby', 'python', 100) 2 ('ojaswi', 'R', 97) 3 ('rohith', 'cpp', 89) 4 ('gnanesh', 'bigdata', 80) we can also use t[index] in the above approach to get output Example: Using enumerate() and zip() together in Python Python3 # create a list of namesnames = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh'] # create a list of subjectssubjects = ['java', 'python', 'R', 'cpp', 'bigdata'] # create a list of marksmarks = [78, 100, 97, 89, 80] # use enumerate() and zip() function# to iterate the lists with t functionfor i, t in enumerate(zip(names, subjects, marks)): print(i, t[0], t[1], t[2]) Output: 0 sravan java 78 1 bobby python 100 2 ojaswi R 97 3 rohith cpp 89 4 gnanesh bigdata 80 Picked Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Nov, 2021" }, { "code": null, "e": 141, "s": 54, "text": "In this article, we will discuss how to use enumerate() and zip() functions in python." }, { "code": null, "e": 226, "s": 141, "text": "Python enumerate() is used to convert into a list of tuples using the list() method." }, { "code": null, "e": 234, "s": 226, "text": "Syntax:" }, { "code": null, "e": 263, "s": 234, "text": "enumerate(iterable, start=0)" }, { "code": null, "e": 275, "s": 263, "text": "Parameters:" }, { "code": null, "e": 320, "s": 275, "text": "Iterable: any object that supports iteration" }, { "code": null, "e": 404, "s": 320, "text": "Start: the index value from which the counter is to be started, by default it is 0" }, { "code": null, "e": 538, "s": 404, "text": "Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. " }, { "code": null, "e": 546, "s": 538, "text": "Syntax:" }, { "code": null, "e": 563, "s": 546, "text": "zip(*iterators) " }, { "code": null, "e": 661, "s": 563, "text": "Using Both, we can iterate two/more lists/objects by using enumerate and zip functions at a time." }, { "code": null, "e": 669, "s": 661, "text": "Syntax:" }, { "code": null, "e": 706, "s": 669, "text": "enumerate(zip(list1,list2,.,list n))" }, { "code": null, "e": 739, "s": 706, "text": "We can iterate this in for loop." }, { "code": null, "e": 747, "s": 739, "text": "Syntax:" }, { "code": null, "e": 810, "s": 747, "text": "for var1,var2,.,var n in enumerate(zip(list1,list2,..,list n))" }, { "code": null, "e": 817, "s": 810, "text": "where," }, { "code": null, "e": 852, "s": 817, "text": "list1,list2 ,. are the input lists" }, { "code": null, "e": 907, "s": 852, "text": "var1 , var2,... are the iterators to iterate the lists" }, { "code": null, "e": 963, "s": 907, "text": "Example: Using enumerate() and zip() together in Python" }, { "code": null, "e": 971, "s": 963, "text": "Python3" }, { "code": "# create a list of namesnames = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh'] # create a list of subjectssubjects = ['java', 'python', 'R', 'cpp', 'bigdata'] # create a list of marksmarks = [78, 100, 97, 89, 80] # use enumerate() and zip() function# to iterate the listsfor i, (names, subjects, marks) in enumerate(zip(names, subjects, marks)): print(i, names, subjects, marks)", "e": 1360, "s": 971, "text": null }, { "code": null, "e": 1368, "s": 1360, "text": "Output:" }, { "code": null, "e": 1455, "s": 1368, "text": "0 sravan java 78\n1 bobby python 100\n2 ojaswi R 97\n3 rohith cpp 89\n4 gnanesh bigdata 80" }, { "code": null, "e": 1493, "s": 1455, "text": "We can also do this by using tuple(t)" }, { "code": null, "e": 1501, "s": 1493, "text": "Syntax:" }, { "code": null, "e": 1551, "s": 1501, "text": "for i, t in enumerate(zip(names, subjects,marks))" }, { "code": null, "e": 1592, "s": 1551, "text": "Its returns the data in the tuple format" }, { "code": null, "e": 1648, "s": 1592, "text": "Example: Using enumerate() and zip() together in Python" }, { "code": null, "e": 1656, "s": 1648, "text": "Python3" }, { "code": "# create a list of namesnames = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh'] # create a list of subjectssubjects = ['java', 'python', 'R', 'cpp', 'bigdata'] # create a list of marksmarks = [78, 100, 97, 89, 80] # use enumerate() and zip() function# to iterate the lists with t functionfor i, t in enumerate(zip(names, subjects, marks)): print(i, t)", "e": 2017, "s": 1656, "text": null }, { "code": null, "e": 2025, "s": 2017, "text": "Output:" }, { "code": null, "e": 2152, "s": 2025, "text": "0 ('sravan', 'java', 78)\n1 ('bobby', 'python', 100)\n2 ('ojaswi', 'R', 97)\n3 ('rohith', 'cpp', 89)\n4 ('gnanesh', 'bigdata', 80)" }, { "code": null, "e": 2213, "s": 2152, "text": "we can also use t[index] in the above approach to get output" }, { "code": null, "e": 2269, "s": 2213, "text": "Example: Using enumerate() and zip() together in Python" }, { "code": null, "e": 2277, "s": 2269, "text": "Python3" }, { "code": "# create a list of namesnames = ['sravan', 'bobby', 'ojaswi', 'rohith', 'gnanesh'] # create a list of subjectssubjects = ['java', 'python', 'R', 'cpp', 'bigdata'] # create a list of marksmarks = [78, 100, 97, 89, 80] # use enumerate() and zip() function# to iterate the lists with t functionfor i, t in enumerate(zip(names, subjects, marks)): print(i, t[0], t[1], t[2])", "e": 2653, "s": 2277, "text": null }, { "code": null, "e": 2661, "s": 2653, "text": "Output:" }, { "code": null, "e": 2748, "s": 2661, "text": "0 sravan java 78\n1 bobby python 100\n2 ojaswi R 97\n3 rohith cpp 89\n4 gnanesh bigdata 80" }, { "code": null, "e": 2755, "s": 2748, "text": "Picked" }, { "code": null, "e": 2772, "s": 2755, "text": "Python-Functions" }, { "code": null, "e": 2779, "s": 2772, "text": "Python" } ]
Spirally traversing a matrix | Practice | GeeksforGeeks
Given a matrix of size r*c. Traverse the matrix in spiral form. Example 1: Input: r = 4, c = 4 matrix[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15,16}} Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Explanation: Example 2: Input: r = 3, c = 4 matrix[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} Output: 1 2 3 4 8 12 11 10 9 5 6 7 Explanation: Applying same technique as shown above, output for the 2nd testcase will be 1 2 3 4 8 12 11 10 9 5 6 7. Your Task: You dont need to read input or print anything. Complete the function spirallyTraverse() that takes matrix, r and c as input parameters and returns a list of integers denoting the spiral traversal of matrix. Expected Time Complexity: O(r*c) Expected Auxiliary Space: O(r*c), for returning the answer only. Constraints: 1 <= r, c <= 100 0 <= matrixi <= 100 0 cuongphanin 6 hours //java 9/7/22 12:26AM static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c) { ArrayList<Integer> res=new ArrayList<Integer>(); int min=Math.min(r,c); int time=(int)Math.ceil(1.0*min/2); int k=0; while(time!=k){ //top for(int t=k;t<c-k;t++){ res.add(matrix[k][t]); } //right for(int ri=k+1;ri<r-k;ri++){ res.add(matrix[ri][c-k-1]); } //bottom for(int b=c-2-k;b>=k;b--){ if(r-k-1==k) break;//same with top res.add(matrix[r-k-1][b]); } //left for(int l=r-2-k;l>k;l--){ if(c-k-1==k) break;//same with right res.add(matrix[l][k]); } k++; } return res; } 0 ntt45419117 hours ago // C++ 0.08s void outer(vector<vector<int>>& mat,int r, int c, int b, vector<int>& ans){ for(int i{b};i<c-b;i++) ans.push_back(mat[b][i]); for(int i{b+1};i<r-b;i++) ans.push_back(mat[i][c-b-1]); if(r-b-1==b) return; for(int i{c-b-2}; i>=b;i--) ans.push_back(mat[r-b-1][i]); if(b==c-b-1) return; for(int i{r-b-2}; i>b;i--) ans.push_back(mat[i][b]); } vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) { vector<int> ans; int b=0,limit=min(r,c); if(limit & 1) limit++; while(b<limit/2) outer(matrix,r,c,b++,ans); return ans; } 0 arnab_deb_211 day ago vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) { vector<int> result; int count = r*c; int i,j,k,l; int row = 0; int col = c; int m = 0; while(count>0){ for(k=row;k<col;k++){ result.push_back(matrix[row][k]); count--; } if(count==0) break; row++; for(j=row;j<=r-row;j++){ result.push_back(matrix[j][col-1]); count--; } if(count==0) break; col--; for(l=col-1;l>=row-1;l--){ result.push_back(matrix[j-1][l]); count--; } if(count==0) break; j--; l++; for(i=j-1;i>=row;i--){ result.push_back(matrix[i][l]); count--; } } return result; } 0 nitishmishra9372 days ago Java Code static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c) { // code here ArrayList<Integer> list = new ArrayList<Integer> (); int i = 0, j = 0; int maxI = r, maxJ = c; int minI = 0, minJ = 0; int count = 0, total = r*c; while(count < total) { while(j < maxJ && count < total) { list.add(matrix[i][j]); j++; ++count; } j--; maxJ--; i++; while(i < maxI && count < total) { list.add(matrix[i][j]); i++; ++count; } i--; maxI--; j--; while(j >= minJ && count < total) { list.add(matrix[i][j]); j--; ++count; } j++; minJ++; i--; while(i > minI && count < total) { list.add(matrix[i][j]); i--; ++count; } i++; minI++; j++; } return list; } 0 premkumar352 days ago // JAVA CODE class Solution{ //Function to return a list of integers denoting spiral traversal of matrix. static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c) { int nr = r; int nl = 0; int mr = c; int ml = 0; int i = 0; int j = 0; int ki = 0; int kj = 1; ArrayList<Integer> al = new ArrayList<>(); while(i<nr && i>=nl && j>=ml && j<mr) { al.add(matrix[i][j]); i=i+ki; j=j+kj; if(i == nl && j == mr) { kj = 0; ki = 1; nl++; i++; j--; } else if(i == nr && j == mr-1) { mr--; kj = -1; ki = 0; j--; i--; } else if(i == nr-1 && j == ml-1) { nr--; i--; j++; ki = -1; kj = 0; } else if (i == nl-1 && j == ml) { ki = 0; kj = 1; ml++; i++; j++; } } return al; }} 0 pandeyshrey242 days ago // HERE IS THE CODE WHICH I THINK IS MORE EXPLAINABLE // code here vector<int>ans; int cnt=0; int total= r*c; int row_start=0,row_end=r-1,col_start=0,col_end=c-1; while(cnt<total){ //for row start for(int col=col_start;col<=col_end&& cnt<total;col++){ ans.push_back(matrix[row_start][col]); cnt++; } row_start++; //for col end for(int row=row_start;row<=row_end&&cnt<total;row++){ ans.push_back(matrix[row][col_end]); cnt++; } col_end--; //for row end for(int col=col_end;col>=col_start&&cnt<total;col--){ ans.push_back(matrix[row_end][col]); cnt++; } row_end--; //for col start for(int row=row_end;row>=row_start&&cnt<total;row--){ ans.push_back(matrix[row][col_start]); cnt++; } col_start++; } return ans; 0 lovemurari20183 days ago //c++ easy solution //total time taken 0.08/1.07 vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) { // code here vector<int> ans; int cnt = 0; int total = r * c; int startingRow = 0; int startingClm = 0; int endingRow = r-1; int endingClm = c-1; while(cnt<total){ for(int index = startingClm; index <= endingClm && cnt < total; index++){ ans.push_back(matrix[startingRow][index]); cnt++; } startingRow++; for(int index = startingRow; index <= endingRow && cnt < total ; index++ ){ ans.push_back(matrix[index][endingClm]); cnt++; } endingClm--; for(int index = endingClm; index>= startingClm && cnt< total; index--){ ans.push_back(matrix[endingRow][index]); cnt++; } endingRow--; for(int index = endingRow; index>=startingRow && cnt< total ; index--){ ans.push_back(matrix[index][startingClm]); cnt++; } startingClm++; } return ans; } 0 madhavisharma21524 days ago java solution. I have added comments for better understanding.. good luck.. Note that target is the limit to which that particular column or row goes up..! int target_up=0; int target_down=arr.length-1; int target_right=arr[0].length-1; int target_left=0; int mat=r*c; int cnt=0; ArrayList<Integer> list=new ArrayList<>(); while(cnt<mat) { //top //i=target_up for(int j=target_left;j<=target_right&&cnt<mat;j++) { list.add(arr[target_up][j]); cnt++; } target_up++; //right //j=target_right for(int i=target_up;i<=target_down&&cnt<mat;i++) { list.add(arr[i][target_right]); cnt++; } target_right--; //bottom //i=target_bottom for(int j=target_right;j>=target_left&&cnt<mat;j--) { list.add(arr[target_down][j]); cnt++; } target_down--; //left //i=target_left for(int i=target_down;i>=target_up&&cnt<mat;i--) { list.add(arr[i][target_left]); cnt++; } target_left++; } return list; 0 manoranjan201019995 days ago // code here vector<int>vec; int top=0,left=0,bot=r-1,right=c-1; while(top<=bot&&left<=right) { // Top - Row for(int i=left;i<=right;i++) { vec.push_back(matrix[top][i]); } top++; // Right Col for(int i=top;i<=bot;i++) { vec.push_back(matrix[i][right]); } right--; // Bottom Row REverse Order if(top<=bot) { for(int i=right;i>=left;i--) { vec.push_back(matrix[bot][i]); } bot--; } // left Col Reverse if(left<=right) { for(int i=bot;i>=top;i--) { vec.push_back(matrix[i][left]); } left++; } } return vec; +1 hjangid005 days ago vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) { int top=0; int bottom=r-1; int left=0; int right=c-1; vector<int>v; while(1){ if(left>right)break; for(int i=left;i<=right;i++){ v.push_back(matrix[top][i]); } top++; if(top>bottom)break; for(int i=top;i<=bottom;i++){ v.push_back(matrix[i][right]); } right--; if(left>right)break; for(int i=right;i>=left;i--){ v.push_back(matrix[bottom][i]); } bottom--; if(top>bottom)break; for(int i=bottom;i>=top;i--){ v.push_back(matrix[i][left]); } left++; } return v; } 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": 302, "s": 238, "text": "Given a matrix of size r*c. Traverse the matrix in spiral form." }, { "code": null, "e": 313, "s": 302, "text": "Example 1:" }, { "code": null, "e": 504, "s": 313, "text": "Input:\nr = 4, c = 4\nmatrix[][] = {{1, 2, 3, 4},\n {5, 6, 7, 8},\n {9, 10, 11, 12},\n {13, 14, 15,16}}\nOutput: \n1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10\nExplanation:\n" }, { "code": null, "e": 515, "s": 504, "text": "Example 2:" }, { "code": null, "e": 774, "s": 515, "text": "Input:\nr = 3, c = 4 \nmatrix[][] = {{1, 2, 3, 4},\n {5, 6, 7, 8},\n {9, 10, 11, 12}}\nOutput: \n1 2 3 4 8 12 11 10 9 5 6 7\nExplanation:\nApplying same technique as shown above, \noutput for the 2nd testcase will be \n1 2 3 4 8 12 11 10 9 5 6 7.\n" }, { "code": null, "e": 1144, "s": 774, "text": "\nYour Task:\nYou dont need to read input or print anything. Complete the function spirallyTraverse() that takes matrix, r and c as input parameters and returns a list of integers denoting the spiral traversal of matrix. \n\nExpected Time Complexity: O(r*c)\nExpected Auxiliary Space: O(r*c), for returning the answer only.\n\nConstraints:\n1 <= r, c <= 100\n0 <= matrixi <= 100" }, { "code": null, "e": 1146, "s": 1144, "text": "0" }, { "code": null, "e": 1166, "s": 1146, "text": "cuongphanin 6 hours" }, { "code": null, "e": 1188, "s": 1166, "text": "//java 9/7/22 12:26AM" }, { "code": null, "e": 1970, "s": 1188, "text": "static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c) { ArrayList<Integer> res=new ArrayList<Integer>(); int min=Math.min(r,c); int time=(int)Math.ceil(1.0*min/2); int k=0; while(time!=k){ //top for(int t=k;t<c-k;t++){ res.add(matrix[k][t]); } //right for(int ri=k+1;ri<r-k;ri++){ res.add(matrix[ri][c-k-1]); } //bottom for(int b=c-2-k;b>=k;b--){ if(r-k-1==k) break;//same with top res.add(matrix[r-k-1][b]); } //left for(int l=r-2-k;l>k;l--){ if(c-k-1==k) break;//same with right res.add(matrix[l][k]); } k++; } return res; }" }, { "code": null, "e": 1972, "s": 1970, "text": "0" }, { "code": null, "e": 1994, "s": 1972, "text": "ntt45419117 hours ago" }, { "code": null, "e": 2646, "s": 1994, "text": "// C++ 0.08s\nvoid outer(vector<vector<int>>& mat,int r, int c, int b, vector<int>& ans){\n for(int i{b};i<c-b;i++) ans.push_back(mat[b][i]);\n for(int i{b+1};i<r-b;i++) ans.push_back(mat[i][c-b-1]);\n \n if(r-b-1==b) return; \n for(int i{c-b-2}; i>=b;i--) ans.push_back(mat[r-b-1][i]);\n \n if(b==c-b-1) return;\n for(int i{r-b-2}; i>b;i--) ans.push_back(mat[i][b]);\n }\n \n\n\n vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) \n {\n vector<int> ans;\n int b=0,limit=min(r,c);\n if(limit & 1) limit++;\n\n while(b<limit/2) outer(matrix,r,c,b++,ans);\n return ans;\n }" }, { "code": null, "e": 2648, "s": 2646, "text": "0" }, { "code": null, "e": 2670, "s": 2648, "text": "arnab_deb_211 day ago" }, { "code": null, "e": 3587, "s": 2670, "text": "vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) { vector<int> result; int count = r*c; int i,j,k,l; int row = 0; int col = c; int m = 0; while(count>0){ for(k=row;k<col;k++){ result.push_back(matrix[row][k]); count--; } if(count==0) break; row++; for(j=row;j<=r-row;j++){ result.push_back(matrix[j][col-1]); count--; } if(count==0) break; col--; for(l=col-1;l>=row-1;l--){ result.push_back(matrix[j-1][l]); count--; } if(count==0) break; j--; l++; for(i=j-1;i>=row;i--){ result.push_back(matrix[i][l]); count--; } } return result; }" }, { "code": null, "e": 3589, "s": 3587, "text": "0" }, { "code": null, "e": 3615, "s": 3589, "text": "nitishmishra9372 days ago" }, { "code": null, "e": 3625, "s": 3615, "text": "Java Code" }, { "code": null, "e": 4841, "s": 3627, "text": "static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c)\n {\n // code here \n ArrayList<Integer> list = new ArrayList<Integer> ();\n \n int i = 0, j = 0;\n int maxI = r, maxJ = c;\n int minI = 0, minJ = 0;\n int count = 0, total = r*c;\n while(count < total) {\n while(j < maxJ && count < total) {\n list.add(matrix[i][j]);\n j++;\n ++count;\n }\n j--;\n maxJ--;\n i++;\n \n while(i < maxI && count < total) {\n list.add(matrix[i][j]);\n i++;\n ++count;\n }\n i--;\n maxI--;\n j--;\n \n while(j >= minJ && count < total) {\n list.add(matrix[i][j]);\n j--;\n ++count;\n }\n j++;\n minJ++;\n i--;\n \n while(i > minI && count < total) {\n list.add(matrix[i][j]);\n i--;\n ++count;\n }\n i++;\n minI++;\n j++;\n }\n return list;\n }" }, { "code": null, "e": 4843, "s": 4841, "text": "0" }, { "code": null, "e": 4865, "s": 4843, "text": "premkumar352 days ago" }, { "code": null, "e": 4878, "s": 4865, "text": "// JAVA CODE" }, { "code": null, "e": 5611, "s": 4880, "text": "class Solution{ //Function to return a list of integers denoting spiral traversal of matrix. static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c) { int nr = r; int nl = 0; int mr = c; int ml = 0; int i = 0; int j = 0; int ki = 0; int kj = 1; ArrayList<Integer> al = new ArrayList<>(); while(i<nr && i>=nl && j>=ml && j<mr) { al.add(matrix[i][j]); i=i+ki; j=j+kj; if(i == nl && j == mr) { kj = 0; ki = 1; nl++; i++; j--; } else if(i == nr && j == mr-1) { mr--; kj = -1; ki = 0; j--; i--; } else if(i == nr-1 && j == ml-1) { nr--; i--; j++; ki = -1; kj = 0; } else if (i == nl-1 && j == ml) { ki = 0; kj = 1; ml++; i++; j++; } } return al; }}" }, { "code": null, "e": 5613, "s": 5611, "text": "0" }, { "code": null, "e": 5637, "s": 5613, "text": "pandeyshrey242 days ago" }, { "code": null, "e": 5692, "s": 5637, "text": "// HERE IS THE CODE WHICH I THINK IS MORE EXPLAINABLE " }, { "code": null, "e": 6715, "s": 5694, "text": " // code here vector<int>ans; int cnt=0; int total= r*c; int row_start=0,row_end=r-1,col_start=0,col_end=c-1; while(cnt<total){ //for row start for(int col=col_start;col<=col_end&& cnt<total;col++){ ans.push_back(matrix[row_start][col]); cnt++; } row_start++; //for col end for(int row=row_start;row<=row_end&&cnt<total;row++){ ans.push_back(matrix[row][col_end]); cnt++; } col_end--; //for row end for(int col=col_end;col>=col_start&&cnt<total;col--){ ans.push_back(matrix[row_end][col]); cnt++; } row_end--; //for col start for(int row=row_end;row>=row_start&&cnt<total;row--){ ans.push_back(matrix[row][col_start]); cnt++; } col_start++; } return ans;" }, { "code": null, "e": 6717, "s": 6715, "text": "0" }, { "code": null, "e": 6742, "s": 6717, "text": "lovemurari20183 days ago" }, { "code": null, "e": 6762, "s": 6742, "text": "//c++ easy solution" }, { "code": null, "e": 6792, "s": 6762, "text": "//total time taken 0.08/1.07" }, { "code": null, "e": 7962, "s": 6792, "text": " vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) { // code here vector<int> ans; int cnt = 0; int total = r * c; int startingRow = 0; int startingClm = 0; int endingRow = r-1; int endingClm = c-1; while(cnt<total){ for(int index = startingClm; index <= endingClm && cnt < total; index++){ ans.push_back(matrix[startingRow][index]); cnt++; } startingRow++; for(int index = startingRow; index <= endingRow && cnt < total ; index++ ){ ans.push_back(matrix[index][endingClm]); cnt++; } endingClm--; for(int index = endingClm; index>= startingClm && cnt< total; index--){ ans.push_back(matrix[endingRow][index]); cnt++; } endingRow--; for(int index = endingRow; index>=startingRow && cnt< total ; index--){ ans.push_back(matrix[index][startingClm]); cnt++; } startingClm++; } return ans; }" }, { "code": null, "e": 7964, "s": 7962, "text": "0" }, { "code": null, "e": 7992, "s": 7964, "text": "madhavisharma21524 days ago" }, { "code": null, "e": 8149, "s": 7992, "text": "java solution. I have added comments for better understanding.. good luck.. Note that target is the limit to which that particular column or row goes up..!" }, { "code": null, "e": 9325, "s": 8151, "text": " int target_up=0; int target_down=arr.length-1; int target_right=arr[0].length-1; int target_left=0; int mat=r*c; int cnt=0; ArrayList<Integer> list=new ArrayList<>(); while(cnt<mat) { //top //i=target_up for(int j=target_left;j<=target_right&&cnt<mat;j++) { list.add(arr[target_up][j]); cnt++; } target_up++; //right //j=target_right for(int i=target_up;i<=target_down&&cnt<mat;i++) { list.add(arr[i][target_right]); cnt++; } target_right--; //bottom //i=target_bottom for(int j=target_right;j>=target_left&&cnt<mat;j--) { list.add(arr[target_down][j]); cnt++; } target_down--; //left //i=target_left for(int i=target_down;i>=target_up&&cnt<mat;i--) { list.add(arr[i][target_left]); cnt++; } target_left++; } return list;" }, { "code": null, "e": 9327, "s": 9325, "text": "0" }, { "code": null, "e": 9356, "s": 9327, "text": "manoranjan201019995 days ago" }, { "code": null, "e": 10310, "s": 9356, "text": "// code here vector<int>vec; int top=0,left=0,bot=r-1,right=c-1; while(top<=bot&&left<=right) { // Top - Row for(int i=left;i<=right;i++) { vec.push_back(matrix[top][i]); } top++; // Right Col for(int i=top;i<=bot;i++) { vec.push_back(matrix[i][right]); } right--; // Bottom Row REverse Order if(top<=bot) { for(int i=right;i>=left;i--) { vec.push_back(matrix[bot][i]); } bot--; } // left Col Reverse if(left<=right) { for(int i=bot;i>=top;i--) { vec.push_back(matrix[i][left]); } left++; } } return vec;" }, { "code": null, "e": 10313, "s": 10310, "text": "+1" }, { "code": null, "e": 10333, "s": 10313, "text": "hjangid005 days ago" }, { "code": null, "e": 11136, "s": 10333, "text": "vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) { int top=0; int bottom=r-1; int left=0; int right=c-1; vector<int>v; while(1){ if(left>right)break; for(int i=left;i<=right;i++){ v.push_back(matrix[top][i]); } top++; if(top>bottom)break; for(int i=top;i<=bottom;i++){ v.push_back(matrix[i][right]); } right--; if(left>right)break; for(int i=right;i>=left;i--){ v.push_back(matrix[bottom][i]); } bottom--; if(top>bottom)break; for(int i=bottom;i>=top;i--){ v.push_back(matrix[i][left]); } left++; } return v; }" }, { "code": null, "e": 11282, "s": 11136, "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": 11318, "s": 11282, "text": " Login to access your submissions. " }, { "code": null, "e": 11328, "s": 11318, "text": "\nProblem\n" }, { "code": null, "e": 11338, "s": 11328, "text": "\nContest\n" }, { "code": null, "e": 11401, "s": 11338, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11586, "s": 11401, "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": 11870, "s": 11586, "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": 12016, "s": 11870, "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": 12093, "s": 12016, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 12134, "s": 12093, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 12162, "s": 12134, "text": "Disable browser extensions." }, { "code": null, "e": 12233, "s": 12162, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 12420, "s": 12233, "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." } ]
Python Pandas – Display all the column names in a DataFrame
To display only the column names in a DataFrame, use dataframe.columns. Import the required library with an alias − import pandas as pd; Following is the DataFrame − dataFrame = pd.DataFrame( { "Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],"Place": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],"Units": [100, 150, 50, 110, 90, 120, 80] } ) Display the column names with dataframe.columns. Following is the complete code − import pandas as pd; # create a DataFrame dataFrame = pd.DataFrame( { "Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],"Place": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],"Units": [100, 150, 50, 110, 90, 120, 80] } ) print"DataFrame ...\n",dataFrame # get all the column names print"\n Display all the column names ...\n",dataFrame.columns This will produce the following output − DataFrame ... Car Place Units 0 BMW Delhi 100 1 Audi Bangalore 150 2 BMW Hyderabad 50 3 Lexus Chandigarh 110 4 Tesla Pune 90 5 Lexus Mumbai 120 6 Mustang Jaipur 80 Display all the column names ... Index([u'Car', u'Place', u'Units'], dtype='object')
[ { "code": null, "e": 1259, "s": 1187, "text": "To display only the column names in a DataFrame, use dataframe.columns." }, { "code": null, "e": 1303, "s": 1259, "text": "Import the required library with an alias −" }, { "code": null, "e": 1324, "s": 1303, "text": "import pandas as pd;" }, { "code": null, "e": 1353, "s": 1324, "text": "Following is the DataFrame −" }, { "code": null, "e": 1590, "s": 1353, "text": "dataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],\"Place\": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],\"Units\": [100, 150, 50, 110, 90, 120, 80]\n }\n)" }, { "code": null, "e": 1672, "s": 1590, "text": "Display the column names with dataframe.columns. Following is the complete code −" }, { "code": null, "e": 2077, "s": 1672, "text": "import pandas as pd;\n\n# create a DataFrame\ndataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],\"Place\": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],\"Units\": [100, 150, 50, 110, 90, 120, 80]\n }\n)\n\nprint\"DataFrame ...\\n\",dataFrame\n\n# get all the column names\nprint\"\\n Display all the column names ...\\n\",dataFrame.columns" }, { "code": null, "e": 2118, "s": 2077, "text": "This will produce the following output −" }, { "code": null, "e": 2459, "s": 2118, "text": "DataFrame ...\n Car Place Units\n0 BMW Delhi 100\n1 Audi Bangalore 150\n2 BMW Hyderabad 50\n3 Lexus Chandigarh 110\n4 Tesla Pune 90\n5 Lexus Mumbai 120\n6 Mustang Jaipur 80\n\nDisplay all the column names ...\nIndex([u'Car', u'Place', u'Units'], dtype='object')" } ]
POST method – Python requests
22 Sep, 2021 Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make POST request to a specified URL using requests.post() method. Before checking out the POST method, let’s figure out what a POST request is – POST is a request method supported by HTTP used by the World Wide Web. By design, the POST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form. Python’s requests module provides in-built method called post() for making a POST request to a specified URI.Syntax – requests.post(url, params={key: value}, args) Example – Let’s try making a request to httpbin’s APIs for example purposes. Python3 import requests # Making a POST requestr = requests.post('https://httpbin.org / post', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.json()) save this file as request.py and through terminal run, python request.py Output – It is more secure than GET because user-entered information is never visible in the URL query string or in the server logs. There is a much larger limit on the amount of data that can be passed and one can send text data as well as binary data (uploading a file) using POST. Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark the page with specific query. POST requests are never cached POST requests do not remain in the browser history. sooda367 Python-requests Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 321, "s": 28, "text": "Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make POST request to a specified URL using requests.post() method. Before checking out the POST method, let’s figure out what a POST request is – " }, { "code": null, "e": 626, "s": 321, "text": "POST is a request method supported by HTTP used by the World Wide Web. By design, the POST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form. " }, { "code": null, "e": 745, "s": 626, "text": "Python’s requests module provides in-built method called post() for making a POST request to a specified URI.Syntax – " }, { "code": null, "e": 791, "s": 745, "text": "requests.post(url, params={key: value}, args)" }, { "code": null, "e": 870, "s": 791, "text": "Example – Let’s try making a request to httpbin’s APIs for example purposes. " }, { "code": null, "e": 878, "s": 870, "text": "Python3" }, { "code": "import requests # Making a POST requestr = requests.post('https://httpbin.org / post', data ={'key':'value'}) # check status code for response received# success code - 200print(r) # print content of requestprint(r.json())", "e": 1100, "s": 878, "text": null }, { "code": null, "e": 1157, "s": 1100, "text": "save this file as request.py and through terminal run, " }, { "code": null, "e": 1175, "s": 1157, "text": "python request.py" }, { "code": null, "e": 1184, "s": 1175, "text": "Output –" }, { "code": null, "e": 1310, "s": 1186, "text": "It is more secure than GET because user-entered information is never visible in the URL query string or in the server logs." }, { "code": null, "e": 1462, "s": 1310, "text": "There is a much larger limit on the amount of data that can be passed and one can send text data as well as binary data (uploading a file) using POST. " }, { "code": null, "e": 1592, "s": 1462, "text": "Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark the page with specific query." }, { "code": null, "e": 1623, "s": 1592, "text": "POST requests are never cached" }, { "code": null, "e": 1675, "s": 1623, "text": "POST requests do not remain in the browser history." }, { "code": null, "e": 1684, "s": 1675, "text": "sooda367" }, { "code": null, "e": 1700, "s": 1684, "text": "Python-requests" }, { "code": null, "e": 1707, "s": 1700, "text": "Python" }, { "code": null, "e": 1805, "s": 1707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1847, "s": 1805, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1869, "s": 1847, "text": "Enumerate() in Python" }, { "code": null, "e": 1895, "s": 1869, "text": "Python String | replace()" }, { "code": null, "e": 1927, "s": 1895, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1956, "s": 1927, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1983, "s": 1956, "text": "Python Classes and Objects" }, { "code": null, "e": 2019, "s": 1983, "text": "Convert integer to string in Python" }, { "code": null, "e": 2040, "s": 2019, "text": "Python OOPs Concepts" }, { "code": null, "e": 2071, "s": 2040, "text": "Python | os.path.join() method" } ]
Mounting a Volume Inside Docker Container
31 Oct, 2020 When you are working on a micro-service architecture using Docker Containers, you create multiple Docker Containers to create and test different components of your application. Now, some of those components might require sharing files and directories. If you copy the same files in all the Containers separately, it might lead to an unnecessary increase in the Image size, and also, changing a file in one Container will not create the corresponding change in the same file in other Containers. Hence, you required a shared directory or volume that you can mount on multiple Docker Containers and all of them have shared access to a particular file or directory. Docker allows you to mount shared volumes in multiple Containers. In this article, we will mount a volume to different Containers and check whether the changes in the file is shared among all the Containers or not. Follow the below steps to mount a volume inside Docker Container: To display all the existing Docker Volumes, you can use the list command as follows. sudo docker volume ls Volume List To create a new Docker Volume, you can use the Volume Create Command. sudo docker volume create geeksforgeeks Volume Create To get the details of the Volumes you have created you can, you can use the Volume Inspect Command. sudo docker volume inspect geeksforgeeks Volume Inspect After creating the Volume, the next step is to mount the Volume to Docker Containers. We will create a Docker Container with the Ubuntu base Image and mount the geeksforgeeks Volume to that Container using the -v flag. sudo docker run -it -v geeksforgeeks:/shared-volume --name my-container-01 ubuntu The above command mounts the geeksforgeeks volume to a directory called shared-volume inside the Docker Container named my-container-01. Mounting Docker Volumes Inside the bash of the Container, create a new file and add some content. ls cd /shared-volume echo “GeeksforGeeks” > geeksforgeeks.txt ls exit Creating a file Create another Docker Container called my-container-02 and mount the same Docker Volume called geeksforgeeks inside the Container. sudo docker run -it -v geeksforgeeks:/shared-volume --name my-container-02 ubuntu Verifying Shared Contents If you go to the shared-volume directory and list the files, you will find the geeksforgeeks.txt file that you had created in the same volume but mounted in my-container-01 earlier and it also has the same content inside it. This is so because, the volume is shared among the two Containers. To conclude, in this article we discussed how to create and inspect a Volume and mount it to multiple Docker Containers. This proves to be very helpful when you want shared access to files and directories among multiple Docker Containers. Docker Container linux Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Fuzzy Logic | Introduction Game Playing in Artificial Intelligence Artificial Intelligence - Temporal Logic Difference between Backward and Forward Chaining. Markov Decision Process Getting Started with System Design Basics of API Testing Using Postman Web Mining Python | Implementation of Polynomial Regression ML | What is Machine Learning ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2020" }, { "code": null, "e": 523, "s": 28, "text": "When you are working on a micro-service architecture using Docker Containers, you create multiple Docker Containers to create and test different components of your application. Now, some of those components might require sharing files and directories. If you copy the same files in all the Containers separately, it might lead to an unnecessary increase in the Image size, and also, changing a file in one Container will not create the corresponding change in the same file in other Containers." }, { "code": null, "e": 972, "s": 523, "text": "Hence, you required a shared directory or volume that you can mount on multiple Docker Containers and all of them have shared access to a particular file or directory. Docker allows you to mount shared volumes in multiple Containers. In this article, we will mount a volume to different Containers and check whether the changes in the file is shared among all the Containers or not. Follow the below steps to mount a volume inside Docker Container:" }, { "code": null, "e": 1057, "s": 972, "text": "To display all the existing Docker Volumes, you can use the list command as follows." }, { "code": null, "e": 1081, "s": 1057, "text": "sudo docker volume ls \n" }, { "code": null, "e": 1093, "s": 1081, "text": "Volume List" }, { "code": null, "e": 1163, "s": 1093, "text": "To create a new Docker Volume, you can use the Volume Create Command." }, { "code": null, "e": 1204, "s": 1163, "text": "sudo docker volume create geeksforgeeks\n" }, { "code": null, "e": 1218, "s": 1204, "text": "Volume Create" }, { "code": null, "e": 1318, "s": 1218, "text": "To get the details of the Volumes you have created you can, you can use the Volume Inspect Command." }, { "code": null, "e": 1360, "s": 1318, "text": "sudo docker volume inspect geeksforgeeks\n" }, { "code": null, "e": 1375, "s": 1360, "text": "Volume Inspect" }, { "code": null, "e": 1594, "s": 1375, "text": "After creating the Volume, the next step is to mount the Volume to Docker Containers. We will create a Docker Container with the Ubuntu base Image and mount the geeksforgeeks Volume to that Container using the -v flag." }, { "code": null, "e": 1677, "s": 1594, "text": "sudo docker run -it -v geeksforgeeks:/shared-volume --name my-container-01 ubuntu\n" }, { "code": null, "e": 1814, "s": 1677, "text": "The above command mounts the geeksforgeeks volume to a directory called shared-volume inside the Docker Container named my-container-01." }, { "code": null, "e": 1838, "s": 1814, "text": "Mounting Docker Volumes" }, { "code": null, "e": 1913, "s": 1838, "text": " Inside the bash of the Container, create a new file and add some content." }, { "code": null, "e": 1984, "s": 1913, "text": "ls\ncd /shared-volume\necho “GeeksforGeeks” > geeksforgeeks.txt\nls\nexit\n" }, { "code": null, "e": 2000, "s": 1984, "text": "Creating a file" }, { "code": null, "e": 2131, "s": 2000, "text": "Create another Docker Container called my-container-02 and mount the same Docker Volume called geeksforgeeks inside the Container." }, { "code": null, "e": 2214, "s": 2131, "text": "sudo docker run -it -v geeksforgeeks:/shared-volume --name my-container-02 ubuntu\n" }, { "code": null, "e": 2240, "s": 2214, "text": "Verifying Shared Contents" }, { "code": null, "e": 2532, "s": 2240, "text": "If you go to the shared-volume directory and list the files, you will find the geeksforgeeks.txt file that you had created in the same volume but mounted in my-container-01 earlier and it also has the same content inside it. This is so because, the volume is shared among the two Containers." }, { "code": null, "e": 2771, "s": 2532, "text": "To conclude, in this article we discussed how to create and inspect a Volume and mount it to multiple Docker Containers. This proves to be very helpful when you want shared access to files and directories among multiple Docker Containers." }, { "code": null, "e": 2788, "s": 2771, "text": "Docker Container" }, { "code": null, "e": 2794, "s": 2788, "text": "linux" }, { "code": null, "e": 2820, "s": 2794, "text": "Advanced Computer Subject" }, { "code": null, "e": 2918, "s": 2820, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2945, "s": 2918, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 2985, "s": 2945, "text": "Game Playing in Artificial Intelligence" }, { "code": null, "e": 3026, "s": 2985, "text": "Artificial Intelligence - Temporal Logic" }, { "code": null, "e": 3076, "s": 3026, "text": "Difference between Backward and Forward Chaining." }, { "code": null, "e": 3100, "s": 3076, "text": "Markov Decision Process" }, { "code": null, "e": 3135, "s": 3100, "text": "Getting Started with System Design" }, { "code": null, "e": 3171, "s": 3135, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 3182, "s": 3171, "text": "Web Mining" }, { "code": null, "e": 3231, "s": 3182, "text": "Python | Implementation of Polynomial Regression" } ]
Hospital Management System in C++
18 Jan, 2021 In this article, a C++ program is discussed to manage the Hospital Management System. Given data of Hospitals with the name of hospital, contact and doctors and patients below are the functionalities that needed to be implemented: Functions Supported: Print Hospital DATA Print Patients data SORT BY Beds Price SORT BY Available Beds SORT BY NAME SORT BY Rating and reviews Print hospital of any specific city The important functions in the program: PrintHospitalData() : It will print all the hospitals data. PrintPatientData() : It will print all the hospitals data.SortHospitalByName(): Sort all the hospitals from nameSortHospitalByRating(): Sort hospitals according to ratingSortByBedsAvailable() : Sort hospitals according to beds availableSortByBedsPrice(): Sort hospitals according to the minimum price. PrintHospitalData() : It will print all the hospitals data. PrintPatientData() : It will print all the hospitals data. SortHospitalByName(): Sort all the hospitals from name SortHospitalByRating(): Sort hospitals according to rating SortByBedsAvailable() : Sort hospitals according to beds available SortByBedsPrice(): Sort hospitals according to the minimum price. Approach: Create classes for both the Hospital dataset and Patient data. Initialize variables that store Hospital dataset and Patient data. Create Objects for hospitals and Patient classes that access the Hospital dataset and Patient data. use two arrays that hold the Hospital dataset and Patient data. Implement the given functionality as shown below. Below is the implementation of the above approach. C++ // C++ program to implement the Hospital// Management System#include <bits/stdc++.h>using namespace std; // Store the data of Hospitalclass Hospital {public: string H_name; string location; int available_beds; float rating; string contact; string doctor_name; int price;}; // Stores the data of Patientclass Patient : public Hospital {public: string P_name; int P_id;}; // Hospital Datavoid PrintHospitalData( vector<Hospital>& hospitals){ cout << "PRINT hospitals DATA:" << endl; cout << "HospitalName " << "Location " << "Beds_Available " << "Rating " << "Hospital_Contact " << "Doctor_Name " << "Price_Per_Bed \n"; for (int i = 0; i < 4; i++) { cout << hospitals[i].H_name << " " << " " << hospitals[i].location << " " << hospitals[i].available_beds << " " << hospitals[i].rating << " " << hospitals[i].contact << " " << hospitals[i].doctor_name << " " << " " << hospitals[i].price << " " << endl; } cout << endl << endl;} // Function to print the patient// data in the hospitalvoid PrintPatientData( vector<Patient>& patients, vector<Hospital>& hospitals){ cout << "PRINT patients DATA:" << endl; cout << "Patient_Name " << "Patient_Id " << "Patient_Contact " << "Alloted_Hospital " << "Patient_Expenditure \n"; for (int i = 0; i < 4; i++) { cout << patients[i].P_name << " " << " " << patients[i].P_id << " " << " " << patients[i].contact << " " << hospitals[i].H_name << " " << patients[i].price << " " << endl; } cout << endl << endl;} // Comparator function to sort the// hospital data by namebool name(Hospital& A, Hospital& B){ return A.H_name > B.H_name;} // Function to sort the hospital// data by namevoid SortHospitalByName( vector<Hospital> hospitals){ // Sort the date sort(hospitals.begin(), hospitals.end(), name); cout << "SORT BY NAME:" << endl << endl; PrintHospitalData(hospitals);} // Comparator function to sort the// hospital data by ratingbool rating(Hospital& A, Hospital& B){ return A.rating > B.rating;} // Function to sort the hospital// data by nameratingvoid SortHospitalByRating(vector<Hospital> hospitals){ sort(hospitals.begin(), hospitals.end(), rating); cout << "SORT BY Rating:" << endl << endl; PrintHospitalData(hospitals);} // Comparator function to sort the// hospital data by Bed Availablebool beds(Hospital& A, Hospital& B){ return A.available_beds > B.available_beds;} // Function to sort the hospital// data by Bed Availablevoid SortByBedsAvailable( vector<Hospital> hospitals){ sort(hospitals.begin(), hospitals.end(), beds); cout << "SORT BY Available Beds:" << endl << endl; PrintHospitalData(hospitals);} // Comparator function to sort the// hospital data by Bed Pricebool beds_price(Hospital& A, Hospital& B){ return A.price < B.price;} // Function to sort the hospital// data by Bed Pricevoid SortByBedsPrice( vector<Hospital> hospitals){ sort(hospitals.begin(), hospitals.end(), beds_price); cout << "SORT BY Available Beds Price:" << endl << endl; PrintHospitalData(hospitals);} // Comparator function to sort the// hospital data by Cityvoid PrintHospitalBycity( string city, vector<Hospital> hospitals){ cout << "PRINT hospitals by Name :" << city << endl; cout << "HospitalName " << "Location " << "Beds_Available " << "Rating " << "Hospital_Contact " << "Doctor_Name " << "Price_Per_Bed \n"; for (int i = 0; i < 4; i++) { if (hospitals[i].location != city) continue; cout << hospitals[i].H_name << " " << " " << hospitals[i].location << " " << hospitals[i].available_beds << " " << hospitals[i].rating << " " << hospitals[i].contact << " " << hospitals[i].doctor_name << " " << " " << hospitals[i].price << " " << endl; } cout << endl << endl;} // Function to implement Hospital// Management Systemvoid HospitalManagement( string patient_Name[], int patient_Id[], string patient_Contact[], int bookingCost[], string hospital_Name[], string locations[], int beds[], float ratings[], string hospital_Contact[], string doctor_Name[], int prices[]){ // Stores the Hospital data // and user data vector<Hospital> hospitals; // Create Objects for hospital // and the users Hospital h; // Initialize the data for (int i = 0; i < 4; i++) { h.H_name = hospital_Name[i]; h.location = locations[i]; h.available_beds = beds[i]; h.rating = ratings[i]; h.contact = hospital_Contact[i]; h.doctor_name = doctor_Name[i]; h.price = prices[i]; hospitals.push_back(h); } // Stores the patient data vector<Patient> patients; Patient p; // Initialize the data for (int i = 0; i < 4; i++) { p.P_name = patient_Name[i]; p.P_id = patient_Id[i]; p.contact = patient_Contact[i]; p.price = bookingCost[i]; patients.push_back(p); } cout << endl; // Call the various operations PrintHospitalData(hospitals); PrintPatientData(patients, hospitals); SortHospitalByName(hospitals); SortHospitalByRating(hospitals); PrintHospitalBycity("Bangalore", hospitals); SortByBedsAvailable(hospitals); SortByBedsPrice(hospitals);} // Driver Codeint main(){ // Stores hospital data and // the user data string patient_Name[] = { "P1", "P2", "P3", "P4" }; int patient_Id[] = { 2, 3, 4, 1 }; string patient_Contact[] = { "234534XXX7", "234576XXX2", "857465XXX9", "567657XXX0" }; int bookingCost[] = { 1000, 1200, 1100, 600 }; string hospital_Name[] = { "H1", "H2", "H4", "H3" }; string locations[] = { "Bangalore", "Bangalore", "Mumbai ", "Prayagraj" }; int beds[] = { 4, 5, 6, 9 }; float ratings[] = { 5.2, 4.1, 3.4, 5.9 }; string hospital_Contact[] = { "657534XXX7", "298766XXX2", "324565XXX9", "343456XXX4" }; string doctor_Name[] = { "D1", "D4", "D3", "D2" }; int prices[] = { 100, 200, 100, 290 }; // Function Call HospitalManagement( patient_Name, patient_Id, patient_Contact, bookingCost, hospital_Name, locations, beds, ratings, hospital_Contact, doctor_Name, prices); return 0;} Output: Technical Scripter 2020 C++ C++ Programs Project Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ std::string class in C++ Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Jan, 2021" }, { "code": null, "e": 283, "s": 52, "text": "In this article, a C++ program is discussed to manage the Hospital Management System. Given data of Hospitals with the name of hospital, contact and doctors and patients below are the functionalities that needed to be implemented:" }, { "code": null, "e": 304, "s": 283, "text": "Functions Supported:" }, { "code": null, "e": 324, "s": 304, "text": "Print Hospital DATA" }, { "code": null, "e": 344, "s": 324, "text": "Print Patients data" }, { "code": null, "e": 363, "s": 344, "text": "SORT BY Beds Price" }, { "code": null, "e": 386, "s": 363, "text": "SORT BY Available Beds" }, { "code": null, "e": 399, "s": 386, "text": "SORT BY NAME" }, { "code": null, "e": 426, "s": 399, "text": "SORT BY Rating and reviews" }, { "code": null, "e": 462, "s": 426, "text": "Print hospital of any specific city" }, { "code": null, "e": 502, "s": 462, "text": "The important functions in the program:" }, { "code": null, "e": 865, "s": 502, "text": " PrintHospitalData() : It will print all the hospitals data. PrintPatientData() : It will print all the hospitals data.SortHospitalByName(): Sort all the hospitals from nameSortHospitalByRating(): Sort hospitals according to ratingSortByBedsAvailable() : Sort hospitals according to beds availableSortByBedsPrice(): Sort hospitals according to the minimum price." }, { "code": null, "e": 926, "s": 865, "text": " PrintHospitalData() : It will print all the hospitals data." }, { "code": null, "e": 986, "s": 926, "text": " PrintPatientData() : It will print all the hospitals data." }, { "code": null, "e": 1041, "s": 986, "text": "SortHospitalByName(): Sort all the hospitals from name" }, { "code": null, "e": 1100, "s": 1041, "text": "SortHospitalByRating(): Sort hospitals according to rating" }, { "code": null, "e": 1167, "s": 1100, "text": "SortByBedsAvailable() : Sort hospitals according to beds available" }, { "code": null, "e": 1233, "s": 1167, "text": "SortByBedsPrice(): Sort hospitals according to the minimum price." }, { "code": null, "e": 1243, "s": 1233, "text": "Approach:" }, { "code": null, "e": 1306, "s": 1243, "text": "Create classes for both the Hospital dataset and Patient data." }, { "code": null, "e": 1373, "s": 1306, "text": "Initialize variables that store Hospital dataset and Patient data." }, { "code": null, "e": 1473, "s": 1373, "text": "Create Objects for hospitals and Patient classes that access the Hospital dataset and Patient data." }, { "code": null, "e": 1537, "s": 1473, "text": "use two arrays that hold the Hospital dataset and Patient data." }, { "code": null, "e": 1587, "s": 1537, "text": "Implement the given functionality as shown below." }, { "code": null, "e": 1638, "s": 1587, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1642, "s": 1638, "text": "C++" }, { "code": "// C++ program to implement the Hospital// Management System#include <bits/stdc++.h>using namespace std; // Store the data of Hospitalclass Hospital {public: string H_name; string location; int available_beds; float rating; string contact; string doctor_name; int price;}; // Stores the data of Patientclass Patient : public Hospital {public: string P_name; int P_id;}; // Hospital Datavoid PrintHospitalData( vector<Hospital>& hospitals){ cout << \"PRINT hospitals DATA:\" << endl; cout << \"HospitalName \" << \"Location \" << \"Beds_Available \" << \"Rating \" << \"Hospital_Contact \" << \"Doctor_Name \" << \"Price_Per_Bed \\n\"; for (int i = 0; i < 4; i++) { cout << hospitals[i].H_name << \" \" << \" \" << hospitals[i].location << \" \" << hospitals[i].available_beds << \" \" << hospitals[i].rating << \" \" << hospitals[i].contact << \" \" << hospitals[i].doctor_name << \" \" << \" \" << hospitals[i].price << \" \" << endl; } cout << endl << endl;} // Function to print the patient// data in the hospitalvoid PrintPatientData( vector<Patient>& patients, vector<Hospital>& hospitals){ cout << \"PRINT patients DATA:\" << endl; cout << \"Patient_Name \" << \"Patient_Id \" << \"Patient_Contact \" << \"Alloted_Hospital \" << \"Patient_Expenditure \\n\"; for (int i = 0; i < 4; i++) { cout << patients[i].P_name << \" \" << \" \" << patients[i].P_id << \" \" << \" \" << patients[i].contact << \" \" << hospitals[i].H_name << \" \" << patients[i].price << \" \" << endl; } cout << endl << endl;} // Comparator function to sort the// hospital data by namebool name(Hospital& A, Hospital& B){ return A.H_name > B.H_name;} // Function to sort the hospital// data by namevoid SortHospitalByName( vector<Hospital> hospitals){ // Sort the date sort(hospitals.begin(), hospitals.end(), name); cout << \"SORT BY NAME:\" << endl << endl; PrintHospitalData(hospitals);} // Comparator function to sort the// hospital data by ratingbool rating(Hospital& A, Hospital& B){ return A.rating > B.rating;} // Function to sort the hospital// data by nameratingvoid SortHospitalByRating(vector<Hospital> hospitals){ sort(hospitals.begin(), hospitals.end(), rating); cout << \"SORT BY Rating:\" << endl << endl; PrintHospitalData(hospitals);} // Comparator function to sort the// hospital data by Bed Availablebool beds(Hospital& A, Hospital& B){ return A.available_beds > B.available_beds;} // Function to sort the hospital// data by Bed Availablevoid SortByBedsAvailable( vector<Hospital> hospitals){ sort(hospitals.begin(), hospitals.end(), beds); cout << \"SORT BY Available Beds:\" << endl << endl; PrintHospitalData(hospitals);} // Comparator function to sort the// hospital data by Bed Pricebool beds_price(Hospital& A, Hospital& B){ return A.price < B.price;} // Function to sort the hospital// data by Bed Pricevoid SortByBedsPrice( vector<Hospital> hospitals){ sort(hospitals.begin(), hospitals.end(), beds_price); cout << \"SORT BY Available Beds Price:\" << endl << endl; PrintHospitalData(hospitals);} // Comparator function to sort the// hospital data by Cityvoid PrintHospitalBycity( string city, vector<Hospital> hospitals){ cout << \"PRINT hospitals by Name :\" << city << endl; cout << \"HospitalName \" << \"Location \" << \"Beds_Available \" << \"Rating \" << \"Hospital_Contact \" << \"Doctor_Name \" << \"Price_Per_Bed \\n\"; for (int i = 0; i < 4; i++) { if (hospitals[i].location != city) continue; cout << hospitals[i].H_name << \" \" << \" \" << hospitals[i].location << \" \" << hospitals[i].available_beds << \" \" << hospitals[i].rating << \" \" << hospitals[i].contact << \" \" << hospitals[i].doctor_name << \" \" << \" \" << hospitals[i].price << \" \" << endl; } cout << endl << endl;} // Function to implement Hospital// Management Systemvoid HospitalManagement( string patient_Name[], int patient_Id[], string patient_Contact[], int bookingCost[], string hospital_Name[], string locations[], int beds[], float ratings[], string hospital_Contact[], string doctor_Name[], int prices[]){ // Stores the Hospital data // and user data vector<Hospital> hospitals; // Create Objects for hospital // and the users Hospital h; // Initialize the data for (int i = 0; i < 4; i++) { h.H_name = hospital_Name[i]; h.location = locations[i]; h.available_beds = beds[i]; h.rating = ratings[i]; h.contact = hospital_Contact[i]; h.doctor_name = doctor_Name[i]; h.price = prices[i]; hospitals.push_back(h); } // Stores the patient data vector<Patient> patients; Patient p; // Initialize the data for (int i = 0; i < 4; i++) { p.P_name = patient_Name[i]; p.P_id = patient_Id[i]; p.contact = patient_Contact[i]; p.price = bookingCost[i]; patients.push_back(p); } cout << endl; // Call the various operations PrintHospitalData(hospitals); PrintPatientData(patients, hospitals); SortHospitalByName(hospitals); SortHospitalByRating(hospitals); PrintHospitalBycity(\"Bangalore\", hospitals); SortByBedsAvailable(hospitals); SortByBedsPrice(hospitals);} // Driver Codeint main(){ // Stores hospital data and // the user data string patient_Name[] = { \"P1\", \"P2\", \"P3\", \"P4\" }; int patient_Id[] = { 2, 3, 4, 1 }; string patient_Contact[] = { \"234534XXX7\", \"234576XXX2\", \"857465XXX9\", \"567657XXX0\" }; int bookingCost[] = { 1000, 1200, 1100, 600 }; string hospital_Name[] = { \"H1\", \"H2\", \"H4\", \"H3\" }; string locations[] = { \"Bangalore\", \"Bangalore\", \"Mumbai \", \"Prayagraj\" }; int beds[] = { 4, 5, 6, 9 }; float ratings[] = { 5.2, 4.1, 3.4, 5.9 }; string hospital_Contact[] = { \"657534XXX7\", \"298766XXX2\", \"324565XXX9\", \"343456XXX4\" }; string doctor_Name[] = { \"D1\", \"D4\", \"D3\", \"D2\" }; int prices[] = { 100, 200, 100, 290 }; // Function Call HospitalManagement( patient_Name, patient_Id, patient_Contact, bookingCost, hospital_Name, locations, beds, ratings, hospital_Contact, doctor_Name, prices); return 0;}", "e": 9120, "s": 1642, "text": null }, { "code": null, "e": 9129, "s": 9120, "text": "Output: " }, { "code": null, "e": 9153, "s": 9129, "text": "Technical Scripter 2020" }, { "code": null, "e": 9157, "s": 9153, "text": "C++" }, { "code": null, "e": 9170, "s": 9157, "text": "C++ Programs" }, { "code": null, "e": 9178, "s": 9170, "text": "Project" }, { "code": null, "e": 9197, "s": 9178, "text": "Technical Scripter" }, { "code": null, "e": 9201, "s": 9197, "text": "CPP" }, { "code": null, "e": 9299, "s": 9201, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9323, "s": 9299, "text": "Sorting a vector in C++" }, { "code": null, "e": 9343, "s": 9323, "text": "Polymorphism in C++" }, { "code": null, "e": 9387, "s": 9343, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 9420, "s": 9387, "text": "Friend class and function in C++" }, { "code": null, "e": 9445, "s": 9420, "text": "std::string class in C++" }, { "code": null, "e": 9480, "s": 9445, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 9514, "s": 9480, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 9558, "s": 9514, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 9617, "s": 9558, "text": "How to return multiple values from a function in C or C++?" } ]
How to sort a Scala Map by key
13 Aug, 2019 Map is same as dictionary which holds key:value pairs. In this article, we will learn how to sort a Scala Map by key. We can sort the map by key, from low to high or high to low, using sortBy.Syntax : mapName.toSeq.sortBy(_._1):_* Let’s try to understand it with better example.Example #1: // Scala program to sort given map by keyimport scala.collection.immutable.ListMap // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val mapIm = Map("Zash" -> 30, "Jhavesh" -> 20, "Charlie" -> 50) // Sort map by key val res = ListMap(mapIm.toSeq.sortBy(_._1):_*) println(res) } } Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30) Example #2: // Scala program to sort given map by keyimport scala.collection.immutable.ListMap // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val mapIm = Map("Zash" -> 30, "Jhavesh" -> 20, "Charlie" -> 50) // reverse map in ascending order val res = ListMap(mapIm.toSeq.sortWith(_._1 < _._1):_*) println(res) } } Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30) Example #3: // Scala program to sort given map by keyimport scala.collection.immutable.ListMap // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val mapIm = Map("Zash" -> 30, "Jhavesh" -> 20, "Charlie" -> 50) // reverse map in descending order val res = ListMap(mapIm.toSeq.sortWith(_._1 > _._1):_*) println(res) } } Map(Zash -> 30, Jhavesh -> 20, Charlie -> 50) Scala Scala-Map Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Class and Object in Scala Scala Tutorial – Learn Scala with Step By Step Guide Scala Lists Operators in Scala Scala | Arrays Scala Constructors Enumeration in Scala Lambda Expression in Scala How to Install Scala with VSCode? Inheritance in Scala
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2019" }, { "code": null, "e": 229, "s": 28, "text": "Map is same as dictionary which holds key:value pairs. In this article, we will learn how to sort a Scala Map by key. We can sort the map by key, from low to high or high to low, using sortBy.Syntax :" }, { "code": null, "e": 259, "s": 229, "text": "mapName.toSeq.sortBy(_._1):_*" }, { "code": null, "e": 318, "s": 259, "text": "Let’s try to understand it with better example.Example #1:" }, { "code": "// Scala program to sort given map by keyimport scala.collection.immutable.ListMap // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val mapIm = Map(\"Zash\" -> 30, \"Jhavesh\" -> 20, \"Charlie\" -> 50) // Sort map by key val res = ListMap(mapIm.toSeq.sortBy(_._1):_*) println(res) } } ", "e": 781, "s": 318, "text": null }, { "code": null, "e": 828, "s": 781, "text": "Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)\n" }, { "code": null, "e": 840, "s": 828, "text": "Example #2:" }, { "code": "// Scala program to sort given map by keyimport scala.collection.immutable.ListMap // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val mapIm = Map(\"Zash\" -> 30, \"Jhavesh\" -> 20, \"Charlie\" -> 50) // reverse map in ascending order val res = ListMap(mapIm.toSeq.sortWith(_._1 < _._1):_*) println(res) } } ", "e": 1311, "s": 840, "text": null }, { "code": null, "e": 1358, "s": 1311, "text": "Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)\n" }, { "code": null, "e": 1370, "s": 1358, "text": "Example #3:" }, { "code": "// Scala program to sort given map by keyimport scala.collection.immutable.ListMap // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val mapIm = Map(\"Zash\" -> 30, \"Jhavesh\" -> 20, \"Charlie\" -> 50) // reverse map in descending order val res = ListMap(mapIm.toSeq.sortWith(_._1 > _._1):_*) println(res) } } ", "e": 1842, "s": 1370, "text": null }, { "code": null, "e": 1889, "s": 1842, "text": "Map(Zash -> 30, Jhavesh -> 20, Charlie -> 50)\n" }, { "code": null, "e": 1895, "s": 1889, "text": "Scala" }, { "code": null, "e": 1905, "s": 1895, "text": "Scala-Map" }, { "code": null, "e": 1918, "s": 1905, "text": "Scala-Method" }, { "code": null, "e": 1924, "s": 1918, "text": "Scala" }, { "code": null, "e": 2022, "s": 1924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2048, "s": 2022, "text": "Class and Object in Scala" }, { "code": null, "e": 2101, "s": 2048, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 2113, "s": 2101, "text": "Scala Lists" }, { "code": null, "e": 2132, "s": 2113, "text": "Operators in Scala" }, { "code": null, "e": 2147, "s": 2132, "text": "Scala | Arrays" }, { "code": null, "e": 2166, "s": 2147, "text": "Scala Constructors" }, { "code": null, "e": 2187, "s": 2166, "text": "Enumeration in Scala" }, { "code": null, "e": 2214, "s": 2187, "text": "Lambda Expression in Scala" }, { "code": null, "e": 2248, "s": 2214, "text": "How to Install Scala with VSCode?" } ]
R – Repeat loop
21 Apr, 2020 Repeat loop in R is used to iterate over a block of code multiple number of times. And also it executes the same code again and again until a break statement is found. Repeat loop, unlike other loops, doesn’t use a condition to exit the loop instead it looks for a break statement that executes if a condition within the loop body results to be true. An infinite loop in R can be created very easily with the help of the Repeat loop. The keyword used for the repeat loop is 'repeat'. Syntax: repeat { commands if(condition) { break } } Flowchart: Example 1: # R program to illustrate repeat loop result <- c("Hello World")i <- 1 # test expression repeat { print(result) # update expression i <- i + 1 # Breaking condition if(i >5) { break }} Output: [1] "Hello World" [1] "Hello World" [1] "Hello World" [1] "Hello World" [1] "Hello World" Example 2: # R program to illustrate repeat loop result <- 1i <- 1 # test expression repeat { print(result) # update expression i <- i + 1 result = result + 1 # Breaking condition if(i > 5) { break }} Output: [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 Picked 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": "\n21 Apr, 2020" }, { "code": null, "e": 196, "s": 28, "text": "Repeat loop in R is used to iterate over a block of code multiple number of times. And also it executes the same code again and again until a break statement is found." }, { "code": null, "e": 512, "s": 196, "text": "Repeat loop, unlike other loops, doesn’t use a condition to exit the loop instead it looks for a break statement that executes if a condition within the loop body results to be true. An infinite loop in R can be created very easily with the help of the Repeat loop. The keyword used for the repeat loop is 'repeat'." }, { "code": null, "e": 520, "s": 512, "text": "Syntax:" }, { "code": null, "e": 581, "s": 520, "text": "repeat { \n commands \n if(condition) {\n break\n }\n}" }, { "code": null, "e": 592, "s": 581, "text": "Flowchart:" }, { "code": null, "e": 603, "s": 592, "text": "Example 1:" }, { "code": "# R program to illustrate repeat loop result <- c(\"Hello World\")i <- 1 # test expression repeat { print(result) # update expression i <- i + 1 # Breaking condition if(i >5) { break }}", "e": 819, "s": 603, "text": null }, { "code": null, "e": 827, "s": 819, "text": "Output:" }, { "code": null, "e": 917, "s": 827, "text": "[1] \"Hello World\"\n[1] \"Hello World\"\n[1] \"Hello World\"\n[1] \"Hello World\"\n[1] \"Hello World\"" }, { "code": null, "e": 928, "s": 917, "text": "Example 2:" }, { "code": "# R program to illustrate repeat loop result <- 1i <- 1 # test expression repeat { print(result) # update expression i <- i + 1 result = result + 1 # Breaking condition if(i > 5) { break }}", "e": 1149, "s": 928, "text": null }, { "code": null, "e": 1157, "s": 1149, "text": "Output:" }, { "code": null, "e": 1187, "s": 1157, "text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5" }, { "code": null, "e": 1194, "s": 1187, "text": "Picked" }, { "code": null, "e": 1205, "s": 1194, "text": "R Language" } ]
Python Program to convert List of Integer to List of String
23 Jan, 2020 Given a List of Integers. The task is to convert them to List of Strings. Examples: Input: [1, 12, 15, 21, 131] Output: ['1', '12', '15', '21', '131'] Input: [0, 1, 11, 15, 58] Output: ['0', '1', '11', '15', '58'] Method 1: Using map() # Python code to convert list of # string into sorted list of integer # List initialization list_int = [1, 12, 15, 21, 131] # mapping list_string = map(str, list_int) # Printing sorted list of integers print(list(list_string)) Output: ['1', '12', '15', '21', '131'] Example 2: Using list comprehension # Python code to convert list of # string into sorted list of integer # List initialization list_string = [1, 12, 15, 21, 131] # Using list comprehension output = [str(x) for x in list_string] # Printing output print(output) Output: ['1', '12', '15', '21', '131'] Method 3: Using iteration # Python code to convert list of # string into sorted list of integer # List initialization list_string = [1, 12, 15, 21, 131] list_int = []# using iteration and sorted() for i in list_string: list_int.append(i) # printing output print(list_int) Output: ['1', '12', '15', '21', '131'] Python list-programs python-list Python python-list 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 Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jan, 2020" }, { "code": null, "e": 127, "s": 53, "text": "Given a List of Integers. The task is to convert them to List of Strings." }, { "code": null, "e": 137, "s": 127, "text": "Examples:" }, { "code": null, "e": 269, "s": 137, "text": "Input: [1, 12, 15, 21, 131]\nOutput: ['1', '12', '15', '21', '131']\n\nInput: [0, 1, 11, 15, 58]\nOutput: ['0', '1', '11', '15', '58']\n" }, { "code": null, "e": 291, "s": 269, "text": "Method 1: Using map()" }, { "code": "# Python code to convert list of # string into sorted list of integer # List initialization list_int = [1, 12, 15, 21, 131] # mapping list_string = map(str, list_int) # Printing sorted list of integers print(list(list_string))", "e": 529, "s": 291, "text": null }, { "code": null, "e": 537, "s": 529, "text": "Output:" }, { "code": null, "e": 569, "s": 537, "text": "['1', '12', '15', '21', '131']\n" }, { "code": null, "e": 605, "s": 569, "text": "Example 2: Using list comprehension" }, { "code": "# Python code to convert list of # string into sorted list of integer # List initialization list_string = [1, 12, 15, 21, 131] # Using list comprehension output = [str(x) for x in list_string] # Printing output print(output)", "e": 841, "s": 605, "text": null }, { "code": null, "e": 849, "s": 841, "text": "Output:" }, { "code": null, "e": 881, "s": 849, "text": "['1', '12', '15', '21', '131']\n" }, { "code": null, "e": 907, "s": 881, "text": "Method 3: Using iteration" }, { "code": "# Python code to convert list of # string into sorted list of integer # List initialization list_string = [1, 12, 15, 21, 131] list_int = []# using iteration and sorted() for i in list_string: list_int.append(i) # printing output print(list_int) ", "e": 1171, "s": 907, "text": null }, { "code": null, "e": 1179, "s": 1171, "text": "Output:" }, { "code": null, "e": 1211, "s": 1179, "text": "['1', '12', '15', '21', '131']\n" }, { "code": null, "e": 1232, "s": 1211, "text": "Python list-programs" }, { "code": null, "e": 1244, "s": 1232, "text": "python-list" }, { "code": null, "e": 1251, "s": 1244, "text": "Python" }, { "code": null, "e": 1263, "s": 1251, "text": "python-list" }, { "code": null, "e": 1361, "s": 1263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1393, "s": 1361, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1420, "s": 1393, "text": "Python Classes and Objects" }, { "code": null, "e": 1441, "s": 1420, "text": "Python OOPs Concepts" }, { "code": null, "e": 1472, "s": 1441, "text": "Python | os.path.join() method" }, { "code": null, "e": 1528, "s": 1472, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1551, "s": 1528, "text": "Introduction To PYTHON" }, { "code": null, "e": 1593, "s": 1551, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1635, "s": 1593, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1674, "s": 1635, "text": "Python | datetime.timedelta() function" } ]
How to Remove the Legend in Matplotlib?
01 Feb, 2021 Matplotlib is one of the most popular data visualization libraries present in Python. Using this matplotlib library, if we want to visualize more than a single variable, we might want to explain what each variable represents. For this purpose, there is a function called legend() present in matplotlib library. This legend is a small area on the graph describing what each variable represents. In order to remove the legend, there are four ways. They are : Using .remove() Using .set_visible() Fix legend_ attribute of the required Axes object = None Using label=_nolegend_ Method 1: Using .remove() Example 1: By using ax.get_legend().remove() method, legend can be removed from figure in matplotlib. Python3 import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 100)y1 = np.power(x, 2)y2 = np.power(x, 3) fig, ax = plt.subplots() ax.plot(x, y1, c = 'r',label = 'x^2')ax.plot(x, y2, c = 'g',label = 'x^3') leg = plt.legend() ax.get_legend().remove() plt.show() Output : We can see that there is no legend in the above figure. Example 2: More than one subplots : In the case of more than one subplot, we can mention the required subplot object for which we want to remove the legend. Here, we have written axs[1].get_legend().remove() which means we are removing legend for second subplot specifically. Python3 import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 100)y1 = np.power(x, 2)y2 = np.power(x, 3) fig, axs = plt.subplots(2, 1) axs[0].plot(x, y1, c = 'r',label = 'x^2')axs[1].plot(x, y2, c = 'g',label = 'x^3') axs[0].legend(loc = 'upper left')axs[1].legend(loc = 'upper left') axs[1].get_legend().remove() plt.show() Output : In the above figure, we removed the legend for the second subplot specifically. The first subplot will still have a legend. Method 2: Using set_visible() Example 1: By using ax.get_legend().set_visible(False) method, legend can be removed from figure in matplotlib. Python3 import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 1000)y1 = np.sin(x)y2 = np.cos(x) fig, ax = plt.subplots() ax.plot(x, y1,c = 'r',label = 'Sine')ax.plot(x, y2,c = 'g',label = 'Cosine') leg = plt.legend() ax.get_legend().set_visible(False) plt.show() Output : We can see that there is no legend in the above figure. Example-2. More than one subplots : In case of more than one subplot, we can mention the required subplot object for which we want to remove the legend. Here, we have written axs[1].get_legend().set_visible(False) which means we are removing legend for second subplot specifically. Python3 import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3,3,1000)y1 = np.sin(x)y2 = np.cos(x) fig, axs = plt.subplots(2,1) axs[0].plot(x,y1,c='r',label = 'Sine')axs[1].plot(x,y2,c='g',label = 'Cosine') axs[0].legend(loc='upper left')axs[1].legend(loc='upper left') axs[1].get_legend().set_visible(False) plt.show() Output : In the above figure, we removed legend for the second subplot specifically. The first subplot will still have legend. Method 3: Fix legend_ attribute of the required Axes object = None : Example 1: By using ax.legend_ = None, legend can be removed from figure in matplotlib. Python3 import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 1000)y1 = np.sin(x)y2 = np.cos(x) fig, ax = plt.subplots() ax.plot(x, y1,c = 'r',label = 'Sine')ax.plot(x, y2,c = 'g',label = 'Cosine')leg = plt.legend()ax.legend_ = None plt.show() Output: We can see that there is no legend in the above figure. Example 2: More than one subplot: In the case of more than one subplot, we can mention the required subplot object for which we want to remove the legend. Here, we have written axs[0].legend_ = None which means we are removing legend for the first subplot specifically.the Python3 import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 1000)y1 = np.sin(x)y2 = np.cos(x) fig, axs = plt.subplots(2, 1) axs[0].plot(x, y1, c = 'r',label = 'Sine')axs[1].plot(x, y2,c = 'g',label = 'Cosine')axs[0].legend(loc = 'upper left')axs[1].legend(loc = 'upper left')axs[0].legend_ = None plt.show() Output: In the above figure, we removed legend for the first subplot specifically. The second subplot will still have legend. Method 4: Using label = _legend_ Example 1: By sending label = ‘_nolegend_’ argument in ax.plot(), legend can be removed from figure in matplotlib. Python3 import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 100)y1 = np.power(x, 2)y2 = np.power(x, 3) fig, ax = plt.subplots() ax.plot(x, y1, c = 'r',label = '_nolegend_')ax.plot(x, y2,c = 'g',label = '_nolegend_') leg = plt.legend() plt.show() Output: Example-2. More than one subplots : In case of more than one subplot, we can mention the required subplot object for which we want to remove the legend. Here, we have written axs[0].plot(x,y1,c=’r’,label = ‘_nolegend_’) which means we are removing legend for first subplot specifically. Python3 import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3,3,100)y1 = np.power(x,2)y2 = np.power(x,3) fig, axs = plt.subplots(2,1) axs[0].plot(x,y1,c='r',label = '_nolegend_')axs[1].plot(x,y2,c='g',label = 'x^3') axs[0].legend(loc='upper left')axs[1].legend(loc='upper left') plt.show() Output : In the above figure, we removed legend for the first subplot specifically. The second subplot will still have legend. vasireddykomalkumar Picked Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2021" }, { "code": null, "e": 422, "s": 28, "text": "Matplotlib is one of the most popular data visualization libraries present in Python. Using this matplotlib library, if we want to visualize more than a single variable, we might want to explain what each variable represents. For this purpose, there is a function called legend() present in matplotlib library. This legend is a small area on the graph describing what each variable represents." }, { "code": null, "e": 486, "s": 422, "text": "In order to remove the legend, there are four ways. They are : " }, { "code": null, "e": 502, "s": 486, "text": "Using .remove()" }, { "code": null, "e": 523, "s": 502, "text": "Using .set_visible()" }, { "code": null, "e": 580, "s": 523, "text": "Fix legend_ attribute of the required Axes object = None" }, { "code": null, "e": 606, "s": 580, "text": "Using label=_nolegend_ " }, { "code": null, "e": 632, "s": 606, "text": "Method 1: Using .remove()" }, { "code": null, "e": 734, "s": 632, "text": "Example 1: By using ax.get_legend().remove() method, legend can be removed from figure in matplotlib." }, { "code": null, "e": 742, "s": 734, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 100)y1 = np.power(x, 2)y2 = np.power(x, 3) fig, ax = plt.subplots() ax.plot(x, y1, c = 'r',label = 'x^2')ax.plot(x, y2, c = 'g',label = 'x^3') leg = plt.legend() ax.get_legend().remove() plt.show()", "e": 1013, "s": 742, "text": null }, { "code": null, "e": 1025, "s": 1013, "text": " Output : " }, { "code": null, "e": 1081, "s": 1025, "text": "We can see that there is no legend in the above figure." }, { "code": null, "e": 1118, "s": 1081, "text": "Example 2: More than one subplots : " }, { "code": null, "e": 1359, "s": 1118, "text": "In the case of more than one subplot, we can mention the required subplot object for which we want to remove the legend. Here, we have written axs[1].get_legend().remove() which means we are removing legend for second subplot specifically. " }, { "code": null, "e": 1367, "s": 1359, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 100)y1 = np.power(x, 2)y2 = np.power(x, 3) fig, axs = plt.subplots(2, 1) axs[0].plot(x, y1, c = 'r',label = 'x^2')axs[1].plot(x, y2, c = 'g',label = 'x^3') axs[0].legend(loc = 'upper left')axs[1].legend(loc = 'upper left') axs[1].get_legend().remove() plt.show()", "e": 1704, "s": 1367, "text": null }, { "code": null, "e": 1717, "s": 1707, "text": "Output : " }, { "code": null, "e": 1843, "s": 1719, "text": "In the above figure, we removed the legend for the second subplot specifically. The first subplot will still have a legend." }, { "code": null, "e": 1876, "s": 1845, "text": "Method 2: Using set_visible() " }, { "code": null, "e": 1988, "s": 1876, "text": "Example 1: By using ax.get_legend().set_visible(False) method, legend can be removed from figure in matplotlib." }, { "code": null, "e": 1996, "s": 1988, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 1000)y1 = np.sin(x)y2 = np.cos(x) fig, ax = plt.subplots() ax.plot(x, y1,c = 'r',label = 'Sine')ax.plot(x, y2,c = 'g',label = 'Cosine') leg = plt.legend() ax.get_legend().set_visible(False) plt.show()", "e": 2270, "s": 1996, "text": null }, { "code": null, "e": 2282, "s": 2273, "text": "Output :" }, { "code": null, "e": 2342, "s": 2286, "text": "We can see that there is no legend in the above figure." }, { "code": null, "e": 2379, "s": 2342, "text": "Example-2. More than one subplots :" }, { "code": null, "e": 2625, "s": 2379, "text": "In case of more than one subplot, we can mention the required subplot object for which we want to remove the legend. Here, we have written axs[1].get_legend().set_visible(False) which means we are removing legend for second subplot specifically." }, { "code": null, "e": 2633, "s": 2625, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3,3,1000)y1 = np.sin(x)y2 = np.cos(x) fig, axs = plt.subplots(2,1) axs[0].plot(x,y1,c='r',label = 'Sine')axs[1].plot(x,y2,c='g',label = 'Cosine') axs[0].legend(loc='upper left')axs[1].legend(loc='upper left') axs[1].get_legend().set_visible(False) plt.show()", "e": 2960, "s": 2633, "text": null }, { "code": null, "e": 2970, "s": 2960, "text": "Output : " }, { "code": null, "e": 3088, "s": 2970, "text": "In the above figure, we removed legend for the second subplot specifically. The first subplot will still have legend." }, { "code": null, "e": 3157, "s": 3088, "text": "Method 3: Fix legend_ attribute of the required Axes object = None :" }, { "code": null, "e": 3246, "s": 3157, "text": "Example 1: By using ax.legend_ = None, legend can be removed from figure in matplotlib. " }, { "code": null, "e": 3254, "s": 3246, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 1000)y1 = np.sin(x)y2 = np.cos(x) fig, ax = plt.subplots() ax.plot(x, y1,c = 'r',label = 'Sine')ax.plot(x, y2,c = 'g',label = 'Cosine')leg = plt.legend()ax.legend_ = None plt.show()", "e": 3509, "s": 3254, "text": null }, { "code": null, "e": 3517, "s": 3509, "text": "Output:" }, { "code": null, "e": 3573, "s": 3517, "text": "We can see that there is no legend in the above figure." }, { "code": null, "e": 3607, "s": 3573, "text": "Example 2: More than one subplot:" }, { "code": null, "e": 3847, "s": 3607, "text": "In the case of more than one subplot, we can mention the required subplot object for which we want to remove the legend. Here, we have written axs[0].legend_ = None which means we are removing legend for the first subplot specifically.the " }, { "code": null, "e": 3855, "s": 3847, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 1000)y1 = np.sin(x)y2 = np.cos(x) fig, axs = plt.subplots(2, 1) axs[0].plot(x, y1, c = 'r',label = 'Sine')axs[1].plot(x, y2,c = 'g',label = 'Cosine')axs[0].legend(loc = 'upper left')axs[1].legend(loc = 'upper left')axs[0].legend_ = None plt.show()", "e": 4176, "s": 3855, "text": null }, { "code": null, "e": 4184, "s": 4176, "text": "Output:" }, { "code": null, "e": 4302, "s": 4184, "text": "In the above figure, we removed legend for the first subplot specifically. The second subplot will still have legend." }, { "code": null, "e": 4335, "s": 4302, "text": "Method 4: Using label = _legend_" }, { "code": null, "e": 4450, "s": 4335, "text": "Example 1: By sending label = ‘_nolegend_’ argument in ax.plot(), legend can be removed from figure in matplotlib." }, { "code": null, "e": 4458, "s": 4450, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3, 3, 100)y1 = np.power(x, 2)y2 = np.power(x, 3) fig, ax = plt.subplots() ax.plot(x, y1, c = 'r',label = '_nolegend_')ax.plot(x, y2,c = 'g',label = '_nolegend_') leg = plt.legend() plt.show()", "e": 4717, "s": 4458, "text": null }, { "code": null, "e": 4729, "s": 4720, "text": "Output: " }, { "code": null, "e": 4768, "s": 4731, "text": "Example-2. More than one subplots :" }, { "code": null, "e": 5019, "s": 4768, "text": "In case of more than one subplot, we can mention the required subplot object for which we want to remove the legend. Here, we have written axs[0].plot(x,y1,c=’r’,label = ‘_nolegend_’) which means we are removing legend for first subplot specifically." }, { "code": null, "e": 5027, "s": 5019, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt x = np.linspace(-3,3,100)y1 = np.power(x,2)y2 = np.power(x,3) fig, axs = plt.subplots(2,1) axs[0].plot(x,y1,c='r',label = '_nolegend_')axs[1].plot(x,y2,c='g',label = 'x^3') axs[0].legend(loc='upper left')axs[1].legend(loc='upper left') plt.show()", "e": 5325, "s": 5027, "text": null }, { "code": null, "e": 5335, "s": 5325, "text": "Output : " }, { "code": null, "e": 5454, "s": 5335, "text": " In the above figure, we removed legend for the first subplot specifically. The second subplot will still have legend." }, { "code": null, "e": 5474, "s": 5454, "text": "vasireddykomalkumar" }, { "code": null, "e": 5481, "s": 5474, "text": "Picked" }, { "code": null, "e": 5499, "s": 5481, "text": "Python-matplotlib" }, { "code": null, "e": 5523, "s": 5499, "text": "Technical Scripter 2020" }, { "code": null, "e": 5530, "s": 5523, "text": "Python" }, { "code": null, "e": 5549, "s": 5530, "text": "Technical Scripter" }, { "code": null, "e": 5647, "s": 5549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5675, "s": 5647, "text": "Read JSON file using Python" }, { "code": null, "e": 5697, "s": 5675, "text": "Python map() function" }, { "code": null, "e": 5747, "s": 5697, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5765, "s": 5747, "text": "Python Dictionary" }, { "code": null, "e": 5809, "s": 5765, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 5851, "s": 5809, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5874, "s": 5851, "text": "Taking input in Python" }, { "code": null, "e": 5896, "s": 5874, "text": "Enumerate() in Python" }, { "code": null, "e": 5931, "s": 5896, "text": "Read a file line by line in Python" } ]
File mkdir() method in Java with examples
28 Jan, 2019 The mkdir() method is a part of File class. The mkdir() function is used to create a new directory denoted by the abstract pathname. The function returns true if directory is created else returns false. Function Signature: public boolean mkdir() Syntax: file.mkdir() Parameters: This method do not accepts any parameter. Return Value: The function returns boolean data type. The function returns true if directory is created else returns false. Exception: This method throws SecurityException if the method does not allow directory to be created Below programs will illustrate the use of mkdirs() function: Example 1: Try to create a new directory named program in “f:” drive. // Java program to demonstrate// the use of File.mkdirs() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File("F:\\program"); // check if the directory can be created // using the abstract path name if (f.mkdir()) { // display that the directory is created // as the function returned true System.out.println("Directory is created"); } else { // display that the directory cannot be created // as the function returned false System.out.println("Directory cannot be created"); } }} Output: Directory is created Example 2: Try to create a new directory named program1 in “f:\program” directory, but program directory is not created .we will test whether the function mkdir() can create the parent directories of the abstract path name if the directories are not present. // Java program to demonstrate// the use of File.mkdir() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File("F:\\program\\program1"); // check if the directory can be created // using the abstract path name if (f.mkdir()) { // display that the directory is created // as the function returned true System.out.println("Directory is created"); } else { // display that the directory cannot be created // as the function returned false System.out.println("Directory cannot be created"); } }} Output: Directory cannot be created The programs might not run in an online IDE. please use an offline IDE and set the path of the file Java-File Class Java-Functions Java-IO package Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array Iterate through List in Java Java program to count the occurrence of each character in a string using Hashmap How to Iterate HashMap in Java? Remove first and last character of a string in Java Program to print ASCII Value of a character Traverse Through a HashMap in Java Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java?
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Jan, 2019" }, { "code": null, "e": 256, "s": 53, "text": "The mkdir() method is a part of File class. The mkdir() function is used to create a new directory denoted by the abstract pathname. The function returns true if directory is created else returns false." }, { "code": null, "e": 276, "s": 256, "text": "Function Signature:" }, { "code": null, "e": 299, "s": 276, "text": "public boolean mkdir()" }, { "code": null, "e": 307, "s": 299, "text": "Syntax:" }, { "code": null, "e": 320, "s": 307, "text": "file.mkdir()" }, { "code": null, "e": 374, "s": 320, "text": "Parameters: This method do not accepts any parameter." }, { "code": null, "e": 498, "s": 374, "text": "Return Value: The function returns boolean data type. The function returns true if directory is created else returns false." }, { "code": null, "e": 599, "s": 498, "text": "Exception: This method throws SecurityException if the method does not allow directory to be created" }, { "code": null, "e": 660, "s": 599, "text": "Below programs will illustrate the use of mkdirs() function:" }, { "code": null, "e": 730, "s": 660, "text": "Example 1: Try to create a new directory named program in “f:” drive." }, { "code": "// Java program to demonstrate// the use of File.mkdirs() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File(\"F:\\\\program\"); // check if the directory can be created // using the abstract path name if (f.mkdir()) { // display that the directory is created // as the function returned true System.out.println(\"Directory is created\"); } else { // display that the directory cannot be created // as the function returned false System.out.println(\"Directory cannot be created\"); } }}", "e": 1446, "s": 730, "text": null }, { "code": null, "e": 1454, "s": 1446, "text": "Output:" }, { "code": null, "e": 1475, "s": 1454, "text": "Directory is created" }, { "code": null, "e": 1734, "s": 1475, "text": "Example 2: Try to create a new directory named program1 in “f:\\program” directory, but program directory is not created .we will test whether the function mkdir() can create the parent directories of the abstract path name if the directories are not present." }, { "code": "// Java program to demonstrate// the use of File.mkdir() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File(\"F:\\\\program\\\\program1\"); // check if the directory can be created // using the abstract path name if (f.mkdir()) { // display that the directory is created // as the function returned true System.out.println(\"Directory is created\"); } else { // display that the directory cannot be created // as the function returned false System.out.println(\"Directory cannot be created\"); } }}", "e": 2461, "s": 1734, "text": null }, { "code": null, "e": 2469, "s": 2461, "text": "Output:" }, { "code": null, "e": 2497, "s": 2469, "text": "Directory cannot be created" }, { "code": null, "e": 2597, "s": 2497, "text": "The programs might not run in an online IDE. please use an offline IDE and set the path of the file" }, { "code": null, "e": 2613, "s": 2597, "text": "Java-File Class" }, { "code": null, "e": 2628, "s": 2613, "text": "Java-Functions" }, { "code": null, "e": 2644, "s": 2628, "text": "Java-IO package" }, { "code": null, "e": 2658, "s": 2644, "text": "Java Programs" }, { "code": null, "e": 2756, "s": 2658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2794, "s": 2756, "text": "Factory method design pattern in Java" }, { "code": null, "e": 2851, "s": 2794, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 2880, "s": 2851, "text": "Iterate through List in Java" }, { "code": null, "e": 2961, "s": 2880, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 2993, "s": 2961, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 3045, "s": 2993, "text": "Remove first and last character of a string in Java" }, { "code": null, "e": 3089, "s": 3045, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 3124, "s": 3089, "text": "Traverse Through a HashMap in Java" }, { "code": null, "e": 3172, "s": 3124, "text": "Iterate Over the Characters of a String in Java" } ]
Getting frequency counts of a columns in Pandas DataFrame
28 Dec, 2018 Given a Pandas dataframe, we need to find the frequency counts of each item in one or more columns of this dataframe. This can be achieved in multiple ways: Method #1: Using Series.value_counts() This method is applicable to pandas.Series object. Since each DataFrame object is a collection of Series object, we can apply this method to get the frequency counts of values in one column. # importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g', 'bar', 'bar', 'foo', 'bar'], 'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] }) # frequency count of column Acount = df['A'].value_counts()print(count) Output: Method #2: Using GroupBy.count() This method can be used to count frequencies of objects over single columns. After grouping a DataFrame object on one column, we can apply count() method on the resulting groupby object to get a DataFrame object containing frequency count. # importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({ 'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g', 'bar', 'bar', 'foo', 'bar'], 'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] }) # Multi-column frequency countcount = df.groupby(['A']).count()print(count) Output: Method #3: Using GroupBy.size() This method can be used to count frequencies of objects over single or multiple columns. After grouping a DataFrame object on one or more columns, we can apply size() method on the resulting groupby object to get a Series object containing frequency count. # importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({ 'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g', 'bar', 'bar', 'foo', 'bar'], 'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] }) # Multi-column frequency countcount = df.groupby(['A', 'B']).size()print(count) 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": "\n28 Dec, 2018" }, { "code": null, "e": 185, "s": 28, "text": "Given a Pandas dataframe, we need to find the frequency counts of each item in one or more columns of this dataframe. This can be achieved in multiple ways:" }, { "code": null, "e": 224, "s": 185, "text": "Method #1: Using Series.value_counts()" }, { "code": null, "e": 415, "s": 224, "text": "This method is applicable to pandas.Series object. Since each DataFrame object is a collection of Series object, we can apply this method to get the frequency counts of values in one column." }, { "code": "# importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g', 'bar', 'bar', 'foo', 'bar'], 'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] }) # frequency count of column Acount = df['A'].value_counts()print(count)", "e": 735, "s": 415, "text": null }, { "code": null, "e": 776, "s": 735, "text": "Output: Method #2: Using GroupBy.count()" }, { "code": null, "e": 1016, "s": 776, "text": "This method can be used to count frequencies of objects over single columns. After grouping a DataFrame object on one column, we can apply count() method on the resulting groupby object to get a DataFrame object containing frequency count." }, { "code": "# importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({ 'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g', 'bar', 'bar', 'foo', 'bar'], 'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] }) # Multi-column frequency countcount = df.groupby(['A']).count()print(count)", "e": 1349, "s": 1016, "text": null }, { "code": null, "e": 1389, "s": 1349, "text": "Output: Method #3: Using GroupBy.size()" }, { "code": null, "e": 1646, "s": 1389, "text": "This method can be used to count frequencies of objects over single or multiple columns. After grouping a DataFrame object on one or more columns, we can apply size() method on the resulting groupby object to get a Series object containing frequency count." }, { "code": "# importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({ 'A': ['foo', 'bar', 'g2g', 'g2g', 'g2g', 'bar', 'bar', 'foo', 'bar'], 'B': ['a', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'b'] }) # Multi-column frequency countcount = df.groupby(['A', 'B']).size()print(count)", "e": 1984, "s": 1646, "text": null }, { "code": null, "e": 1992, "s": 1984, "text": "Output:" }, { "code": null, "e": 2017, "s": 1992, "text": "pandas-dataframe-program" }, { "code": null, "e": 2024, "s": 2017, "text": "Picked" }, { "code": null, "e": 2048, "s": 2024, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2062, "s": 2048, "text": "Python-pandas" }, { "code": null, "e": 2069, "s": 2062, "text": "Python" } ]
Flatten BST to sorted list | Decreasing order
10 Nov, 2021 Given a binary search tree, the task is to flatten it to a sorted list in decreasing order. Precisely, the value of each node must be greater than the values of all the nodes at its right, and its left node must be NULL after flattening. We must do it in O(H) extra space where ‘H’ is the height of BST. Examples: Input: 5 / \ 3 7 / \ / \ 2 4 6 8 Output: 8 7 6 5 4 3 2 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 5 4 3 2 1 Approach: A simple approach will be to recreate the BST from its ‘reverse in-order’ traversal. This will take O(N) extra space where N is the number of nodes in BST. To improve upon that, we will simulate the reverse in-order traversal of a binary tree as follows: Create a dummy node.Create a variable called ‘prev’ and make it point to the dummy node.Perform reverse in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr Create a dummy node. Create a variable called ‘prev’ and make it point to the dummy node. Perform reverse in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr Set prev -> right = curr Set prev -> left = NULL Set prev = curr This will improve the space complexity to O(H) in the worst case as in-order traversal takes O(H) extra space. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the// above approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Function to print flattened// binary treevoid print(node* parent){ node* curr = parent; while (curr != NULL) cout << curr->data << " ", curr = curr->right;} // Function to perform reverse in-order traversalvoid revInorder(node* curr, node*& prev){ // Base case if (curr == NULL) return; revInorder(curr->right, prev); prev->left = NULL; prev->right = curr; prev = curr; revInorder(curr->left, prev);} // Function to flatten binary tree using// level order traversalnode* flatten(node* parent){ // Dummy node node* dummy = new node(-1); // Pointer to previous element node* prev = dummy; // Calling in-order traversal revInorder(parent, prev); prev->left = NULL; prev->right = NULL; node* ret = dummy->right; // Delete dummy node delete dummy; return ret;} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); // Calling required function print(flatten(root)); return 0;} // Java implementation of the// above approachimport java.util.*;class GFG{ // Node of the binary treestatic class node{ int data; node left; node right; node(int data) { this.data = data; left = null; right = null; }}; // Function to print flattened// binary treestatic void print(node parent){ node curr = parent; while (curr != null) { System.out.print(curr.data + " "); curr = curr.right; }} static node prev; // Function to perform reverse// in-order traversalstatic void revInorder(node curr){ // Base case if (curr == null) return; revInorder(curr.right); prev.left = null; prev.right = curr; prev = curr; revInorder(curr.left);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){ // Dummy node node dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal revInorder(parent); prev.left = null; prev.right = null; node ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codepublic static void main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); // Calling required function print(flatten(root));}} // This code is contributed by Amit Katiyar # Python3 implementation of the# above approach # Node of the binary treeclass node: def __init__(self, data): self.data = data; self.left = None; self.right = None; # Function to print flattened# binary treedef printNode(parent): curr = parent; while (curr != None): print(curr.data, end = ' ') curr = curr.right; # Function to perform reverse in-order traversaldef revInorder(curr): global prev; # Base case if (curr == None): return; revInorder(curr.right); prev.left = None; prev.right = curr; prev = curr; revInorder(curr.left); # Function to flatten binary tree using# level order traversaldef flatten(parent): global prev; # Dummy node dummy = node(-1); # Pointer to previous element prev = dummy; # Calling in-order traversal revInorder(parent); prev.left = None; prev.right = None; ret = dummy.right; return ret; # Driver codeprev = node(0)root = node(5);root.left = node(3);root.right = node(7);root.left.left = node(2);root.left.right = node(4);root.right.left = node(6);root.right.right = node(8); # Calling required functionprintNode(flatten(root)); # This code is contributed by rrrtnx. // C# implementation of the// above approachusing System; class GFG{ // Node of the binary treepublic class node{ public int data; public node left; public node right; public node(int data) { this.data = data; left = null; right = null; }}; // Function to print flattened// binary treestatic void print(node parent){ node curr = parent; while (curr != null) { Console.Write(curr.data + " "); curr = curr.right; }} static node prev; // Function to perform reverse// in-order traversalstatic void revInorder(node curr){ // Base case if (curr == null) return; revInorder(curr.right); prev.left = null; prev.right = curr; prev = curr; revInorder(curr.left);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){ // Dummy node node dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal revInorder(parent); prev.left = null; prev.right = null; node ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codepublic static void Main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); // Calling required function print(flatten(root));}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Function to print flattened// binary treefunction print(parent){ let curr = parent; while (curr != null) { document.write(curr.data + " "); curr = curr.right; }} let prev; // Function to perform reverse// in-order traversalfunction revInorder(curr){ // Base case if (curr == null) return; revInorder(curr.right); prev.left = null; prev.right = curr; prev = curr; revInorder(curr.left);} // Function to flatten binary// tree using level order// traversalfunction flatten(parent){ // Dummy node let dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal revInorder(parent); prev.left = null; prev.right = null; let ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codelet root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); // Calling required functionprint(flatten(root)); // This code is contributed by divyeshrabadiya07 </script> 8 7 6 5 4 3 2 Time Complexity: O(N)Auxiliary Space: O(N) amit143katiyar Rajput-Ji divyeshrabadiya07 pankajsharmagfg rrrtnx Algorithms Binary Search Tree Data Structures Tree Data Structures Binary Search Tree Tree Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Binary Search Tree | Set 1 (Search and Insertion) AVL Tree | Set 1 (Insertion) Binary Search Tree | Set 2 (Delete) A program to check if a binary tree is BST or not Find postorder traversal of BST from preorder traversal
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Nov, 2021" }, { "code": null, "e": 332, "s": 28, "text": "Given a binary search tree, the task is to flatten it to a sorted list in decreasing order. Precisely, the value of each node must be greater than the values of all the nodes at its right, and its left node must be NULL after flattening. We must do it in O(H) extra space where ‘H’ is the height of BST." }, { "code": null, "e": 343, "s": 332, "text": "Examples: " }, { "code": null, "e": 585, "s": 343, "text": "Input: \n 5 \n / \\ \n 3 7 \n / \\ / \\ \n 2 4 6 8\nOutput: 8 7 6 5 4 3 2\n\nInput:\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\nOutput: 5 4 3 2 1" }, { "code": null, "e": 852, "s": 585, "text": "Approach: A simple approach will be to recreate the BST from its ‘reverse in-order’ traversal. This will take O(N) extra space where N is the number of nodes in BST. To improve upon that, we will simulate the reverse in-order traversal of a binary tree as follows: " }, { "code": null, "e": 1056, "s": 852, "text": "Create a dummy node.Create a variable called ‘prev’ and make it point to the dummy node.Perform reverse in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr" }, { "code": null, "e": 1077, "s": 1056, "text": "Create a dummy node." }, { "code": null, "e": 1146, "s": 1077, "text": "Create a variable called ‘prev’ and make it point to the dummy node." }, { "code": null, "e": 1262, "s": 1146, "text": "Perform reverse in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr" }, { "code": null, "e": 1287, "s": 1262, "text": "Set prev -> right = curr" }, { "code": null, "e": 1311, "s": 1287, "text": "Set prev -> left = NULL" }, { "code": null, "e": 1327, "s": 1311, "text": "Set prev = curr" }, { "code": null, "e": 1438, "s": 1327, "text": "This will improve the space complexity to O(H) in the worst case as in-order traversal takes O(H) extra space." }, { "code": null, "e": 1490, "s": 1438, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1494, "s": 1490, "text": "C++" }, { "code": null, "e": 1499, "s": 1494, "text": "Java" }, { "code": null, "e": 1507, "s": 1499, "text": "Python3" }, { "code": null, "e": 1510, "s": 1507, "text": "C#" }, { "code": null, "e": 1521, "s": 1510, "text": "Javascript" }, { "code": "// C++ implementation of the// above approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Function to print flattened// binary treevoid print(node* parent){ node* curr = parent; while (curr != NULL) cout << curr->data << \" \", curr = curr->right;} // Function to perform reverse in-order traversalvoid revInorder(node* curr, node*& prev){ // Base case if (curr == NULL) return; revInorder(curr->right, prev); prev->left = NULL; prev->right = curr; prev = curr; revInorder(curr->left, prev);} // Function to flatten binary tree using// level order traversalnode* flatten(node* parent){ // Dummy node node* dummy = new node(-1); // Pointer to previous element node* prev = dummy; // Calling in-order traversal revInorder(parent, prev); prev->left = NULL; prev->right = NULL; node* ret = dummy->right; // Delete dummy node delete dummy; return ret;} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); // Calling required function print(flatten(root)); return 0;}", "e": 2964, "s": 1521, "text": null }, { "code": "// Java implementation of the// above approachimport java.util.*;class GFG{ // Node of the binary treestatic class node{ int data; node left; node right; node(int data) { this.data = data; left = null; right = null; }}; // Function to print flattened// binary treestatic void print(node parent){ node curr = parent; while (curr != null) { System.out.print(curr.data + \" \"); curr = curr.right; }} static node prev; // Function to perform reverse// in-order traversalstatic void revInorder(node curr){ // Base case if (curr == null) return; revInorder(curr.right); prev.left = null; prev.right = curr; prev = curr; revInorder(curr.left);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){ // Dummy node node dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal revInorder(parent); prev.left = null; prev.right = null; node ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codepublic static void main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); // Calling required function print(flatten(root));}} // This code is contributed by Amit Katiyar", "e": 4374, "s": 2964, "text": null }, { "code": "# Python3 implementation of the# above approach # Node of the binary treeclass node: def __init__(self, data): self.data = data; self.left = None; self.right = None; # Function to print flattened# binary treedef printNode(parent): curr = parent; while (curr != None): print(curr.data, end = ' ') curr = curr.right; # Function to perform reverse in-order traversaldef revInorder(curr): global prev; # Base case if (curr == None): return; revInorder(curr.right); prev.left = None; prev.right = curr; prev = curr; revInorder(curr.left); # Function to flatten binary tree using# level order traversaldef flatten(parent): global prev; # Dummy node dummy = node(-1); # Pointer to previous element prev = dummy; # Calling in-order traversal revInorder(parent); prev.left = None; prev.right = None; ret = dummy.right; return ret; # Driver codeprev = node(0)root = node(5);root.left = node(3);root.right = node(7);root.left.left = node(2);root.left.right = node(4);root.right.left = node(6);root.right.right = node(8); # Calling required functionprintNode(flatten(root)); # This code is contributed by rrrtnx.", "e": 5598, "s": 4374, "text": null }, { "code": "// C# implementation of the// above approachusing System; class GFG{ // Node of the binary treepublic class node{ public int data; public node left; public node right; public node(int data) { this.data = data; left = null; right = null; }}; // Function to print flattened// binary treestatic void print(node parent){ node curr = parent; while (curr != null) { Console.Write(curr.data + \" \"); curr = curr.right; }} static node prev; // Function to perform reverse// in-order traversalstatic void revInorder(node curr){ // Base case if (curr == null) return; revInorder(curr.right); prev.left = null; prev.right = curr; prev = curr; revInorder(curr.left);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){ // Dummy node node dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal revInorder(parent); prev.left = null; prev.right = null; node ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codepublic static void Main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); // Calling required function print(flatten(root));}} // This code is contributed by Rajput-Ji", "e": 7040, "s": 5598, "text": null }, { "code": "<script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Function to print flattened// binary treefunction print(parent){ let curr = parent; while (curr != null) { document.write(curr.data + \" \"); curr = curr.right; }} let prev; // Function to perform reverse// in-order traversalfunction revInorder(curr){ // Base case if (curr == null) return; revInorder(curr.right); prev.left = null; prev.right = curr; prev = curr; revInorder(curr.left);} // Function to flatten binary// tree using level order// traversalfunction flatten(parent){ // Dummy node let dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal revInorder(parent); prev.left = null; prev.right = null; let ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codelet root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); // Calling required functionprint(flatten(root)); // This code is contributed by divyeshrabadiya07 </script>", "e": 8424, "s": 7040, "text": null }, { "code": null, "e": 8438, "s": 8424, "text": "8 7 6 5 4 3 2" }, { "code": null, "e": 8483, "s": 8440, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 8498, "s": 8483, "text": "amit143katiyar" }, { "code": null, "e": 8508, "s": 8498, "text": "Rajput-Ji" }, { "code": null, "e": 8526, "s": 8508, "text": "divyeshrabadiya07" }, { "code": null, "e": 8542, "s": 8526, "text": "pankajsharmagfg" }, { "code": null, "e": 8549, "s": 8542, "text": "rrrtnx" }, { "code": null, "e": 8560, "s": 8549, "text": "Algorithms" }, { "code": null, "e": 8579, "s": 8560, "text": "Binary Search Tree" }, { "code": null, "e": 8595, "s": 8579, "text": "Data Structures" }, { "code": null, "e": 8600, "s": 8595, "text": "Tree" }, { "code": null, "e": 8616, "s": 8600, "text": "Data Structures" }, { "code": null, "e": 8635, "s": 8616, "text": "Binary Search Tree" }, { "code": null, "e": 8640, "s": 8635, "text": "Tree" }, { "code": null, "e": 8651, "s": 8640, "text": "Algorithms" }, { "code": null, "e": 8749, "s": 8651, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8787, "s": 8749, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 8855, "s": 8787, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 8882, "s": 8855, "text": "How to Start Learning DSA?" }, { "code": null, "e": 8925, "s": 8882, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 8992, "s": 8925, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 9042, "s": 8992, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 9071, "s": 9042, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 9107, "s": 9071, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 9157, "s": 9107, "text": "A program to check if a binary tree is BST or not" } ]
C++ Program to Find All Roots of a Quadratic Equation
A quadratic equation is in the form ax2 + bx + c. The roots of the quadratic equation are given by the following formula − There are three cases − b2 < 4*a*c - The roots are not real i.e. they are complex b2 = 4*a*c - The roots are real and both roots are the same. b2 > 4*a*c - The roots are real and both roots are different The program to find the roots of a quadratic equation is given as follows. #include<iostream> #include<cmath> using namespace std; int main() { int a = 1, b = 2, c = 1; float discriminant, realPart, imaginaryPart, x1, x2; if (a == 0) { cout << "This is not a quadratic equation"; }else { discriminant = b*b - 4*a*c; if (discriminant > 0) { x1 = (-b + sqrt(discriminant)) / (2*a); x2 = (-b - sqrt(discriminant)) / (2*a); cout << "Roots are real and different." << endl; cout << "Root 1 = " << x1 << endl; cout << "Root 2 = " << x2 << endl; } else if (discriminant == 0) { cout << "Roots are real and same." << endl; x1 = (-b + sqrt(discriminant)) / (2*a); cout << "Root 1 = Root 2 =" << x1 << endl; }else { realPart = (float) -b/(2*a); imaginaryPart =sqrt(-discriminant)/(2*a); cout << "Roots are complex and different." << endl; cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" <<end; cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" <<end; } } return 0; } Roots are real and same. Root 1 = Root 2 =-1 In the above program, first the discriminant is calculated. If it is greater than 0, then both the roots are real and different. This is demonstrated by the following code snippet. if (discriminant > 0) { x1 = (-b + sqrt(discriminant)) / (2*a); x2 = (-b - sqrt(discriminant)) / (2*a); cout << "Roots are real and different." << endl; cout << "Root 1 = " << x1 << endl; cout << "Root 2 = " << x2 << endl; } If the discriminant is equal to 0, then both the roots are real and same. This is demonstrated by the following code snippet. else if (discriminant == 0) { cout << "Roots are real and same." << endl; x1 = (-b + sqrt(discriminant)) / (2*a); cout << "Root 1 = Root 2 =" << x1 << endl; } If the discriminant is less than 0, then both the roots are complex and different. This is demonstrated by the following code snippet. else { realPart = (float) -b/(2*a); imaginaryPart =sqrt(-discriminant)/(2*a); cout << "Roots are complex and different." << endl; cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" << endl; cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl; }
[ { "code": null, "e": 1185, "s": 1062, "text": "A quadratic equation is in the form ax2 + bx + c. The roots of the quadratic equation are given by the following formula −" }, { "code": null, "e": 1209, "s": 1185, "text": "There are three cases −" }, { "code": null, "e": 1267, "s": 1209, "text": "b2 < 4*a*c - The roots are not real i.e. they are complex" }, { "code": null, "e": 1328, "s": 1267, "text": "b2 = 4*a*c - The roots are real and both roots are the same." }, { "code": null, "e": 1389, "s": 1328, "text": "b2 > 4*a*c - The roots are real and both roots are different" }, { "code": null, "e": 1464, "s": 1389, "text": "The program to find the roots of a quadratic equation is given as follows." }, { "code": null, "e": 2549, "s": 1464, "text": "#include<iostream>\n#include<cmath>\nusing namespace std;\nint main() {\n int a = 1, b = 2, c = 1;\n float discriminant, realPart, imaginaryPart, x1, x2;\n if (a == 0) {\n cout << \"This is not a quadratic equation\";\n }else {\n discriminant = b*b - 4*a*c;\n if (discriminant > 0) {\n x1 = (-b + sqrt(discriminant)) / (2*a);\n x2 = (-b - sqrt(discriminant)) / (2*a);\n cout << \"Roots are real and different.\" << endl;\n cout << \"Root 1 = \" << x1 << endl;\n cout << \"Root 2 = \" << x2 << endl;\n } else if (discriminant == 0) {\n cout << \"Roots are real and same.\" << endl;\n x1 = (-b + sqrt(discriminant)) / (2*a);\n cout << \"Root 1 = Root 2 =\" << x1 << endl;\n }else {\n realPart = (float) -b/(2*a);\n imaginaryPart =sqrt(-discriminant)/(2*a);\n cout << \"Roots are complex and different.\" << endl;\n cout << \"Root 1 = \" << realPart << \" + \" << imaginaryPart << \"i\" <<end;\n cout << \"Root 2 = \" << realPart << \" - \" << imaginaryPart << \"i\" <<end;\n }\n }\n return 0;\n}" }, { "code": null, "e": 2594, "s": 2549, "text": "Roots are real and same.\nRoot 1 = Root 2 =-1" }, { "code": null, "e": 2723, "s": 2594, "text": "In the above program, first the discriminant is calculated. If it is greater than 0, then both the roots are real and different." }, { "code": null, "e": 2775, "s": 2723, "text": "This is demonstrated by the following code snippet." }, { "code": null, "e": 3015, "s": 2775, "text": "if (discriminant > 0) {\n x1 = (-b + sqrt(discriminant)) / (2*a);\n x2 = (-b - sqrt(discriminant)) / (2*a);\n cout << \"Roots are real and different.\" << endl;\n cout << \"Root 1 = \" << x1 << endl;\n cout << \"Root 2 = \" << x2 << endl;\n}" }, { "code": null, "e": 3141, "s": 3015, "text": "If the discriminant is equal to 0, then both the roots are real and same. This is demonstrated by the following code snippet." }, { "code": null, "e": 3309, "s": 3141, "text": "else if (discriminant == 0) {\n cout << \"Roots are real and same.\" << endl;\n x1 = (-b + sqrt(discriminant)) / (2*a);\n cout << \"Root 1 = Root 2 =\" << x1 << endl;\n}" }, { "code": null, "e": 3444, "s": 3309, "text": "If the discriminant is less than 0, then both the roots are complex and different. This is demonstrated by the following code snippet." }, { "code": null, "e": 3739, "s": 3444, "text": "else {\n realPart = (float) -b/(2*a);\n imaginaryPart =sqrt(-discriminant)/(2*a);\n cout << \"Roots are complex and different.\" << endl;\n cout << \"Root 1 = \" << realPart << \" + \" << imaginaryPart << \"i\" << endl;\n cout << \"Root 2 = \" << realPart << \" - \" << imaginaryPart << \"i\" << endl;\n}" } ]
How to Read Text File Into List in Python? - GeeksforGeeks
19 Dec, 2021 In this article, we are going to see how to read text files into lists in Python. File for demonstration: We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of the line(‘/n’) with ‘ ‘ and split the text further when ‘.’ is seen using the split() and replace() functions. read(): The read bytes are returned as a string. Reads n bytes, or the full file if no n is given. Syntax: fileobject.read(size) split(): The split() method creates a list from a string. The separator can be specified; the default separator is any whitespace. Syntax: string.split(separator, maxsplit) replace(): The replace() method substitutes one phrase for another. Syntax: string.replace(previous_value, value_to_be_replaced_with, count) Code: Python3 # opening the file in read modemy_file = open("file1.txt", "r") # reading the filedata = my_file.read() # replacing end of line('/n') with ' ' and# splitting the text it further when '.' is seen.data_into_list = data.replace('\n', ' ').split(".") # printing the dataprint(data_into_list)my_file.close() Output: ['Hello geeks Welcome to geeksforgeeks'] The same process as before but we don’t replace any string here. Python3 # opening the file in read modemy_file = open("file1.txt", "r") # reading the filedata = my_file.read() # replacing end splitting the text # when newline ('\n') is seen.data_into_list = data.split("\n")print(data_into_list)my_file.close() Output: ['Hello geeks', 'Welcome to geeksforgeeks'] Picked python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n19 Dec, 2021" }, { "code": null, "e": 23983, "s": 23901, "text": "In this article, we are going to see how to read text files into lists in Python." }, { "code": null, "e": 24007, "s": 23983, "text": "File for demonstration:" }, { "code": null, "e": 24268, "s": 24007, "text": "We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of the line(‘/n’) with ‘ ‘ and split the text further when ‘.’ is seen using the split() and replace() functions. " }, { "code": null, "e": 24367, "s": 24268, "text": "read(): The read bytes are returned as a string. Reads n bytes, or the full file if no n is given." }, { "code": null, "e": 24397, "s": 24367, "text": "Syntax: fileobject.read(size)" }, { "code": null, "e": 24528, "s": 24397, "text": "split(): The split() method creates a list from a string. The separator can be specified; the default separator is any whitespace." }, { "code": null, "e": 24570, "s": 24528, "text": "Syntax: string.split(separator, maxsplit)" }, { "code": null, "e": 24638, "s": 24570, "text": "replace(): The replace() method substitutes one phrase for another." }, { "code": null, "e": 24711, "s": 24638, "text": "Syntax: string.replace(previous_value, value_to_be_replaced_with, count)" }, { "code": null, "e": 24717, "s": 24711, "text": "Code:" }, { "code": null, "e": 24725, "s": 24717, "text": "Python3" }, { "code": "# opening the file in read modemy_file = open(\"file1.txt\", \"r\") # reading the filedata = my_file.read() # replacing end of line('/n') with ' ' and# splitting the text it further when '.' is seen.data_into_list = data.replace('\\n', ' ').split(\".\") # printing the dataprint(data_into_list)my_file.close()", "e": 25031, "s": 24725, "text": null }, { "code": null, "e": 25039, "s": 25031, "text": "Output:" }, { "code": null, "e": 25080, "s": 25039, "text": "['Hello geeks Welcome to geeksforgeeks']" }, { "code": null, "e": 25145, "s": 25080, "text": "The same process as before but we don’t replace any string here." }, { "code": null, "e": 25153, "s": 25145, "text": "Python3" }, { "code": "# opening the file in read modemy_file = open(\"file1.txt\", \"r\") # reading the filedata = my_file.read() # replacing end splitting the text # when newline ('\\n') is seen.data_into_list = data.split(\"\\n\")print(data_into_list)my_file.close()", "e": 25394, "s": 25153, "text": null }, { "code": null, "e": 25402, "s": 25394, "text": "Output:" }, { "code": null, "e": 25446, "s": 25402, "text": "['Hello geeks', 'Welcome to geeksforgeeks']" }, { "code": null, "e": 25453, "s": 25446, "text": "Picked" }, { "code": null, "e": 25474, "s": 25453, "text": "python-file-handling" }, { "code": null, "e": 25481, "s": 25474, "text": "Python" }, { "code": null, "e": 25579, "s": 25481, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25588, "s": 25579, "text": "Comments" }, { "code": null, "e": 25601, "s": 25588, "text": "Old Comments" }, { "code": null, "e": 25633, "s": 25601, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25689, "s": 25633, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25731, "s": 25689, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25773, "s": 25731, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25809, "s": 25773, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25831, "s": 25809, "text": "Defaultdict in Python" }, { "code": null, "e": 25870, "s": 25831, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25897, "s": 25870, "text": "Python Classes and Objects" }, { "code": null, "e": 25928, "s": 25897, "text": "Python | os.path.join() method" } ]
Plotly - Box Plot Violin Plot and Contour Plot
This chapter focusses on detail understanding about various plots including box plot, violin plot, contour plot and quiver plot. Initially, we will begin with the Box Plot follow. A box plot displays a summary of a set of data containing the minimum, first quartile, median, third quartile, and maximum. In a box plot, we draw a box from the first quartile to the third quartile. A vertical line goes through the box at the median. The lines extending vertically from the boxes indicating variability outside the upper and lower quartiles are called whiskers. Hence, box plot is also known as box and whisker plot. The whiskers go from each quartile to the minimum or maximum. To draw Box chart, we have to use go.Box() function. The data series can be assigned to x or y parameter. Accordingly, the box plot will be drawn horizontally or vertically. In following example, sales figures of a certain company in its various branches is converted in horizontal box plot. It shows the median of minimum and maximum value. trace1 = go.Box(y = [1140,1460,489,594,502,508,370,200]) data = [trace1] fig = go.Figure(data) iplot(fig) The output of the same will be as follows − The go.Box() function can be given various other parameters to control the appearance and behaviour of box plot. One such is boxmean parameter. The boxmean parameter is set to true by default. As a result, the mean of the boxes' underlying distribution is drawn as a dashed line inside the boxes. If it is set to sd, the standard deviation of the distribution is also drawn. The boxpoints parameter is by default equal to "outliers". Only the sample points lying outside the whiskers are shown. If "suspectedoutliers", the outlier points are shown and points either less than 4"Q1-3"Q3 or greater than 4"Q3-3"Q1 are highlighted. If "False", only the box(es) are shown with no sample points. In the following example, the box trace is drawn with standard deviation and outlier points. trc = go.Box( y = [ 0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15, 8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25 ], boxpoints = 'suspectedoutliers', boxmean = 'sd' ) data = [trc] fig = go.Figure(data) iplot(fig) The output of the same is stated below − Violin plots are similar to box plots, except that they also show the probability density of the data at different values. Violin plots will include a marker for the median of the data and a box indicating the interquartile range, as in standard box plots. Overlaid on this box plot is a kernel density estimation. Like box plots, violin plots are used to represent comparison of a variable distribution (or sample distribution) across different "categories". A violin plot is more informative than a plain box plot. In fact, while a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data. Violin trace object is returned by go.Violin() function in graph_objects module. In order to display underlying box plot, the boxplot_visible attribute is set to True. Similarly, by setting meanline_visible property to true, a line corresponding to the sample's mean is shown inside the violins. Following example demonstrates how Violin plot is displayed using plotly’s functionality. import numpy as np np.random.seed(10) c1 = np.random.normal(100, 10, 200) c2 = np.random.normal(80, 30, 200) trace1 = go.Violin(y = c1, meanline_visible = True) trace2 = go.Violin(y = c2, box_visible = True) data = [trace1, trace2] fig = go.Figure(data = data) iplot(fig) The output is as follows − A 2D contour plot shows the contour lines of a 2D numerical array z, i.e. interpolated lines of isovalues of z. A contour line of a function of two variables is a curve along which the function has a constant value, so that the curve joins points of equal value. A contour plot is appropriate if you want to see how some value Z changes as a function of two inputs, X and Y such that Z = f(X,Y). A contour line or isoline of a function of two variables is a curve along which the function has a constant value. The independent variables x and y are usually restricted to a regular grid called meshgrid. The numpy.meshgrid creates a rectangular grid out of an array of x values and an array of y values. Let us first create data values for x, y and z using linspace() function from Numpy library. We create a meshgrid from x and y values and obtain z array consisting of square root of x2+y2 We have go.Contour() function in graph_objects module which takes x,y and z attributes. Following code snippet displays contour plot of x, y and z values computed as above. import numpy as np xlist = np.linspace(-3.0, 3.0, 100) ylist = np.linspace(-3.0, 3.0, 100) X, Y = np.meshgrid(xlist, ylist) Z = np.sqrt(X**2 + Y**2) trace = go.Contour(x = xlist, y = ylist, z = Z) data = [trace] fig = go.Figure(data) iplot(fig) The output is as follows − The contour plot can be customized by one or more of following parameters − Transpose (boolean) − Transposes the z data. Transpose (boolean) − Transposes the z data. If xtype (or ytype) equals "array", x/y coordinates are given by "x"/"y". If "scaled", x coordinates are given by "x0" and "dx". The connectgaps parameter determines whether or not gaps in the z data are filled in. The connectgaps parameter determines whether or not gaps in the z data are filled in. Default value of ncontours parameter is 15. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is "True". Default value of ncontours parameter is 15. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is "True". Contours type is by default: "levels" so the data is represented as a contour plot with multiple levels displayed. If constrain, the data is represented as constraints with the invalid region shaded as specified by the operation and value parameters. showlines − Determines whether or not the contour lines are drawn. zauto is True by default and determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `False` when `zmin` and `zmax` are set by the user. Quiver plot is also known as velocity plot. It displays velocity vectors as arrows with components (u,v) at the points (x,y). In order to draw Quiver plot, we will use create_quiver() function defined in figure_factory module in Plotly. Plotly's Python API contains a figure factory module which includes many wrapper functions that create unique chart types that are not yet included in plotly.js, Plotly's open-source graphing library. The create_quiver() function accepts following parameters − x − x coordinates of the arrow locations x − x coordinates of the arrow locations y − y coordinates of the arrow locations y − y coordinates of the arrow locations u − x components of the arrow vectors u − x components of the arrow vectors v − y components of the arrow vectors v − y components of the arrow vectors scale − scales size of the arrows scale − scales size of the arrows arrow_scale − length of arrowhead. arrow_scale − length of arrowhead. angle − angle of arrowhead. angle − angle of arrowhead. Following code renders a simple quiver plot in Jupyter notebook − import plotly.figure_factory as ff import numpy as np x,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25)) z = x*np.exp(-x**2 - y**2) v, u = np.gradient(z, .2, .2) # Create quiver figure fig = ff.create_quiver(x, y, u, v, scale = .25, arrow_scale = .4, name = 'quiver', line = dict(width = 1)) iplot(fig) Output of the code is as follows − 12 Lectures 53 mins Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2540, "s": 2360, "text": "This chapter focusses on detail understanding about various plots including box plot, violin plot, contour plot and quiver plot. Initially, we will begin with the Box Plot follow." }, { "code": null, "e": 3037, "s": 2540, "text": "A box plot displays a summary of a set of data containing the minimum, first quartile, median, third quartile, and maximum. In a box plot, we draw a box from the first quartile to the third quartile. A vertical line goes through the box at the median. The lines extending vertically from the boxes indicating variability outside the upper and lower quartiles are called whiskers. Hence, box plot is also known as box and whisker plot. The whiskers go from each quartile to the minimum or maximum." }, { "code": null, "e": 3379, "s": 3037, "text": "To draw Box chart, we have to use go.Box() function. The data series can be assigned to x or y parameter. Accordingly, the box plot will be drawn horizontally or vertically. In following example, sales figures of a certain company in its various branches is converted in horizontal box plot. It shows the median of minimum and maximum value." }, { "code": null, "e": 3485, "s": 3379, "text": "trace1 = go.Box(y = [1140,1460,489,594,502,508,370,200])\ndata = [trace1]\nfig = go.Figure(data)\niplot(fig)" }, { "code": null, "e": 3529, "s": 3485, "text": "The output of the same will be as follows −" }, { "code": null, "e": 3673, "s": 3529, "text": "The go.Box() function can be given various other parameters to control the appearance and behaviour of box plot. One such is boxmean parameter." }, { "code": null, "e": 3904, "s": 3673, "text": "The boxmean parameter is set to true by default. As a result, the mean of the boxes' underlying distribution is drawn as a dashed line inside the boxes. If it is set to sd, the standard deviation of the distribution is also drawn." }, { "code": null, "e": 4220, "s": 3904, "text": "The boxpoints parameter is by default equal to \"outliers\". Only the sample points lying outside the whiskers are shown. If \"suspectedoutliers\", the outlier points are shown and points either less than 4\"Q1-3\"Q3 or greater than 4\"Q3-3\"Q1 are highlighted. If \"False\", only the box(es) are shown with no sample points." }, { "code": null, "e": 4313, "s": 4220, "text": "In the following example, the box trace is drawn with standard deviation and outlier points." }, { "code": null, "e": 4593, "s": 4313, "text": "trc = go.Box(\n y = [\n 0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,\n 8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25\n ],\n boxpoints = 'suspectedoutliers', boxmean = 'sd'\n)\ndata = [trc]\nfig = go.Figure(data)\niplot(fig)" }, { "code": null, "e": 4634, "s": 4593, "text": "The output of the same is stated below −" }, { "code": null, "e": 5094, "s": 4634, "text": "Violin plots are similar to box plots, except that they also show the probability density of the data at different values. Violin plots will include a marker for the median of the data and a box indicating the interquartile range, as in standard box plots. Overlaid on this box plot is a kernel density estimation. Like box plots, violin plots are used to represent comparison of a variable distribution (or sample distribution) across different \"categories\"." }, { "code": null, "e": 5310, "s": 5094, "text": "A violin plot is more informative than a plain box plot. In fact, while a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data." }, { "code": null, "e": 5606, "s": 5310, "text": "Violin trace object is returned by go.Violin() function in graph_objects module. In order to display underlying box plot, the boxplot_visible attribute is set to True. Similarly, by setting meanline_visible property to true, a line corresponding to the sample's mean is shown inside the violins." }, { "code": null, "e": 5696, "s": 5606, "text": "Following example demonstrates how Violin plot is displayed using plotly’s functionality." }, { "code": null, "e": 5968, "s": 5696, "text": "import numpy as np\nnp.random.seed(10)\nc1 = np.random.normal(100, 10, 200)\nc2 = np.random.normal(80, 30, 200)\ntrace1 = go.Violin(y = c1, meanline_visible = True)\ntrace2 = go.Violin(y = c2, box_visible = True)\ndata = [trace1, trace2]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 5995, "s": 5968, "text": "The output is as follows −" }, { "code": null, "e": 6258, "s": 5995, "text": "A 2D contour plot shows the contour lines of a 2D numerical array z, i.e. interpolated lines of isovalues of z. A contour line of a function of two variables is a curve along which the function has a constant value, so that the curve joins points of equal value." }, { "code": null, "e": 6506, "s": 6258, "text": "A contour plot is appropriate if you want to see how some value Z changes as a function of two inputs, X and Y such that Z = f(X,Y). A contour line or isoline of a function of two variables is a curve along which the function has a constant value." }, { "code": null, "e": 6698, "s": 6506, "text": "The independent variables x and y are usually restricted to a regular grid called meshgrid. The numpy.meshgrid creates a rectangular grid out of an array of x values and an array of y values." }, { "code": null, "e": 6886, "s": 6698, "text": "Let us first create data values for x, y and z using linspace() function from Numpy library. We create a meshgrid from x and y values and obtain z array consisting of square root of x2+y2" }, { "code": null, "e": 7059, "s": 6886, "text": "We have go.Contour() function in graph_objects module which takes x,y and z attributes. Following code snippet displays contour plot of x, y and z values computed as above." }, { "code": null, "e": 7304, "s": 7059, "text": "import numpy as np\nxlist = np.linspace(-3.0, 3.0, 100)\nylist = np.linspace(-3.0, 3.0, 100)\nX, Y = np.meshgrid(xlist, ylist)\nZ = np.sqrt(X**2 + Y**2)\ntrace = go.Contour(x = xlist, y = ylist, z = Z)\ndata = [trace]\nfig = go.Figure(data)\niplot(fig)" }, { "code": null, "e": 7331, "s": 7304, "text": "The output is as follows −" }, { "code": null, "e": 7407, "s": 7331, "text": "The contour plot can be customized by one or more of following parameters −" }, { "code": null, "e": 7452, "s": 7407, "text": "Transpose (boolean) − Transposes the z data." }, { "code": null, "e": 7497, "s": 7452, "text": "Transpose (boolean) − Transposes the z data." }, { "code": null, "e": 7626, "s": 7497, "text": "If xtype (or ytype) equals \"array\", x/y coordinates are given by \"x\"/\"y\". If \"scaled\", x coordinates are given by \"x0\" and \"dx\"." }, { "code": null, "e": 7712, "s": 7626, "text": "The connectgaps parameter determines whether or not gaps in the z data are filled in." }, { "code": null, "e": 7798, "s": 7712, "text": "The connectgaps parameter determines whether or not gaps in the z data are filled in." }, { "code": null, "e": 8002, "s": 7798, "text": "Default value of ncontours parameter is 15. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is \"True\"." }, { "code": null, "e": 8206, "s": 8002, "text": "Default value of ncontours parameter is 15. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is \"True\"." }, { "code": null, "e": 8457, "s": 8206, "text": "Contours type is by default: \"levels\" so the data is represented as a contour plot with multiple levels displayed. If constrain, the data is represented as constraints with the invalid region shaded as specified by the operation and value parameters." }, { "code": null, "e": 8524, "s": 8457, "text": "showlines − Determines whether or not the contour lines are drawn." }, { "code": null, "e": 8756, "s": 8524, "text": "zauto is True by default and determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `False` when `zmin` and `zmax` are set by the user." }, { "code": null, "e": 8993, "s": 8756, "text": "Quiver plot is also known as velocity plot. It displays velocity vectors as arrows with components (u,v) at the points (x,y). In order to draw Quiver plot, we will use create_quiver() function defined in figure_factory module in Plotly." }, { "code": null, "e": 9194, "s": 8993, "text": "Plotly's Python API contains a figure factory module which includes many wrapper functions that create unique chart types that are not yet included in plotly.js, Plotly's open-source graphing library." }, { "code": null, "e": 9254, "s": 9194, "text": "The create_quiver() function accepts following parameters −" }, { "code": null, "e": 9295, "s": 9254, "text": "x − x coordinates of the arrow locations" }, { "code": null, "e": 9336, "s": 9295, "text": "x − x coordinates of the arrow locations" }, { "code": null, "e": 9377, "s": 9336, "text": "y − y coordinates of the arrow locations" }, { "code": null, "e": 9418, "s": 9377, "text": "y − y coordinates of the arrow locations" }, { "code": null, "e": 9456, "s": 9418, "text": "u − x components of the arrow vectors" }, { "code": null, "e": 9494, "s": 9456, "text": "u − x components of the arrow vectors" }, { "code": null, "e": 9532, "s": 9494, "text": "v − y components of the arrow vectors" }, { "code": null, "e": 9570, "s": 9532, "text": "v − y components of the arrow vectors" }, { "code": null, "e": 9604, "s": 9570, "text": "scale − scales size of the arrows" }, { "code": null, "e": 9638, "s": 9604, "text": "scale − scales size of the arrows" }, { "code": null, "e": 9673, "s": 9638, "text": "arrow_scale − length of arrowhead." }, { "code": null, "e": 9708, "s": 9673, "text": "arrow_scale − length of arrowhead." }, { "code": null, "e": 9736, "s": 9708, "text": "angle − angle of arrowhead." }, { "code": null, "e": 9764, "s": 9736, "text": "angle − angle of arrowhead." }, { "code": null, "e": 9830, "s": 9764, "text": "Following code renders a simple quiver plot in Jupyter notebook −" }, { "code": null, "e": 10146, "s": 9830, "text": "import plotly.figure_factory as ff\nimport numpy as np\nx,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25))\nz = x*np.exp(-x**2 - y**2)\nv, u = np.gradient(z, .2, .2)\n\n# Create quiver figure\nfig = ff.create_quiver(x, y, u, v,\nscale = .25, arrow_scale = .4,\nname = 'quiver', line = dict(width = 1))\niplot(fig)" }, { "code": null, "e": 10181, "s": 10146, "text": "Output of the code is as follows −" }, { "code": null, "e": 10213, "s": 10181, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 10233, "s": 10213, "text": " Pranjal Srivastava" }, { "code": null, "e": 10240, "s": 10233, "text": " Print" }, { "code": null, "e": 10251, "s": 10240, "text": " Add Notes" } ]
Shuffle or Randomize a list in Java
To shuffle a list in Java, the code is as follows − Live Demo import java.util.*; public class Demo{ public static void main(String[] args){ ArrayList<String> my_list = new ArrayList<String>(); my_list.add("Hello"); my_list.add(","); my_list.add("this"); my_list.add("is"); my_list.add("a"); my_list.add("sample"); System.out.println("The original list is : \n" + my_list); Collections.shuffle(my_list); System.out.println("\n The shuffled list is : \n" + my_list); } } The original list is : [Hello, ,, this, is, a, sample] The shuffled list is : [a, is, ,, Hello, this, sample] A class named Demo contains the main function. Here, an array list is defined and elements are added to the array list with the help of the ‘add’ function. The original list is printed, and then the ‘shuffle’ function is called on this array list. This way, the elements in the list will be shuffled and then printed on the screen.
[ { "code": null, "e": 1114, "s": 1062, "text": "To shuffle a list in Java, the code is as follows −" }, { "code": null, "e": 1125, "s": 1114, "text": " Live Demo" }, { "code": null, "e": 1599, "s": 1125, "text": "import java.util.*;\npublic class Demo{\n public static void main(String[] args){\n ArrayList<String> my_list = new ArrayList<String>();\n my_list.add(\"Hello\");\n my_list.add(\",\");\n my_list.add(\"this\");\n my_list.add(\"is\");\n my_list.add(\"a\");\n my_list.add(\"sample\");\n System.out.println(\"The original list is : \\n\" + my_list);\n Collections.shuffle(my_list);\n System.out.println(\"\\n The shuffled list is : \\n\" + my_list);\n }\n}" }, { "code": null, "e": 1709, "s": 1599, "text": "The original list is :\n[Hello, ,, this, is, a, sample]\nThe shuffled list is :\n[a, is, ,, Hello, this, sample]" }, { "code": null, "e": 2041, "s": 1709, "text": "A class named Demo contains the main function. Here, an array list is defined and elements are\nadded to the array list with the help of the ‘add’ function. The original list is printed, and then the\n‘shuffle’ function is called on this array list. This way, the elements in the list will be shuffled and\nthen printed on the screen." } ]
How to create an empty DataFrame in R ? - GeeksforGeeks
07 Apr, 2021 In this article, we are going to see how to create an empty DataFrame in R Programming Language. An empty data frame corresponds to the tabular structure where the axes are of length 0, that is it does not contain any data items. Method 1: We first create a matrix with both rows and columns and then convert it to a data frame A data frame and matrix are easily inter-convertible to each other, we first create a matrix with both rows and columns equivalent to 0 and then convert it to a data frame. The dimensions of the equivalent data frame are 0. Time complexity incurred in the creation of an empty data frame is O(1), since a constant time is required. R # creating a matrix with 0 rows # and columns mat = matrix(ncol = 0, nrow = 0) # converting the matrix to data # framedf=data.frame(mat)print ("Data Frame")print (df) # check for the dimensions of data # frameprint("Dimensions of data frame")dim(df) Output [1] "Data Frame" data frame with 0 columns and 0 rows [1] "Dimensions of data frame" [1] 0 0 The data frame can also be created using this method, without specifying the column types. Naming the columns of a data frame is also optional. An empty vector can be passed as an argument in the data.frame method. R # declaring an empty data frame with 5# columns and null entriesdf = data.frame(matrix( vector(), 0, 5, dimnames=list(c(), c("C1","C2","C3","C4","C5"))), stringsAsFactors=F) # printing the empty data frameprint ("Empty dataframe")print (df) Output [1] "Empty dataframe" [1] C1 C2 C3 C4 C5 <0 rows> (or 0-length row.names) Method 2: Assign the column with the empty vectors An empty data frame can also be created with or without specifying the column names and column types to the data values contained within it. data.frame() method can be used to create a data frame, and we can assign the column with the empty vectors. Column type checking with zero rows is supported by the data frames, where in we define the data type of each column prior to its creation. R # declaring an empty data framedf <- data.frame(Col1 = double(), Col2 = integer(), Col3 = character(), stringsAsFactors = FALSE) # print the data framestr(df) Output 'data.frame': 0 obs. of 3 variables: $ Col1: num $ Col2: int $ Col3: chr Column 1 of the data frame can support numeric values, Column 2 can support integer values, and Column 3 as character variable values. Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? How to Replace specific values in column in R DataFrame ? How to Split Column Into Multiple Columns in R DataFrame? Remove rows with NA in one column of R DataFrame How to filter R DataFrame by values in a column? Replace Specific Characters in String in R
[ { "code": null, "e": 24303, "s": 24275, "text": "\n07 Apr, 2021" }, { "code": null, "e": 24533, "s": 24303, "text": "In this article, we are going to see how to create an empty DataFrame in R Programming Language. An empty data frame corresponds to the tabular structure where the axes are of length 0, that is it does not contain any data items." }, { "code": null, "e": 24631, "s": 24533, "text": "Method 1: We first create a matrix with both rows and columns and then convert it to a data frame" }, { "code": null, "e": 24964, "s": 24631, "text": "A data frame and matrix are easily inter-convertible to each other, we first create a matrix with both rows and columns equivalent to 0 and then convert it to a data frame. The dimensions of the equivalent data frame are 0. Time complexity incurred in the creation of an empty data frame is O(1), since a constant time is required. " }, { "code": null, "e": 24966, "s": 24964, "text": "R" }, { "code": "# creating a matrix with 0 rows # and columns mat = matrix(ncol = 0, nrow = 0) # converting the matrix to data # framedf=data.frame(mat)print (\"Data Frame\")print (df) # check for the dimensions of data # frameprint(\"Dimensions of data frame\")dim(df)", "e": 25218, "s": 24966, "text": null }, { "code": null, "e": 25225, "s": 25218, "text": "Output" }, { "code": null, "e": 25318, "s": 25225, "text": "[1] \"Data Frame\"\ndata frame with 0 columns and 0 rows\n[1] \"Dimensions of data frame\"\n[1] 0 0" }, { "code": null, "e": 25534, "s": 25318, "text": "The data frame can also be created using this method, without specifying the column types. Naming the columns of a data frame is also optional. An empty vector can be passed as an argument in the data.frame method. " }, { "code": null, "e": 25536, "s": 25534, "text": "R" }, { "code": "# declaring an empty data frame with 5# columns and null entriesdf = data.frame(matrix( vector(), 0, 5, dimnames=list(c(), c(\"C1\",\"C2\",\"C3\",\"C4\",\"C5\"))), stringsAsFactors=F) # printing the empty data frameprint (\"Empty dataframe\")print (df)", "e": 25794, "s": 25536, "text": null }, { "code": null, "e": 25801, "s": 25794, "text": "Output" }, { "code": null, "e": 25875, "s": 25801, "text": "[1] \"Empty dataframe\"\n[1] C1 C2 C3 C4 C5\n<0 rows> (or 0-length row.names)" }, { "code": null, "e": 25926, "s": 25875, "text": "Method 2: Assign the column with the empty vectors" }, { "code": null, "e": 26317, "s": 25926, "text": "An empty data frame can also be created with or without specifying the column names and column types to the data values contained within it. data.frame() method can be used to create a data frame, and we can assign the column with the empty vectors. Column type checking with zero rows is supported by the data frames, where in we define the data type of each column prior to its creation. " }, { "code": null, "e": 26319, "s": 26317, "text": "R" }, { "code": "# declaring an empty data framedf <- data.frame(Col1 = double(), Col2 = integer(), Col3 = character(), stringsAsFactors = FALSE) # print the data framestr(df)", "e": 26527, "s": 26319, "text": null }, { "code": null, "e": 26534, "s": 26527, "text": "Output" }, { "code": null, "e": 26609, "s": 26534, "text": "'data.frame': 0 obs. of 3 variables:\n$ Col1: num\n$ Col2: int\n$ Col3: chr " }, { "code": null, "e": 26744, "s": 26609, "text": "Column 1 of the data frame can support numeric values, Column 2 can support integer values, and Column 3 as character variable values." }, { "code": null, "e": 26751, "s": 26744, "text": "Picked" }, { "code": null, "e": 26772, "s": 26751, "text": "R DataFrame-Programs" }, { "code": null, "e": 26784, "s": 26772, "text": "R-DataFrame" }, { "code": null, "e": 26795, "s": 26784, "text": "R Language" }, { "code": null, "e": 26806, "s": 26795, "text": "R Programs" }, { "code": null, "e": 26904, "s": 26806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26913, "s": 26904, "text": "Comments" }, { "code": null, "e": 26926, "s": 26913, "text": "Old Comments" }, { "code": null, "e": 26984, "s": 26926, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27036, "s": 26984, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27068, "s": 27036, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27120, "s": 27068, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27158, "s": 27120, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27216, "s": 27158, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27274, "s": 27216, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27323, "s": 27274, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 27372, "s": 27323, "text": "How to filter R DataFrame by values in a column?" } ]
C# | Get object at the top of the Stack - Peek operation - GeeksforGeeks
01 Feb, 2019 Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.Peek Method is used to returns the object at the top of the Stack<T> without removing it. This method is an O(1) operation. Properties: The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation. Stack accepts null as a valid value and allows duplicate elements. Syntax: object Peek(); Return Value: The Peek() method returns the last (top-most) value from the Stack<T> of type System.Object. Exception: Calling Peek() method on empty stack will throw InvalidOperationException. So always check for elements in the stack before retrieving elements using the Peek() method. Below given are some examples to understand the implementation in a better way. Example 1: // C# code to Get object at// the top of the Stackusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push("1st Element"); myStack.Push("2nd Element"); myStack.Push("3rd Element"); myStack.Push("4th Element"); myStack.Push("5th Element"); myStack.Push("6th Element"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine("Element at the top is : " + myStack.Peek()); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine("Element at the top is : " + myStack.Peek()); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); }} Output: Total number of elements in the Stack are : 6 Element at the top is : 6th Element Element at the top is : 6th Element Total number of elements in the Stack are : 6 Example 2: // C# code to Get object at// the top of the Stackusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of Integers Stack<int> myStack = new Stack<int>(); // Displaying the top element of Stack // without removing it from the Stack // Calling Peek() method on empty stack // will throw InvalidOperationException. Console.WriteLine("Element at the top is : " + myStack.Peek()); }} Runtime Error: Unhandled Exception:System.InvalidOperationException: Stack empty. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.peek?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Generic-Namespace CSharp-Generic-Stack CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24677, "s": 24302, "text": "Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.Peek Method is used to returns the object at the top of the Stack<T> without removing it. This method is an O(1) operation." }, { "code": null, "e": 24689, "s": 24677, "text": "Properties:" }, { "code": null, "e": 24867, "s": 24689, "text": "The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation." }, { "code": null, "e": 25089, "s": 24867, "text": "If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation." }, { "code": null, "e": 25156, "s": 25089, "text": "Stack accepts null as a valid value and allows duplicate elements." }, { "code": null, "e": 25164, "s": 25156, "text": "Syntax:" }, { "code": null, "e": 25181, "s": 25164, "text": "object Peek(); \n" }, { "code": null, "e": 25288, "s": 25181, "text": "Return Value: The Peek() method returns the last (top-most) value from the Stack<T> of type System.Object." }, { "code": null, "e": 25468, "s": 25288, "text": "Exception: Calling Peek() method on empty stack will throw InvalidOperationException. So always check for elements in the stack before retrieving elements using the Peek() method." }, { "code": null, "e": 25548, "s": 25468, "text": "Below given are some examples to understand the implementation in a better way." }, { "code": null, "e": 25559, "s": 25548, "text": "Example 1:" }, { "code": "// C# code to Get object at// the top of the Stackusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push(\"1st Element\"); myStack.Push(\"2nd Element\"); myStack.Push(\"3rd Element\"); myStack.Push(\"4th Element\"); myStack.Push(\"5th Element\"); myStack.Push(\"6th Element\"); // Displaying the count of elements // contained in the Stack Console.Write(\"Total number of elements in the Stack are : \"); Console.WriteLine(myStack.Count); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine(\"Element at the top is : \" + myStack.Peek()); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine(\"Element at the top is : \" + myStack.Peek()); // Displaying the count of elements // contained in the Stack Console.Write(\"Total number of elements in the Stack are : \"); Console.WriteLine(myStack.Count); }}", "e": 26797, "s": 25559, "text": null }, { "code": null, "e": 26805, "s": 26797, "text": "Output:" }, { "code": null, "e": 26970, "s": 26805, "text": "Total number of elements in the Stack are : 6\nElement at the top is : 6th Element\nElement at the top is : 6th Element\nTotal number of elements in the Stack are : 6\n" }, { "code": null, "e": 26981, "s": 26970, "text": "Example 2:" }, { "code": "// C# code to Get object at// the top of the Stackusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of Integers Stack<int> myStack = new Stack<int>(); // Displaying the top element of Stack // without removing it from the Stack // Calling Peek() method on empty stack // will throw InvalidOperationException. Console.WriteLine(\"Element at the top is : \" + myStack.Peek()); }}", "e": 27497, "s": 26981, "text": null }, { "code": null, "e": 27512, "s": 27497, "text": "Runtime Error:" }, { "code": null, "e": 27579, "s": 27512, "text": "Unhandled Exception:System.InvalidOperationException: Stack empty." }, { "code": null, "e": 27590, "s": 27579, "text": "Reference:" }, { "code": null, "e": 27688, "s": 27590, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.peek?view=netframework-4.7.2" }, { "code": null, "e": 27717, "s": 27688, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 27742, "s": 27717, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 27763, "s": 27742, "text": "CSharp-Generic-Stack" }, { "code": null, "e": 27777, "s": 27763, "text": "CSharp-method" }, { "code": null, "e": 27780, "s": 27777, "text": "C#" }, { "code": null, "e": 27878, "s": 27780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27896, "s": 27878, "text": "Destructors in C#" }, { "code": null, "e": 27919, "s": 27896, "text": "Extension Method in C#" }, { "code": null, "e": 27947, "s": 27919, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27987, "s": 27947, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28030, "s": 27987, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28052, "s": 28030, "text": "Partial Classes in C#" }, { "code": null, "e": 28069, "s": 28052, "text": "C# | Inheritance" }, { "code": null, "e": 28085, "s": 28069, "text": "C# | List Class" }, { "code": null, "e": 28135, "s": 28085, "text": "Difference between Hashtable and Dictionary in C#" } ]
Level of a Node in Binary Tree | Practice | GeeksforGeeks
Given a Binary Tree and a target key you need to find the level of target key in the given Binary Tree. Note: The level of the root node is 1. 3 / \ 2 5 / \ 1 4 Key: 4 Level: 3 Note: if no such key exists then return 0. Example 1: Input: 1 / \ 2 3 target = 4 Output: 0 Example 2: Input: 3 / \ 2 5 / \ 1 4 target = 4 Output: 3 Your Task: You don't have to take input. Just complete the function getLevel() that takes a node and a target as parameters and returns the level of the target value. Expected Time Complexity: O(N). Expected Auxiliary Space: O(H). Note: H is the height of the tree and this space is used implicitly for recursion stack. Constraints: 1 <= Number of nodes<= 105 1 <= Data of a node<= 105 1 <= Target <= 105 0 ravikishan6242 months ago JAVA Solution Just an simple approach similar to preOrder traversal, in place of printing data we need to have variable (int) which can count the level that's it. class Solution{ /* Returns level of given data value */ int getLevel(Node node, int data) { return levelGet(node,data,1); } int levelGet(Node node, int data, int level){ if(node==null) return 0; if(node.data==data) return level; int downLevel=levelGet(node.left,data,level+1); if(downLevel!=0) return downLevel; downLevel=levelGet(node.right,data,level+1); return downLevel; } } 0 hamidnourashraf2 months ago class Solution: def getLevel(self, root, target): level = 1 q = [(root, level)] while len(q) > 0: node, level = q.pop(0) if node.data == target: return level if node.left: q.append((node.left, level+1)) if node.right: q.append((node.right, level+1)) return 0 0 ishnoorsinghsethi3 months ago C++ solution using Level Order Traversal int getLevel(struct Node *node, int target) { int ans; int level = 1; queue<Node * > q; q.push(node); while(q.size()){ int count = q.size(); while(count--){ Node * p = q.front(); q.pop(); if(p->data == target) return level; if(p->left) q.push(p->left); if(p->right) q.push(p->right); } level++; } return 0; } 0 abhishekvicky123453 months ago /*Java Solution*/ class Solution{ public int flag=0; public void check(Node root,int data,int level) { if(root.data==data) flag=level; if(root.left!=null) check(root.left,data,level+1); if(root.right!=null) check(root.right,data,level+1); } public int getLevel(Node node, int data) { check(node,data,1); return flag; } } 0 shiva10903 months ago int ans = 0; void nodelevel(struct Node* root , int x , int level) { if(root == NULL)return; if(root->data == x){ ans = level; return; } nodelevel(root->left , x , level+1); nodelevel(root->right , x , level+1); } int getLevel(struct Node *node, int target) { //code here nodelevel(node , target , 1); return ans; } 0 mayank20213 months ago C++ int getLevel(struct Node *node, int target) { if(node==NULL) return 0; else if(node->data==target) return 1; else if(getLevel(node->left, target) || getLevel(node->right, target)) return (1+max(getLevel(node->left, target), getLevel(node->right, target))); else return 0; } +1 codingprep213 months ago JAVA class Solution { int getLevel(Node node, int data) { if (node == null) return 0; if (node.data == data) return 1; int result = getLevel(node.right, data); if (result == 0) { result = getLevel(node.left, data); } return result == 0 ? 0 : ++result; } } 0 snipperwolf3 months ago class Solution: def getLevel(self, root,target): ''' :param root: root of given tree. :param target: target to find level :return: LEVEL NO ''' depth=1 l=[] level(root,target,depth,l) if len(l)==0: return 0 else: return l[-1]def level(root,target,depth,l): if root is None: return 0 if root.data==target: l.append(depth) level(root.left,target,depth+1,l) level(root.right,target,depth+1,l) 0 emmanueluluabuike3 months ago A simple java solution with explanations int level = 0; int getLevel(Node node, int data){ // The search begins from 1 because we are counting (root node) from 1 return search(node, data, 1); } int search(Node node, int search, int h){ // Checks if the initial is null or first root node is equal // to search, return level = 0 if(node == null || (search == node.data && h == 0)) { return 0; } // Just like inOrder travesal, search nodes on the left, visit the root, // and search nodes on right while incrementing the height // Whilst performing Inorder traversal, we checking each node data to see // if it is equal to search and then return the level search(node.left, search, h + 1); // And then checking each node to see it if(node.data == search){ level = h; } search(node.right, search, h + 1); return level; } +1 17vineet3 months ago int getLevel(Node node, int data) { int level = 1 ; Queue<Node> q = new LinkedList<Node>() ; q.add(node) ; while(true) { int size = q.size() ; if(size == 0) break ; while(size>0) { Node root = q.poll() ; if(root.data == data) return level ; if(root.left != null) q.add(root.left) ; if(root.right != null) q.add(root.right) ; size-- ; } level++ ; } return 0 ; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 342, "s": 238, "text": "Given a Binary Tree and a target key you need to find the level of target key in the given Binary Tree." }, { "code": null, "e": 381, "s": 342, "text": "Note: The level of the root node is 1." }, { "code": null, "e": 468, "s": 381, "text": " 3\n / \\\n 2 5\n / \\\n 1 4\nKey: 4\nLevel: 3 " }, { "code": null, "e": 511, "s": 468, "text": "Note: if no such key exists then return 0." }, { "code": null, "e": 522, "s": 511, "text": "Example 1:" }, { "code": null, "e": 587, "s": 522, "text": "Input:\n 1\n / \\\n 2 3\ntarget = 4\nOutput: 0\n\n" }, { "code": null, "e": 598, "s": 587, "text": "Example 2:" }, { "code": null, "e": 686, "s": 598, "text": "Input:\n 3\n / \\\n 2 5\n / \\\n 1 4\ntarget = 4\nOutput: 3\n" }, { "code": null, "e": 855, "s": 686, "text": "Your Task:\n You don't have to take input. Just complete the function getLevel() that takes a node and a target as parameters and returns the level of the target value. " }, { "code": null, "e": 1008, "s": 855, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(H).\nNote: H is the height of the tree and this space is used implicitly for recursion stack." }, { "code": null, "e": 1093, "s": 1008, "text": "Constraints:\n1 <= Number of nodes<= 105\n1 <= Data of a node<= 105\n1 <= Target <= 105" }, { "code": null, "e": 1095, "s": 1093, "text": "0" }, { "code": null, "e": 1121, "s": 1095, "text": "ravikishan6242 months ago" }, { "code": null, "e": 1135, "s": 1121, "text": "JAVA Solution" }, { "code": null, "e": 1286, "s": 1137, "text": "Just an simple approach similar to preOrder traversal, in place of printing data we need to have variable (int) which can count the level that's it." }, { "code": null, "e": 1348, "s": 1288, "text": "class Solution{ /* Returns level of given data value */" }, { "code": null, "e": 1746, "s": 1348, "text": " int getLevel(Node node, int data) { return levelGet(node,data,1); } int levelGet(Node node, int data, int level){ if(node==null) return 0; if(node.data==data) return level; int downLevel=levelGet(node.left,data,level+1); if(downLevel!=0) return downLevel; downLevel=levelGet(node.right,data,level+1); return downLevel; } " }, { "code": null, "e": 1748, "s": 1746, "text": "}" }, { "code": null, "e": 1750, "s": 1748, "text": "0" }, { "code": null, "e": 1778, "s": 1750, "text": "hamidnourashraf2 months ago" }, { "code": null, "e": 2179, "s": 1778, "text": "class Solution:\n def getLevel(self, root, target):\n \n level = 1 \n q = [(root, level)]\n while len(q) > 0:\n node, level = q.pop(0)\n if node.data == target:\n return level\n if node.left:\n q.append((node.left, level+1))\n if node.right:\n q.append((node.right, level+1))\n return 0" }, { "code": null, "e": 2181, "s": 2179, "text": "0" }, { "code": null, "e": 2211, "s": 2181, "text": "ishnoorsinghsethi3 months ago" }, { "code": null, "e": 2252, "s": 2211, "text": "C++ solution using Level Order Traversal" }, { "code": null, "e": 2669, "s": 2252, "text": "int getLevel(struct Node *node, int target) { int ans; int level = 1; queue<Node * > q; q.push(node); while(q.size()){ int count = q.size(); while(count--){ Node * p = q.front(); q.pop(); if(p->data == target) return level; if(p->left) q.push(p->left); if(p->right) q.push(p->right); } level++; } return 0; }" }, { "code": null, "e": 2671, "s": 2669, "text": "0" }, { "code": null, "e": 2702, "s": 2671, "text": "abhishekvicky123453 months ago" }, { "code": null, "e": 2720, "s": 2702, "text": "/*Java Solution*/" }, { "code": null, "e": 3082, "s": 2720, "text": "class Solution{ public int flag=0; public void check(Node root,int data,int level) { if(root.data==data) flag=level; if(root.left!=null) check(root.left,data,level+1); if(root.right!=null) check(root.right,data,level+1); } public int getLevel(Node node, int data) { check(node,data,1); return flag; } }" }, { "code": null, "e": 3084, "s": 3082, "text": "0" }, { "code": null, "e": 3106, "s": 3084, "text": "shiva10903 months ago" }, { "code": null, "e": 3544, "s": 3106, "text": " int ans = 0;\n void nodelevel(struct Node* root , int x , int level)\n {\n if(root == NULL)return;\n \n if(root->data == x){\n ans = level;\n return;\n }\n \n nodelevel(root->left , x , level+1);\n nodelevel(root->right , x , level+1);\n }\n int getLevel(struct Node *node, int target)\n {\n \t//code here\n \tnodelevel(node , target , 1);\n \treturn ans;\n }" }, { "code": null, "e": 3546, "s": 3544, "text": "0" }, { "code": null, "e": 3569, "s": 3546, "text": "mayank20213 months ago" }, { "code": null, "e": 3888, "s": 3569, "text": "C++ int getLevel(struct Node *node, int target) { if(node==NULL) return 0; else if(node->data==target) return 1; else if(getLevel(node->left, target) || getLevel(node->right, target)) return (1+max(getLevel(node->left, target), getLevel(node->right, target))); else return 0; }" }, { "code": null, "e": 3891, "s": 3888, "text": "+1" }, { "code": null, "e": 3916, "s": 3891, "text": "codingprep213 months ago" }, { "code": null, "e": 4242, "s": 3916, "text": "JAVA\n\nclass Solution\n{\n int getLevel(Node node, int data) {\n if (node == null) return 0;\n if (node.data == data) return 1;\n int result = getLevel(node.right, data);\n if (result == 0) {\n result = getLevel(node.left, data);\n }\n return result == 0 ? 0 : ++result;\n } \n}" }, { "code": null, "e": 4244, "s": 4242, "text": "0" }, { "code": null, "e": 4268, "s": 4244, "text": "snipperwolf3 months ago" }, { "code": null, "e": 4766, "s": 4268, "text": "class Solution: def getLevel(self, root,target): ''' :param root: root of given tree. :param target: target to find level :return: LEVEL NO ''' depth=1 l=[] level(root,target,depth,l) if len(l)==0: return 0 else: return l[-1]def level(root,target,depth,l): if root is None: return 0 if root.data==target: l.append(depth) level(root.left,target,depth+1,l) level(root.right,target,depth+1,l)" }, { "code": null, "e": 4768, "s": 4766, "text": "0" }, { "code": null, "e": 4798, "s": 4768, "text": "emmanueluluabuike3 months ago" }, { "code": null, "e": 4839, "s": 4798, "text": "A simple java solution with explanations" }, { "code": null, "e": 5792, "s": 4839, "text": "int level = 0;\n int getLevel(Node node, int data){ \n // The search begins from 1 because we are counting (root node) from 1\n return search(node, data, 1);\n }\n \n int search(Node node, int search, int h){\n // Checks if the initial is null or first root node is equal\n // to search, return level = 0\n if(node == null || (search == node.data && h == 0)) {\n return 0;\n }\n // Just like inOrder travesal, search nodes on the left, visit the root, \n // and search nodes on right while incrementing the height\n // Whilst performing Inorder traversal, we checking each node data to see\n // if it is equal to search and then return the level\n search(node.left, search, h + 1);\n // And then checking each node to see it \n if(node.data == search){\n level = h;\n }\n search(node.right, search, h + 1);\n return level;\n }" }, { "code": null, "e": 5795, "s": 5792, "text": "+1" }, { "code": null, "e": 5816, "s": 5795, "text": "17vineet3 months ago" }, { "code": null, "e": 6532, "s": 5816, "text": "int getLevel(Node node, int data) \n {\n int level = 1 ;\n Queue<Node> q = new LinkedList<Node>() ;\n q.add(node) ;\n \n while(true)\n {\n int size = q.size() ;\n if(size == 0)\n break ;\n \n while(size>0)\n {\n Node root = q.poll() ;\n if(root.data == data)\n return level ;\n \n if(root.left != null)\n q.add(root.left) ;\n if(root.right != null)\n q.add(root.right) ;\n \n size-- ;\n }\n level++ ;\n }\n return 0 ;\n } " }, { "code": null, "e": 6678, "s": 6532, "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": 6714, "s": 6678, "text": " Login to access your submissions. " }, { "code": null, "e": 6724, "s": 6714, "text": "\nProblem\n" }, { "code": null, "e": 6734, "s": 6724, "text": "\nContest\n" }, { "code": null, "e": 6797, "s": 6734, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6945, "s": 6797, "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": 7153, "s": 6945, "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": 7259, "s": 7153, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to concatenate column values and create a new column in an R data frame?
Sometimes we want to combine column values of two columns to create a new column. This is mostly used when we have a unique column that maybe combined with a numerical or any other type of column. Also, we can do this by separating the column values that is going to be created with difference characters. And it can be done with the help of apply function. Consider the below data frame − Live Demo > ID<-1:20 > Country<- sample(c("Russia","USA","China","Canada","UK","India","Nepal"),20,replace=TRUE) > df1<-data.frame(ID,Country) > df1 ID Country 1 1 UK 2 2 UK 3 3 India 4 4 USA 5 5 USA 6 6 UK 7 7 Nepal 8 8 Russia 9 9 Nepal 10 10 China 11 11 UK 12 12 Nepal 13 13 Canada 14 14 USA 15 15 Russia 16 16 UK 17 17 China 18 18 USA 19 19 China 20 20 Russia Creating a new column of ID and Country − > df1$ID_with_Country<-apply(df1,1,paste,collapse="") > df1 ID Country ID_with_Country 1 1 UK 1UK 2 2 UK 2UK 3 3 India 3India 4 4 USA 4USA 5 5 USA 5USA 6 6 UK 6UK 7 7 Nepal 7Nepal 8 8 Russia 8Russia 9 9 Nepal 9Nepal 10 10 China 10China 11 11 UK 11UK 12 12 Nepal 12Nepal 13 13 Canada 13Canada 14 14 USA 14USA 15 15 Russia 15Russia 16 16 UK 16UK 17 17 China 17China 18 18 USA 18USA 19 19 China 19China 20 20 Russia 20Russia Let’s have a look at another example − Live Demo > Class<-LETTERS[1:20] > Rank<-sample(1:10,20,replace=TRUE) > df2<-data.frame(Class,Rank) > df2 Class Rank 1 A 2 2 B 4 3 C 4 4 D 6 5 E 7 6 F 10 7 G 10 8 H 5 9 I 9 10 J 6 11 K 1 12 L 8 13 M 10 14 N 7 15 O 5 16 P 7 17 Q 6 18 R 1 19 S 10 20 T 3 > df2$Class_Rank<-apply(df2,1,paste,collapse="_") > df2 Class Rank Class_Rank 1 A 2 A_ 2 2 B 4 B_ 4 3 C 4 C_ 4 4 D 6 D_ 6 5 E 7 E_ 7 6 F 10 F_10 7 G 10 G_10 8 H 5 H_ 5 9 I 9 I_ 9 10 J 6 J_ 6 11 K 1 K_ 1 12 L 8 L_ 8 13 M 10 M_10 14 N 7 N_ 7 15 O 5 O_ 5 16 P 7 P_ 7 17 Q 6 Q_ 6 18 R 1 R_ 1 19 S 10 S_10 20 T 3 T_ 3
[ { "code": null, "e": 1420, "s": 1062, "text": "Sometimes we want to combine column values of two columns to create a new column. This is mostly used when we have a unique column that maybe combined with a numerical or any other type of column. Also, we can do this by separating the column values that is going to be created with difference characters. And it can be done with the help of apply function." }, { "code": null, "e": 1452, "s": 1420, "text": "Consider the below data frame −" }, { "code": null, "e": 1463, "s": 1452, "text": " Live Demo" }, { "code": null, "e": 1602, "s": 1463, "text": "> ID<-1:20\n> Country<-\nsample(c(\"Russia\",\"USA\",\"China\",\"Canada\",\"UK\",\"India\",\"Nepal\"),20,replace=TRUE)\n> df1<-data.frame(ID,Country)\n> df1" }, { "code": null, "e": 1817, "s": 1602, "text": " ID Country\n1 1 UK\n2 2 UK\n3 3 India\n4 4 USA\n5 5 USA\n6 6 UK\n7 7 Nepal\n8 8 Russia\n9 9 Nepal\n10 10 China\n11 11 UK\n12 12 Nepal\n13 13 Canada\n14 14 USA\n15 15 Russia\n16 16 UK\n17 17 China\n18 18 USA\n19 19 China\n20 20 Russia" }, { "code": null, "e": 1859, "s": 1817, "text": "Creating a new column of ID and Country −" }, { "code": null, "e": 1919, "s": 1859, "text": "> df1$ID_with_Country<-apply(df1,1,paste,collapse=\"\")\n> df1" }, { "code": null, "e": 2383, "s": 1919, "text": " ID Country ID_with_Country\n1 1 UK 1UK\n2 2 UK 2UK\n3 3 India 3India\n4 4 USA 4USA\n5 5 USA 5USA\n6 6 UK 6UK\n7 7 Nepal 7Nepal\n8 8 Russia 8Russia\n9 9 Nepal 9Nepal\n10 10 China 10China\n11 11 UK 11UK\n12 12 Nepal 12Nepal\n13 13 Canada 13Canada\n14 14 USA 14USA\n15 15 Russia 15Russia\n16 16 UK 16UK\n17 17 China 17China\n18 18 USA 18USA\n19 19 China 19China\n20 20 Russia 20Russia" }, { "code": null, "e": 2422, "s": 2383, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2433, "s": 2422, "text": " Live Demo" }, { "code": null, "e": 2529, "s": 2433, "text": "> Class<-LETTERS[1:20]\n> Rank<-sample(1:10,20,replace=TRUE)\n> df2<-data.frame(Class,Rank)\n> df2" }, { "code": null, "e": 2734, "s": 2529, "text": " Class Rank\n1 A 2\n2 B 4\n3 C 4\n4 D 6\n5 E 7\n6 F 10\n7 G 10\n8 H 5\n9 I 9\n10 J 6\n11 K 1\n12 L 8\n13 M 10\n14 N 7\n15 O 5\n16 P 7\n17 Q 6\n18 R 1\n19 S 10\n20 T 3" }, { "code": null, "e": 2790, "s": 2734, "text": "> df2$Class_Rank<-apply(df2,1,paste,collapse=\"_\")\n> df2" }, { "code": null, "e": 3227, "s": 2790, "text": " Class Rank Class_Rank\n1 A 2 A_ 2\n2 B 4 B_ 4\n3 C 4 C_ 4\n4 D 6 D_ 6\n5 E 7 E_ 7\n6 F 10 F_10\n7 G 10 G_10\n8 H 5 H_ 5\n9 I 9 I_ 9\n10 J 6 J_ 6\n11 K 1 K_ 1\n12 L 8 L_ 8\n13 M 10 M_10\n14 N 7 N_ 7\n15 O 5 O_ 5\n16 P 7 P_ 7\n17 Q 6 Q_ 6\n18 R 1 R_ 1\n19 S 10 S_10\n20 T 3 T_ 3" } ]
Find the player who will win the Coin game - GeeksforGeeks
06 Apr, 2022 Given N coins, the task is to find who win the coin game.Coin game is a game in which each player picks coins from the given N coins in such a way that he can pick coins ranging from 1 to 5 coins in one turn and the game continues for both the players. The player who picks the last coin loses the game.Examples: Input: N = 4 Output: First Player Explanation: Player 1 pick 3 coins and Player 2 pick last coin Input: N = 7 Output: Second Player Approach: As the player can take coins ranging from 1 to 5 inclusively and if a player loses it means that he had only 1 coin, otherwise, he could have taken 1 less coin than available coins and force another player to lose. So now we will consider the case when the second player is going to win, which means the first player had only one coin. For N = 1, second player is going to win, for N = 2 to 6, first player can choose 1 less coin than N, and force the second player to lose so discard them, for N = 7, first player can choose coin 1 to 5, that’s going to leave coin ranging from 6 to 2, and then second player can choose 1 to 5, and to win second player will intelligently choose 1 less coin forcing first to loose, So basically starting from 1, all the numbers on a gap of 6(as whatever first player choose, second player will choose coins equal to difference of 6 and coins chosen by the first player) will be the winning for second player. Finally, we just have to check if n is of form 6*c+1 if it is then the second player going to win, otherwise, the first player going to win. Below is the implementation for the above approach: C++ Java Python3 C# Javascript // C++ program to find the player// who wins the game #include <bits/stdc++.h>using namespace std; // Function to check the// winning playervoid findWinner(int n){ // As discussed in the // above approach if ((n - 1) % 6 == 0) { cout << "Second Player wins the game"; } else { cout << "First Player wins the game"; }} // Driver functionint main(){ int n = 7; findWinner(n);} // Java program to find the player// who wins the gameclass GFG{ // Function to check the// winning playerstatic void findWinner(int n){ // As discussed in the // above approach if ((n - 1) % 6 == 0) { System.out.println("Second Player wins the game"); } else { System.out.println("First Player wins the game"); }} // Driver Codepublic static void main(String[] args){ int n = 7; findWinner(n);}} // This code is contributed by Rajput-Ji # Python3 program to find the player# who wins the game # Function to check the# winning playerdef findWinner(n): # As discussed in the # above approach if ((n - 1) % 6 == 0): print("Second Player wins the game"); else: print("First Player wins the game"); # Driver Codeif __name__ == '__main__': n = 7; findWinner(n); # This code is contributed by 29AjayKumar // C# program to find the player// who wins the game using System; class GFG{ // Function to check the // winning player static void findWinner(int n) { // As discussed in the // above approach if ((n - 1) % 6 == 0) { Console.WriteLine("Second Player wins the game"); } else { Console.WriteLine("First Player wins the game"); } } // Driver Code public static void Main() { int n = 7; findWinner(n); }} // This code is contributed by AnkitRai01 <script> // JavaScript program to find the player// who wins the game // Function to check the// winning playerfunction findWinner(n){ // As discussed in the // above approach if ((n - 1) % 6 == 0) { document.write("Second Player wins the game"); } else { document.write("First Player wins the game"); }} // Driver functionvar n = 7;findWinner(n); </script> Output: Second Player wins the game Time Complexity: Auxiliary Space: O(1) Rajput-Ji ankthon 29AjayKumar rutvik_56 subham348 simmytarika5 number-theory Game Theory Mathematical number-theory Mathematical Game Theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Classification of Algorithms with Examples A Binary String Game Find the winner of a game of removing any number of stones from the least indexed non-empty pile from given N piles Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number Find the winner of game of repeatedly removing the first character to empty given string Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25204, "s": 25176, "text": "\n06 Apr, 2022" }, { "code": null, "e": 25518, "s": 25204, "text": "Given N coins, the task is to find who win the coin game.Coin game is a game in which each player picks coins from the given N coins in such a way that he can pick coins ranging from 1 to 5 coins in one turn and the game continues for both the players. The player who picks the last coin loses the game.Examples: " }, { "code": null, "e": 25652, "s": 25518, "text": "Input: N = 4\nOutput: First Player\nExplanation:\nPlayer 1 pick 3 coins and \nPlayer 2 pick last coin\n\nInput: N = 7\nOutput: Second Player" }, { "code": null, "e": 25666, "s": 25654, "text": "Approach: " }, { "code": null, "e": 26002, "s": 25666, "text": "As the player can take coins ranging from 1 to 5 inclusively and if a player loses it means that he had only 1 coin, otherwise, he could have taken 1 less coin than available coins and force another player to lose. So now we will consider the case when the second player is going to win, which means the first player had only one coin." }, { "code": null, "e": 26609, "s": 26002, "text": "For N = 1, second player is going to win, for N = 2 to 6, first player can choose 1 less coin than N, and force the second player to lose so discard them, for N = 7, first player can choose coin 1 to 5, that’s going to leave coin ranging from 6 to 2, and then second player can choose 1 to 5, and to win second player will intelligently choose 1 less coin forcing first to loose, So basically starting from 1, all the numbers on a gap of 6(as whatever first player choose, second player will choose coins equal to difference of 6 and coins chosen by the first player) will be the winning for second player." }, { "code": null, "e": 26750, "s": 26609, "text": "Finally, we just have to check if n is of form 6*c+1 if it is then the second player going to win, otherwise, the first player going to win." }, { "code": null, "e": 26804, "s": 26750, "text": "Below is the implementation for the above approach: " }, { "code": null, "e": 26808, "s": 26804, "text": "C++" }, { "code": null, "e": 26813, "s": 26808, "text": "Java" }, { "code": null, "e": 26821, "s": 26813, "text": "Python3" }, { "code": null, "e": 26824, "s": 26821, "text": "C#" }, { "code": null, "e": 26835, "s": 26824, "text": "Javascript" }, { "code": "// C++ program to find the player// who wins the game #include <bits/stdc++.h>using namespace std; // Function to check the// winning playervoid findWinner(int n){ // As discussed in the // above approach if ((n - 1) % 6 == 0) { cout << \"Second Player wins the game\"; } else { cout << \"First Player wins the game\"; }} // Driver functionint main(){ int n = 7; findWinner(n);}", "e": 27249, "s": 26835, "text": null }, { "code": "// Java program to find the player// who wins the gameclass GFG{ // Function to check the// winning playerstatic void findWinner(int n){ // As discussed in the // above approach if ((n - 1) % 6 == 0) { System.out.println(\"Second Player wins the game\"); } else { System.out.println(\"First Player wins the game\"); }} // Driver Codepublic static void main(String[] args){ int n = 7; findWinner(n);}} // This code is contributed by Rajput-Ji", "e": 27731, "s": 27249, "text": null }, { "code": "# Python3 program to find the player# who wins the game # Function to check the# winning playerdef findWinner(n): # As discussed in the # above approach if ((n - 1) % 6 == 0): print(\"Second Player wins the game\"); else: print(\"First Player wins the game\"); # Driver Codeif __name__ == '__main__': n = 7; findWinner(n); # This code is contributed by 29AjayKumar", "e": 28133, "s": 27731, "text": null }, { "code": "// C# program to find the player// who wins the game using System; class GFG{ // Function to check the // winning player static void findWinner(int n) { // As discussed in the // above approach if ((n - 1) % 6 == 0) { Console.WriteLine(\"Second Player wins the game\"); } else { Console.WriteLine(\"First Player wins the game\"); } } // Driver Code public static void Main() { int n = 7; findWinner(n); }} // This code is contributed by AnkitRai01", "e": 28706, "s": 28133, "text": null }, { "code": "<script> // JavaScript program to find the player// who wins the game // Function to check the// winning playerfunction findWinner(n){ // As discussed in the // above approach if ((n - 1) % 6 == 0) { document.write(\"Second Player wins the game\"); } else { document.write(\"First Player wins the game\"); }} // Driver functionvar n = 7;findWinner(n); </script>", "e": 29096, "s": 28706, "text": null }, { "code": null, "e": 29105, "s": 29096, "text": "Output: " }, { "code": null, "e": 29133, "s": 29105, "text": "Second Player wins the game" }, { "code": null, "e": 29150, "s": 29133, "text": "Time Complexity:" }, { "code": null, "e": 29173, "s": 29150, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 29183, "s": 29173, "text": "Rajput-Ji" }, { "code": null, "e": 29191, "s": 29183, "text": "ankthon" }, { "code": null, "e": 29203, "s": 29191, "text": "29AjayKumar" }, { "code": null, "e": 29213, "s": 29203, "text": "rutvik_56" }, { "code": null, "e": 29223, "s": 29213, "text": "subham348" }, { "code": null, "e": 29236, "s": 29223, "text": "simmytarika5" }, { "code": null, "e": 29250, "s": 29236, "text": "number-theory" }, { "code": null, "e": 29262, "s": 29250, "text": "Game Theory" }, { "code": null, "e": 29275, "s": 29262, "text": "Mathematical" }, { "code": null, "e": 29289, "s": 29275, "text": "number-theory" }, { "code": null, "e": 29302, "s": 29289, "text": "Mathematical" }, { "code": null, "e": 29314, "s": 29302, "text": "Game Theory" }, { "code": null, "e": 29412, "s": 29314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29421, "s": 29412, "text": "Comments" }, { "code": null, "e": 29434, "s": 29421, "text": "Old Comments" }, { "code": null, "e": 29477, "s": 29434, "text": "Classification of Algorithms with Examples" }, { "code": null, "e": 29498, "s": 29477, "text": "A Binary String Game" }, { "code": null, "e": 29614, "s": 29498, "text": "Find the winner of a game of removing any number of stones from the least indexed non-empty pile from given N piles" }, { "code": null, "e": 29737, "s": 29614, "text": "Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number" }, { "code": null, "e": 29826, "s": 29737, "text": "Find the winner of game of repeatedly removing the first character to empty given string" }, { "code": null, "e": 29856, "s": 29826, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29871, "s": 29856, "text": "C++ Data Types" }, { "code": null, "e": 29931, "s": 29871, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29974, "s": 29931, "text": "Set in C++ Standard Template Library (STL)" } ]
Can we override only one method while implementing Java interface?
An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface. To create an object of this type you need to implement this interface, provide body for all the abstract methods of the interface and obtain the object of the implementing class. Live Demo interface Sample { void demoMethod1(); void demoMethod2(); void demoMethod3(); } public class InterfaceExample implements Sample { public void demoMethod1() { System.out.println("This is demo method-1"); } public void demoMethod2() { System.out.println("This is demo method-2"); } public void demoMethod3() { System.out.println("This is demo method-3"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demoMethod1(); obj.demoMethod1(); obj.demoMethod3(); } } This is demo method-1 This is demo method-2 This is demo method-3 While implementing an interface it is mandatory to override all the abstract methods of it, if you skip overriding any of the abstract methods a compile time error will be generated. Live Demo interface Sample { void demoMethod1(); void demoMethod2(); void demoMethod3(); } public class InterfaceExample implements Sample { public void demoMethod1() { System.out.println("This is demo method-1"); } public void demoMethod2() { System.out.println("This is demo method-2"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demoMethod1(); obj.demoMethod2(); } } InterfaceExample.java:6: error: InterfaceExample is not abstract and does not override abstract method demoMethod3() in Sample public class InterfaceExample implements Sample{ ^ 1 error But, still if you want to override only one abstract method − You can leave remaining methods unimplemented as − Live Demo interface Sample { void demoMethod1(); void demoMethod2(); void demoMethod3(); } public class InterfaceExample implements Sample { public void demoMethod1() { System.out.println("This is demo method-1"); } public void demoMethod2() { } public void demoMethod3() { } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demoMethod1(); obj.demoMethod2(); obj.demoMethod3(); } } This is demo method-1 Since int is not mandatory to implement default methods of an interface, you can declare remaining methods default as − Live Demo interface Sample { void demoMethod1(); default void demoMethod2() { System.out.println("Default demo method 2"); } default void demoMethod3() { System.out.println("Default demo method 3"); } } public class InterfaceExample implements Sample { public void demoMethod1() { System.out.println("This is demo method-1"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demoMethod1(); obj.demoMethod2(); obj.demoMethod3(); } } This is demo method-1 Default demo method 2 Default demo method 3
[ { "code": null, "e": 1273, "s": 1062, "text": "An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface." }, { "code": null, "e": 1452, "s": 1273, "text": "To create an object of this type you need to implement this interface, provide body for all the abstract methods of the interface and obtain the object of the implementing class." }, { "code": null, "e": 1463, "s": 1452, "text": " Live Demo" }, { "code": null, "e": 2043, "s": 1463, "text": "interface Sample {\n void demoMethod1();\n void demoMethod2();\n void demoMethod3();\n}\npublic class InterfaceExample implements Sample {\n public void demoMethod1() {\n System.out.println(\"This is demo method-1\");\n }\n public void demoMethod2() {\n System.out.println(\"This is demo method-2\");\n }\n public void demoMethod3() {\n System.out.println(\"This is demo method-3\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.demoMethod1();\n obj.demoMethod1();\n obj.demoMethod3();\n }\n}" }, { "code": null, "e": 2109, "s": 2043, "text": "This is demo method-1\nThis is demo method-2\nThis is demo method-3" }, { "code": null, "e": 2292, "s": 2109, "text": "While implementing an interface it is mandatory to override all the abstract methods of it, if you skip overriding any of the abstract methods a compile time error will be generated." }, { "code": null, "e": 2303, "s": 2292, "text": " Live Demo" }, { "code": null, "e": 2771, "s": 2303, "text": "interface Sample {\n void demoMethod1();\n void demoMethod2();\n void demoMethod3();\n}\npublic class InterfaceExample implements Sample {\n public void demoMethod1() {\n System.out.println(\"This is demo method-1\");\n }\n public void demoMethod2() {\n System.out.println(\"This is demo method-2\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.demoMethod1();\n obj.demoMethod2();\n }\n}" }, { "code": null, "e": 2964, "s": 2771, "text": "InterfaceExample.java:6: error: InterfaceExample is not abstract and does not override abstract method demoMethod3() in Sample\npublic class InterfaceExample implements Sample{\n ^\n1 error" }, { "code": null, "e": 3026, "s": 2964, "text": "But, still if you want to override only one abstract method −" }, { "code": null, "e": 3077, "s": 3026, "text": "You can leave remaining methods unimplemented as −" }, { "code": null, "e": 3088, "s": 3077, "text": " Live Demo" }, { "code": null, "e": 3566, "s": 3088, "text": "interface Sample {\n void demoMethod1();\n void demoMethod2();\n void demoMethod3();\n}\npublic class InterfaceExample implements Sample {\n public void demoMethod1() {\n System.out.println(\"This is demo method-1\");\n }\n public void demoMethod2() {\n }\n public void demoMethod3() {\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.demoMethod1();\n obj.demoMethod2();\n obj.demoMethod3();\n }\n}" }, { "code": null, "e": 3588, "s": 3566, "text": "This is demo method-1" }, { "code": null, "e": 3708, "s": 3588, "text": "Since int is not mandatory to implement default methods of an interface, you can declare remaining methods default as −" }, { "code": null, "e": 3719, "s": 3708, "text": " Live Demo" }, { "code": null, "e": 4255, "s": 3719, "text": "interface Sample {\n void demoMethod1();\n default void demoMethod2() {\n System.out.println(\"Default demo method 2\");\n }\n default void demoMethod3() {\n System.out.println(\"Default demo method 3\");\n }\n}\npublic class InterfaceExample implements Sample {\n public void demoMethod1() {\n System.out.println(\"This is demo method-1\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.demoMethod1();\n obj.demoMethod2();\n obj.demoMethod3();\n }\n}" }, { "code": null, "e": 4321, "s": 4255, "text": "This is demo method-1\nDefault demo method 2\nDefault demo method 3" } ]
Pandas read_csv - Read CSV file in Pandas and prepare Dataframe - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we will see how we can read data from a CSV file and save a pandas data-frame as a CSV (comma separated values) file in pandas. read_csv() method of pandas will read the data from a comma-separated values file having .csv as a pandas data-frame and also provide some arguments to give some flexibility according to the requirement. The official documentation provides the syntax below, We will learn the most commonly used among these in the following sections with an example. pandas.read_csv(filepath, sep=',', header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, infer_datetime_format=False, keep_date_col=False, date_parser=None,iterator=False, chunksize=None, compression='infer', thousands=None, decimal='.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None) In this example, we will try to read a CSV file using the below arguments along with the file path. Country,Age,Salary,Purchased France,44,72000,No Spain,27,48000,Yes Germany,30,54000,No Spain,38,61000,No Germany,40,,Yes France,35,58000,Yes Spain,,52000,No France,48,79000,Yes Germany,50,83000,No France,37,67000,Yes file-path – This is the path to the file in string format. sep – It is the delimiter that tells the symbol to use for splitting the data. header – integer list of rows to be used as the columns. If multiple rows are passed then we will get a multi-column index data. See the code below where we will use these arguments to read the file. # importing pandas and giving an alias name import pandas as pd # URL of the data url = "home/user/kunalgupta2616/datasets/master/Data.csv" # method to be used to read the data data = pd.read_csv(url,header=[0],sep=',') print(data) Output: Country Age Salary Purchased 0 France 44.0 72000.0 No 1 Spain 27.0 48000.0 Yes 2 Germany 30.0 54000.0 No 3 Spain 38.0 61000.0 No 4 Germany 40.0 NaN Yes 5 France 35.0 58000.0 Yes 6 Spain NaN 52000.0 No 7 France 48.0 79000.0 Yes 8 Germany 50.0 83000.0 No 9 France 37.0 67000.0 Yes usecols – List of column names from data to be read. index_col – This defines the names of row labels, it can be a column from the data or the list of integer or string, None by default. skiprows – list of rows number / No. or rows to be skipped from the top. It is 0-indexed. skipfooter – No. or rows to be skipped from the bottom. skip_blank_lines – If there is any blank line it will be skipped instead of using NaN. nrows – The number of rows to be read from the file. Let’s see an example code to see some of these parameters. import pandas as pd url = "home/user/kunalgupta2616/datasets/master/Data2.csv" data1 = pd.read_csv(url,usecols=['Country','Age','Purchased'],skiprows = [1,2],nrows=4,index_col='Country') print(data1) Output: Age Purchased Country Germany 30 No Spain 38 No Germany 40 Yes France 35 Yes For this example, we will be using employee data of an organization that can be found at this link. parse_dates – List of 0-indexed column numbers that can contain data containing dates. Let us read top 10 rows of this data and parse a column containing dates using parse_dates argument. To verify that the column is of DateTime type, we will print the dtypes attribute. import pandas as pd url = "https://raw.githubusercontent.com/kunalgupta2616/datasets/master/employees.csv" data2 = pd.read_csv(url,nrows=5,parse_dates=[2]) print(data2.dtypes) Output: First Name object Gender object Start Date datetime64[ns] Last Login Time object Salary int64 Bonus % float64 Senior Management bool Team object dtype: object These are the most commonly used arguments that are used when reading a CSV file in pandas. Let us see how we can save a data frame as a CSV file in pandas. What is Python NumPy Library How to read a text file in Python ? Happy Learning 🙂 How to Read CSV File in Python How to Convert Python List Of Objects to CSV File Java – How to read CSV file and Map to Java Object How to read a text file in Python ? How to read JSON file in Python ? How to Delete a File or Directory in Python Python How to read input from keyboard Python raw_input read input from keyboard How to check whether a file exists python ? Java 8 Read File Line By Line Example How to get Words Count in Python from a File Python – How to create Zip File in Python ? PHP File Handling fopen fread and fclose Example How to get Characters Count in Python from a File Read an Image in JDBC Example How to Read CSV File in Python How to Convert Python List Of Objects to CSV File Java – How to read CSV file and Map to Java Object How to read a text file in Python ? How to read JSON file in Python ? How to Delete a File or Directory in Python Python How to read input from keyboard Python raw_input read input from keyboard How to check whether a file exists python ? Java 8 Read File Line By Line Example How to get Words Count in Python from a File Python – How to create Zip File in Python ? PHP File Handling fopen fread and fclose Example How to get Characters Count in Python from a File Read an Image in JDBC Example Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 544, "s": 398, "text": "In this tutorial, we will see how we can read data from a CSV file and save a pandas data-frame as a CSV (comma separated values) file in pandas." }, { "code": null, "e": 748, "s": 544, "text": "read_csv() method of pandas will read the data from a comma-separated values file having .csv as a pandas data-frame and also provide some arguments to give some flexibility according to the requirement." }, { "code": null, "e": 894, "s": 748, "text": "The official documentation provides the syntax below, We will learn the most commonly used among these in the following sections with an example." }, { "code": null, "e": 1666, "s": 894, "text": "pandas.read_csv(filepath, sep=',', header='infer', names=None, index_col=None, \nusecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None,\nconverters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None,\nskipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, \nskip_blank_lines=True, infer_datetime_format=False, keep_date_col=False, \ndate_parser=None,iterator=False, chunksize=None, \ncompression='infer', thousands=None, decimal='.', lineterminator=None, quotechar='\"', quoting=0, \ndoublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, \nerror_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, \nmemory_map=False, float_precision=None)" }, { "code": null, "e": 1766, "s": 1666, "text": "In this example, we will try to read a CSV file using the below arguments along with the file path." }, { "code": null, "e": 1983, "s": 1766, "text": "Country,Age,Salary,Purchased\nFrance,44,72000,No\nSpain,27,48000,Yes\nGermany,30,54000,No\nSpain,38,61000,No\nGermany,40,,Yes\nFrance,35,58000,Yes\nSpain,,52000,No\nFrance,48,79000,Yes\nGermany,50,83000,No\nFrance,37,67000,Yes" }, { "code": null, "e": 2042, "s": 1983, "text": "file-path – This is the path to the file in string format." }, { "code": null, "e": 2121, "s": 2042, "text": "sep – It is the delimiter that tells the symbol to use for splitting the data." }, { "code": null, "e": 2250, "s": 2121, "text": "header – integer list of rows to be used as the columns. If multiple rows are passed then we will get a multi-column index data." }, { "code": null, "e": 2321, "s": 2250, "text": "See the code below where we will use these arguments to read the file." }, { "code": null, "e": 2553, "s": 2321, "text": "# importing pandas and giving an alias name\nimport pandas as pd\n# URL of the data\nurl = \"home/user/kunalgupta2616/datasets/master/Data.csv\"\n# method to be used to read the data\ndata = pd.read_csv(url,header=[0],sep=',')\nprint(data)" }, { "code": null, "e": 2561, "s": 2553, "text": "Output:" }, { "code": null, "e": 2841, "s": 2561, "text": " Country Age Salary Purchased\n0 France 44.0 72000.0 No\n1 Spain 27.0 48000.0 Yes\n2 Germany 30.0 54000.0 No\n3 Spain 38.0 61000.0 No\n4 Germany 40.0 NaN Yes\n5 France 35.0 58000.0 Yes\n6 Spain NaN 52000.0 No\n7 France 48.0 79000.0 Yes\n8 Germany 50.0 83000.0 No\n9 France 37.0 67000.0 Yes" }, { "code": null, "e": 2894, "s": 2841, "text": "usecols – List of column names from data to be read." }, { "code": null, "e": 3028, "s": 2894, "text": "index_col – This defines the names of row labels, it can be a column from the data or the list of integer or string, None by default." }, { "code": null, "e": 3118, "s": 3028, "text": "skiprows – list of rows number / No. or rows to be skipped from the top. It is 0-indexed." }, { "code": null, "e": 3174, "s": 3118, "text": "skipfooter – No. or rows to be skipped from the bottom." }, { "code": null, "e": 3261, "s": 3174, "text": "skip_blank_lines – If there is any blank line it will be skipped instead of using NaN." }, { "code": null, "e": 3314, "s": 3261, "text": "nrows – The number of rows to be read from the file." }, { "code": null, "e": 3373, "s": 3314, "text": "Let’s see an example code to see some of these parameters." }, { "code": null, "e": 3573, "s": 3373, "text": "import pandas as pd\nurl = \"home/user/kunalgupta2616/datasets/master/Data2.csv\"\ndata1 = pd.read_csv(url,usecols=['Country','Age','Purchased'],skiprows = [1,2],nrows=4,index_col='Country')\nprint(data1)" }, { "code": null, "e": 3581, "s": 3573, "text": "Output:" }, { "code": null, "e": 3704, "s": 3581, "text": " Age Purchased\nCountry\nGermany 30 No\nSpain 38 No\nGermany 40 Yes\nFrance 35 Yes" }, { "code": null, "e": 3804, "s": 3704, "text": "For this example, we will be using employee data of an organization that can be found at this link." }, { "code": null, "e": 3891, "s": 3804, "text": "parse_dates – List of 0-indexed column numbers that can contain data containing dates." }, { "code": null, "e": 4075, "s": 3891, "text": "Let us read top 10 rows of this data and parse a column containing dates using parse_dates argument. To verify that the column is of DateTime type, we will print the dtypes attribute." }, { "code": null, "e": 4251, "s": 4075, "text": "import pandas as pd\nurl = \"https://raw.githubusercontent.com/kunalgupta2616/datasets/master/employees.csv\"\ndata2 = pd.read_csv(url,nrows=5,parse_dates=[2])\nprint(data2.dtypes)" }, { "code": null, "e": 4259, "s": 4251, "text": "Output:" }, { "code": null, "e": 4418, "s": 4259, "text": "First Name object\nGender object\nStart Date datetime64[ns]\nLast Login Time object\nSalary int64\nBonus % float64\nSenior Management bool\nTeam object\ndtype: object" }, { "code": null, "e": 4575, "s": 4418, "text": "These are the most commonly used arguments that are used when reading a CSV file in pandas. Let us see how we can save a data frame as a CSV file in pandas." }, { "code": null, "e": 4604, "s": 4575, "text": "What is Python NumPy Library" }, { "code": null, "e": 4640, "s": 4604, "text": "How to read a text file in Python ?" }, { "code": null, "e": 4657, "s": 4640, "text": "Happy Learning 🙂" }, { "code": null, "e": 5287, "s": 4657, "text": "\nHow to Read CSV File in Python\nHow to Convert Python List Of Objects to CSV File\nJava – How to read CSV file and Map to Java Object\nHow to read a text file in Python ?\nHow to read JSON file in Python ?\nHow to Delete a File or Directory in Python\nPython How to read input from keyboard\nPython raw_input read input from keyboard\nHow to check whether a file exists python ?\nJava 8 Read File Line By Line Example\nHow to get Words Count in Python from a File\nPython – How to create Zip File in Python ?\nPHP File Handling fopen fread and fclose Example\nHow to get Characters Count in Python from a File\nRead an Image in JDBC Example\n" }, { "code": null, "e": 5318, "s": 5287, "text": "How to Read CSV File in Python" }, { "code": null, "e": 5368, "s": 5318, "text": "How to Convert Python List Of Objects to CSV File" }, { "code": null, "e": 5419, "s": 5368, "text": "Java – How to read CSV file and Map to Java Object" }, { "code": null, "e": 5455, "s": 5419, "text": "How to read a text file in Python ?" }, { "code": null, "e": 5489, "s": 5455, "text": "How to read JSON file in Python ?" }, { "code": null, "e": 5533, "s": 5489, "text": "How to Delete a File or Directory in Python" }, { "code": null, "e": 5572, "s": 5533, "text": "Python How to read input from keyboard" }, { "code": null, "e": 5614, "s": 5572, "text": "Python raw_input read input from keyboard" }, { "code": null, "e": 5658, "s": 5614, "text": "How to check whether a file exists python ?" }, { "code": null, "e": 5696, "s": 5658, "text": "Java 8 Read File Line By Line Example" }, { "code": null, "e": 5741, "s": 5696, "text": "How to get Words Count in Python from a File" }, { "code": null, "e": 5785, "s": 5741, "text": "Python – How to create Zip File in Python ?" }, { "code": null, "e": 5835, "s": 5785, "text": "PHP File Handling fopen fread and fclose Example" }, { "code": null, "e": 5885, "s": 5835, "text": "How to get Characters Count in Python from a File" }, { "code": null, "e": 5915, "s": 5885, "text": "Read an Image in JDBC Example" }, { "code": null, "e": 5921, "s": 5919, "text": "Δ" }, { "code": null, "e": 5944, "s": 5921, "text": " Python – Introduction" }, { "code": null, "e": 5963, "s": 5944, "text": " Python – Features" }, { "code": null, "e": 5992, "s": 5963, "text": " Python – Install on Windows" }, { "code": null, "e": 6019, "s": 5992, "text": " Python – Modes of Program" }, { "code": null, "e": 6043, "s": 6019, "text": " Python – Number System" }, { "code": null, "e": 6065, "s": 6043, "text": " Python – Identifiers" }, { "code": null, "e": 6085, "s": 6065, "text": " Python – Operators" }, { "code": null, "e": 6112, "s": 6085, "text": " Python – Ternary Operator" }, { "code": null, "e": 6145, "s": 6112, "text": " Python – Command Line Arguments" }, { "code": null, "e": 6164, "s": 6145, "text": " Python – Keywords" }, { "code": null, "e": 6185, "s": 6164, "text": " Python – Data Types" }, { "code": null, "e": 6214, "s": 6185, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 6244, "s": 6214, "text": " Python – Virtual Environment" }, { "code": null, "e": 6267, "s": 6244, "text": " Pyhton – Type Casting" }, { "code": null, "e": 6291, "s": 6267, "text": " Python – String to Int" }, { "code": null, "e": 6324, "s": 6291, "text": " Python – Conditional Statements" }, { "code": null, "e": 6347, "s": 6324, "text": " Python – if statement" }, { "code": null, "e": 6376, "s": 6347, "text": " Python – *args and **kwargs" }, { "code": null, "e": 6402, "s": 6376, "text": " Python – Date Formatting" }, { "code": null, "e": 6437, "s": 6402, "text": " Python – Read input from keyboard" }, { "code": null, "e": 6457, "s": 6437, "text": " Python – raw_input" }, { "code": null, "e": 6481, "s": 6457, "text": " Python – List In Depth" }, { "code": null, "e": 6510, "s": 6481, "text": " Python – List Comprehension" }, { "code": null, "e": 6533, "s": 6510, "text": " Python – Set in Depth" }, { "code": null, "e": 6563, "s": 6533, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 6588, "s": 6563, "text": " Python – Tuple in Depth" }, { "code": null, "e": 6618, "s": 6588, "text": " Python – Stack Datastructure" }, { "code": null, "e": 6648, "s": 6618, "text": " Python – Classes and Objects" }, { "code": null, "e": 6671, "s": 6648, "text": " Python – Constructors" }, { "code": null, "e": 6702, "s": 6671, "text": " Python – Object Introspection" }, { "code": null, "e": 6724, "s": 6702, "text": " Python – Inheritance" }, { "code": null, "e": 6745, "s": 6724, "text": " Python – Decorators" }, { "code": null, "e": 6781, "s": 6745, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 6811, "s": 6781, "text": " Python – Exceptions Handling" }, { "code": null, "e": 6845, "s": 6811, "text": " Python – User defined Exceptions" }, { "code": null, "e": 6871, "s": 6845, "text": " Python – Multiprocessing" }, { "code": null, "e": 6909, "s": 6871, "text": " Python – Default function parameters" }, { "code": null, "e": 6937, "s": 6909, "text": " Python – Lambdas Functions" }, { "code": null, "e": 6961, "s": 6937, "text": " Python – NumPy Library" }, { "code": null, "e": 6987, "s": 6961, "text": " Python – MySQL Connector" }, { "code": null, "e": 7019, "s": 6987, "text": " Python – MySQL Create Database" }, { "code": null, "e": 7045, "s": 7019, "text": " Python – MySQL Read Data" }, { "code": null, "e": 7073, "s": 7045, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 7104, "s": 7073, "text": " Python – MySQL Update Records" }, { "code": null, "e": 7135, "s": 7104, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 7168, "s": 7135, "text": " Python – String Case Conversion" }, { "code": null, "e": 7203, "s": 7168, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 7240, "s": 7203, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 7278, "s": 7240, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 7304, "s": 7278, "text": " Howto – Merge two Lists" }, { "code": null, "e": 7329, "s": 7304, "text": " Howto – Merge two dicts" }, { "code": null, "e": 7369, "s": 7329, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 7404, "s": 7369, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 7439, "s": 7404, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 7468, "s": 7439, "text": " Howto – Read Env variables" }, { "code": null, "e": 7494, "s": 7468, "text": " Howto – Read a text File" }, { "code": null, "e": 7520, "s": 7494, "text": " Howto – Read a JSON File" }, { "code": null, "e": 7552, "s": 7520, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 7580, "s": 7552, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 7620, "s": 7580, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 7654, "s": 7620, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 7679, "s": 7654, "text": " Howto – create Zip File" }, { "code": null, "e": 7700, "s": 7679, "text": " Howto – Get OS info" }, { "code": null, "e": 7731, "s": 7700, "text": " Howto – Get size of Directory" }, { "code": null, "e": 7768, "s": 7731, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 7805, "s": 7768, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 7827, "s": 7805, "text": " Howto – Sort Objects" }, { "code": null, "e": 7865, "s": 7827, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 7888, "s": 7865, "text": " Howto – Read CSV File" }, { "code": null, "e": 7926, "s": 7888, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 7957, "s": 7926, "text": " Howto – Access for loop index" }, { "code": null, "e": 7995, "s": 7957, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 8035, "s": 7995, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 8082, "s": 8035, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 8114, "s": 8082, "text": " Howto – Sort dictionary by key" } ]
Java Program to get Milli seconds from Instant
Create an Instant and get an Instant using milliseconds passed as parameter from the epoch of 1970-01- 01T00:00:00Z. This is done using ofEpochMilli(): Instant instant = Instant.ofEpochMilli(342627282920l); Now, get the Epoch milliseconds from Instant: instant. toEpochMilli(); import java.time.Instant; public class Demo { public static void main(String[] args) { Instant instant = Instant.ofEpochMilli(1262347200000l); long res = instant.toEpochMilli(); System.out.println(res); } } 1262347200000
[ { "code": null, "e": 1214, "s": 1062, "text": "Create an Instant and get an Instant using milliseconds passed as parameter from the epoch of 1970-01-\n01T00:00:00Z. This is done using ofEpochMilli():" }, { "code": null, "e": 1269, "s": 1214, "text": "Instant instant = Instant.ofEpochMilli(342627282920l);" }, { "code": null, "e": 1315, "s": 1269, "text": "Now, get the Epoch milliseconds from Instant:" }, { "code": null, "e": 1340, "s": 1315, "text": "instant. toEpochMilli();" }, { "code": null, "e": 1571, "s": 1340, "text": "import java.time.Instant;\npublic class Demo {\n public static void main(String[] args) {\n Instant instant = Instant.ofEpochMilli(1262347200000l);\n long res = instant.toEpochMilli();\n System.out.println(res);\n }\n}" }, { "code": null, "e": 1585, "s": 1571, "text": "1262347200000" } ]
Tryit Editor v3.7
Tryit: Bad background image for page
[]
Powershell - Rename File
Rename-Item cmdlet is used to rename a File by passing the path of the file to be renamed and target name. In this example, we'll rename a folder D:\Temp\Test\test.txt to test1.txt Type the following command in PowerShell ISE Console Rename-Item D:\temp\Test\test.txt test1.txt You can see the test.txt renamed to test1.txt in Windows explorer. 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2141, "s": 2034, "text": "Rename-Item cmdlet is used to rename a File by passing the path of the file to be renamed and target name." }, { "code": null, "e": 2215, "s": 2141, "text": "In this example, we'll rename a folder D:\\Temp\\Test\\test.txt to test1.txt" }, { "code": null, "e": 2268, "s": 2215, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2312, "s": 2268, "text": "Rename-Item D:\\temp\\Test\\test.txt test1.txt" }, { "code": null, "e": 2379, "s": 2312, "text": "You can see the test.txt renamed to test1.txt in Windows explorer." }, { "code": null, "e": 2414, "s": 2379, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2435, "s": 2414, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 2470, "s": 2435, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2483, "s": 2470, "text": " Vijay Saini" }, { "code": null, "e": 2520, "s": 2483, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 2532, "s": 2520, "text": " Fettah Ben" }, { "code": null, "e": 2539, "s": 2532, "text": " Print" }, { "code": null, "e": 2550, "s": 2539, "text": " Add Notes" } ]
OpenCV - Adding Text
You can add text to an image using the method arrowedLine() of the imgproc class. Following is the syntax of this method. putText(img, text, org, fontFace, fontScale, Scalar color, int thickness) This method accepts the following parameters − mat − A Mat object representing the image to which the text is to be added. mat − A Mat object representing the image to which the text is to be added. text − A string variable of representing the text that is to be added. text − A string variable of representing the text that is to be added. org − A Point object representing the bottom left corner text string in the image. org − A Point object representing the bottom left corner text string in the image. fontFace − A variable of the type integer representing the font type. fontFace − A variable of the type integer representing the font type. fontScale − A variable of the type double representing the scale factor that is multiplied by the font-specific base size. fontScale − A variable of the type double representing the scale factor that is multiplied by the font-specific base size. scalar − A Scalar object representing the color of the text that is to be added. (BGR) scalar − A Scalar object representing the color of the text that is to be added. (BGR) thickness − An integer representing the thickness of the line by default, the value of thickness is 1. thickness − An integer representing the thickness of the line by default, the value of thickness is 1. The following program demonstrates how to add text to an image and display it using JavaFX window. import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.imageio.ImageIO; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.stage.Stage; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class AddingTextToImage extends Application { Mat matrix = null; @Override public void start(Stage stage) throws Exception { // Capturing the snapshot from the camera AddingTextToImage obj = new AddingTextToImage(); WritableImage writableImage = obj.LoadImage(); // Setting the image view ImageView imageView = new ImageView(writableImage); // setting the fit height and width of the image view imageView.setFitHeight(600); imageView.setFitWidth(600); // Setting the preserve ratio of the image view imageView.setPreserveRatio(true); // Creating a Group object Group root = new Group(imageView); // Creating a scene object Scene scene = new Scene(root, 600, 400); // Setting title to the Stage stage.setTitle("Adding text to an image"); // Adding scene to the stage stage.setScene(scene); // Displaying the contents of the stage stage.show(); } public WritableImage LoadImage() throws Exception { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap8/input.jpg"; Mat matrix = Imgcodecs.imread(file); // Adding Text Imgproc.putText ( matrix, // Matrix obj of the image "Ravivarma's Painting", // Text to be added new Point(10, 50), // point Core.FONT_HERSHEY_SIMPLEX , // front face 1, // front scale new Scalar(0, 0, 0), // Scalar object for color 4 // Thickness ); // Encoding the image MatOfByte matOfByte = new MatOfByte(); Imgcodecs.imencode(".jpg", matrix, matOfByte); // Storing the encoded Mat in a byte array byte[] byteArray = matOfByte.toArray(); // Displaying the image InputStream in = new ByteArrayInputStream(byteArray); BufferedImage bufImage = ImageIO.read(in); this.matrix = matrix; //Creating the Writable Image WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null); return writableImage; } public static void main(String args[]) { launch(args); } } On executing the above program, you will get the following output − 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3126, "s": 3004, "text": "You can add text to an image using the method arrowedLine() of the imgproc class. Following is the syntax of this method." }, { "code": null, "e": 3201, "s": 3126, "text": "putText(img, text, org, fontFace, fontScale, Scalar color, int thickness)\n" }, { "code": null, "e": 3248, "s": 3201, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3324, "s": 3248, "text": "mat − A Mat object representing the image to which the text is to be added." }, { "code": null, "e": 3400, "s": 3324, "text": "mat − A Mat object representing the image to which the text is to be added." }, { "code": null, "e": 3471, "s": 3400, "text": "text − A string variable of representing the text that is to be added." }, { "code": null, "e": 3542, "s": 3471, "text": "text − A string variable of representing the text that is to be added." }, { "code": null, "e": 3625, "s": 3542, "text": "org − A Point object representing the bottom left corner text string in the image." }, { "code": null, "e": 3708, "s": 3625, "text": "org − A Point object representing the bottom left corner text string in the image." }, { "code": null, "e": 3778, "s": 3708, "text": "fontFace − A variable of the type integer representing the font type." }, { "code": null, "e": 3848, "s": 3778, "text": "fontFace − A variable of the type integer representing the font type." }, { "code": null, "e": 3971, "s": 3848, "text": "fontScale − A variable of the type double representing the scale factor that is multiplied by the font-specific base size." }, { "code": null, "e": 4094, "s": 3971, "text": "fontScale − A variable of the type double representing the scale factor that is multiplied by the font-specific base size." }, { "code": null, "e": 4181, "s": 4094, "text": "scalar − A Scalar object representing the color of the text that is to be added. (BGR)" }, { "code": null, "e": 4268, "s": 4181, "text": "scalar − A Scalar object representing the color of the text that is to be added. (BGR)" }, { "code": null, "e": 4371, "s": 4268, "text": "thickness − An integer representing the thickness of the line by default, the value of thickness is 1." }, { "code": null, "e": 4474, "s": 4371, "text": "thickness − An integer representing the thickness of the line by default, the value of thickness is 1." }, { "code": null, "e": 4573, "s": 4474, "text": "The following program demonstrates how to add text to an image and display it using JavaFX window." }, { "code": null, "e": 7574, "s": 4573, "text": "import java.awt.image.BufferedImage;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport javax.imageio.ImageIO;\n\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\n\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfByte;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class AddingTextToImage extends Application {\n Mat matrix = null;\n\n @Override\n public void start(Stage stage) throws Exception {\n // Capturing the snapshot from the camera\n AddingTextToImage obj = new AddingTextToImage();\n WritableImage writableImage = obj.LoadImage();\n\n // Setting the image view\n ImageView imageView = new ImageView(writableImage);\n\n // setting the fit height and width of the image view\n imageView.setFitHeight(600);\n imageView.setFitWidth(600);\n\n // Setting the preserve ratio of the image view\n imageView.setPreserveRatio(true);\n\n // Creating a Group object\n Group root = new Group(imageView);\n\n // Creating a scene object\n Scene scene = new Scene(root, 600, 400);\n\n // Setting title to the Stage\n stage.setTitle(\"Adding text to an image\");\n\n // Adding scene to the stage\n stage.setScene(scene);\n\n // Displaying the contents of the stage\n stage.show();\n }\n public WritableImage LoadImage() throws Exception {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap8/input.jpg\";\n Mat matrix = Imgcodecs.imread(file);\n\n // Adding Text\n Imgproc.putText (\n matrix, // Matrix obj of the image\n \"Ravivarma's Painting\", // Text to be added\n new Point(10, 50), // point\n Core.FONT_HERSHEY_SIMPLEX , // front face\n 1, // front scale\n new Scalar(0, 0, 0), // Scalar object for color\n 4 // Thickness\n );\n \n // Encoding the image\n MatOfByte matOfByte = new MatOfByte();\n Imgcodecs.imencode(\".jpg\", matrix, matOfByte);\n\n // Storing the encoded Mat in a byte array\n byte[] byteArray = matOfByte.toArray();\n\n // Displaying the image\n InputStream in = new ByteArrayInputStream(byteArray);\n BufferedImage bufImage = ImageIO.read(in);\n this.matrix = matrix;\n\n //Creating the Writable Image\n WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);\n return writableImage;\n }\n public static void main(String args[]) {\n launch(args);\n }\n}" }, { "code": null, "e": 7642, "s": 7574, "text": "On executing the above program, you will get the following output −" }, { "code": null, "e": 7675, "s": 7642, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 7692, "s": 7675, "text": " Abhilash Nelson" }, { "code": null, "e": 7725, "s": 7692, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 7742, "s": 7725, "text": " Abhilash Nelson" }, { "code": null, "e": 7775, "s": 7742, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7789, "s": 7775, "text": " Spotle Learn" }, { "code": null, "e": 7821, "s": 7789, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 7838, "s": 7821, "text": " Srikanth Guskra" }, { "code": null, "e": 7871, "s": 7838, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 7886, "s": 7871, "text": " Haithem Gasmi" }, { "code": null, "e": 7921, "s": 7886, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7939, "s": 7921, "text": " Gianluca Mottola" }, { "code": null, "e": 7946, "s": 7939, "text": " Print" }, { "code": null, "e": 7957, "s": 7946, "text": " Add Notes" } ]
TensorFlow 2.4 on Apple Silicon M1: installation under Conda environment | by Fabrice Daniel | Towards Data Science
Updated Instructions for TensorFlow 2.4 alpha 3. See details at the end of the article. — The previous article was about the Machine Learning packages that works natively on Apple Silicon. I also explained how TensorFlow and scikit-learn can be installed on a Mac M1. In this article ATF 2.4 stand for TensorFlow 2.4 for Apple Silicon currently available from github in release 0.1 alpha 3. With ATF 2.4, standard installation requires creating a python environment while nearly no other package like scikit-learn can be installed from pip. This is making this environment quite useless for machine learning engineers except for small testing. At the time of writing this article ATF 2.4 is not free of bugs. It cannot yet be used in a professional context. But it’s already possible to start working on personal Machine Learning projects with a Mac M1. Here I describe step by step how to install a full environment under Conda with every packages natively compiled for Apple Silicon: ATF 2.4 (TensorFlow 2.4 for Apple Silicon) numpy scikit-learn pandas matplotlib JupyterLab Install Xcode Command Line Tools by downloading it from Apple Developer or by typing: xcode-select --install Install miniforge for arm64 (Apple Silicon) from miniforge github. Miniforge enables installing python packages natively compiled for Apple Silicon including scikit-learn. Download TensorFlow 2.4 from Apple github, untar it but don’t install it by using the provided script. Go under the arm64 directory: cd tensorflow_macos/arm64 Don’t forget to open a new session or to source your .zshrc after miniforge install and before going through this step. Create an empty Conda environment, then activate it and install python 3.8 (as required for ATF 2.4) and all the needed packages. Please note numpy is unnecessary here as pandas already install it, but it will be overwritten in the last step with the version provided by Apple. conda create --name tf24conda activate tf24conda install -y python==3.8.6conda install -y pandas matplotlib scikit-learn jupyterlab Now manually install ATF 2.4 packages exactly like install_venv.sh does but under your Conda environment. Please note the following instruction corresponds to the second ATF 2.4 release, namely 0.1 alpha 3. Any new release can require a different process, you will be able to adapt it by checking install_venv.sh content. # Install specific pip version and some other base packagespip install --force pip==20.2.4 wheel setuptools cached-property six packaging# Install all the packages provided by Apple but TensorFlowpip install --upgrade --no-dependencies --force numpy-1.18.5-cp38-cp38-macosx_11_0_arm64.whl grpcio-1.33.2-cp38-cp38-macosx_11_0_arm64.whl h5py-2.10.0-cp38-cp38-macosx_11_0_arm64.whl# Install additional packagespip install absl-py astunparse flatbuffers gast google_pasta keras_preprocessing opt_einsum protobuf tensorflow_estimator termcolor typing_extensions wrapt wheel tensorboard typeguard# Install TensorFlowpip install --upgrade --force --no-dependencies tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whlpip install --upgrade --force --no-dependencies tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl Now you can run JupyterLab and start working. Note that as pip installation can lead to inconsistencies with Conda packages previously installed, and especially because numpy is replaced by the 1.18.5 version shipped with ATF 2.4, there is no guarantee that it will work in every situation. For now, I’ve successfully trained several MLP and Convnet models while LSTM still have an issue with the evaluation on test set. I also trained RandomForest models and plot confusion matrix everything from JupyterLab without any issue. In the next article I will go through TensorFlow 2.4 benchmark on Mac M1. Thank you for reading. — This article is updated with instructions for TensorFlow 2.4 alpha 3. Previously, I mentioned that initial instructions were only for alpha 1 release and that “Any new release can require a different process, you will be able to adapt it by checking install_venv.sh content.”. So you can use these instructions for installing TF 2.4 Alpha 3. Alternatively you can also use this process proposed on ATF GitHub. Some people reported errors like ERROR: numpy-1.18.5-cp38-cp38-macosx_11_0_arm64.whl is not a supported wheel on this platform Apple does not propose an install that works everywhere in any situation. It’s an Alpha version. It means the instructions and prerequisites must be carefully followed. You must be on a mac M1, not Intel. Not running a terminal with rosetta2, only keep it native arm64 in any situation. You must install miniforge not anaconda and you must install the exact python version required. And of course if the release increases to alpha 4, you will need to adapt the instructions by yourself (by reading install_venv.sh). If you still have any trouble or want to do any custom thing, please directly ask your questions here to Apple.
[ { "code": null, "e": 260, "s": 172, "text": "Updated Instructions for TensorFlow 2.4 alpha 3. See details at the end of the article." }, { "code": null, "e": 262, "s": 260, "text": "—" }, { "code": null, "e": 440, "s": 262, "text": "The previous article was about the Machine Learning packages that works natively on Apple Silicon. I also explained how TensorFlow and scikit-learn can be installed on a Mac M1." }, { "code": null, "e": 563, "s": 440, "text": "In this article ATF 2.4 stand for TensorFlow 2.4 for Apple Silicon currently available from github in release 0.1 alpha 3." }, { "code": null, "e": 816, "s": 563, "text": "With ATF 2.4, standard installation requires creating a python environment while nearly no other package like scikit-learn can be installed from pip. This is making this environment quite useless for machine learning engineers except for small testing." }, { "code": null, "e": 1158, "s": 816, "text": "At the time of writing this article ATF 2.4 is not free of bugs. It cannot yet be used in a professional context. But it’s already possible to start working on personal Machine Learning projects with a Mac M1. Here I describe step by step how to install a full environment under Conda with every packages natively compiled for Apple Silicon:" }, { "code": null, "e": 1201, "s": 1158, "text": "ATF 2.4 (TensorFlow 2.4 for Apple Silicon)" }, { "code": null, "e": 1207, "s": 1201, "text": "numpy" }, { "code": null, "e": 1220, "s": 1207, "text": "scikit-learn" }, { "code": null, "e": 1227, "s": 1220, "text": "pandas" }, { "code": null, "e": 1238, "s": 1227, "text": "matplotlib" }, { "code": null, "e": 1249, "s": 1238, "text": "JupyterLab" }, { "code": null, "e": 1335, "s": 1249, "text": "Install Xcode Command Line Tools by downloading it from Apple Developer or by typing:" }, { "code": null, "e": 1358, "s": 1335, "text": "xcode-select --install" }, { "code": null, "e": 1425, "s": 1358, "text": "Install miniforge for arm64 (Apple Silicon) from miniforge github." }, { "code": null, "e": 1530, "s": 1425, "text": "Miniforge enables installing python packages natively compiled for Apple Silicon including scikit-learn." }, { "code": null, "e": 1663, "s": 1530, "text": "Download TensorFlow 2.4 from Apple github, untar it but don’t install it by using the provided script. Go under the arm64 directory:" }, { "code": null, "e": 1689, "s": 1663, "text": "cd tensorflow_macos/arm64" }, { "code": null, "e": 1809, "s": 1689, "text": "Don’t forget to open a new session or to source your .zshrc after miniforge install and before going through this step." }, { "code": null, "e": 2087, "s": 1809, "text": "Create an empty Conda environment, then activate it and install python 3.8 (as required for ATF 2.4) and all the needed packages. Please note numpy is unnecessary here as pandas already install it, but it will be overwritten in the last step with the version provided by Apple." }, { "code": null, "e": 2219, "s": 2087, "text": "conda create --name tf24conda activate tf24conda install -y python==3.8.6conda install -y pandas matplotlib scikit-learn jupyterlab" }, { "code": null, "e": 2325, "s": 2219, "text": "Now manually install ATF 2.4 packages exactly like install_venv.sh does but under your Conda environment." }, { "code": null, "e": 2541, "s": 2325, "text": "Please note the following instruction corresponds to the second ATF 2.4 release, namely 0.1 alpha 3. Any new release can require a different process, you will be able to adapt it by checking install_venv.sh content." }, { "code": null, "e": 3363, "s": 2541, "text": "# Install specific pip version and some other base packagespip install --force pip==20.2.4 wheel setuptools cached-property six packaging# Install all the packages provided by Apple but TensorFlowpip install --upgrade --no-dependencies --force numpy-1.18.5-cp38-cp38-macosx_11_0_arm64.whl grpcio-1.33.2-cp38-cp38-macosx_11_0_arm64.whl h5py-2.10.0-cp38-cp38-macosx_11_0_arm64.whl# Install additional packagespip install absl-py astunparse flatbuffers gast google_pasta keras_preprocessing opt_einsum protobuf tensorflow_estimator termcolor typing_extensions wrapt wheel tensorboard typeguard# Install TensorFlowpip install --upgrade --force --no-dependencies tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whlpip install --upgrade --force --no-dependencies tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl" }, { "code": null, "e": 3409, "s": 3363, "text": "Now you can run JupyterLab and start working." }, { "code": null, "e": 3654, "s": 3409, "text": "Note that as pip installation can lead to inconsistencies with Conda packages previously installed, and especially because numpy is replaced by the 1.18.5 version shipped with ATF 2.4, there is no guarantee that it will work in every situation." }, { "code": null, "e": 3891, "s": 3654, "text": "For now, I’ve successfully trained several MLP and Convnet models while LSTM still have an issue with the evaluation on test set. I also trained RandomForest models and plot confusion matrix everything from JupyterLab without any issue." }, { "code": null, "e": 3965, "s": 3891, "text": "In the next article I will go through TensorFlow 2.4 benchmark on Mac M1." }, { "code": null, "e": 3988, "s": 3965, "text": "Thank you for reading." }, { "code": null, "e": 3990, "s": 3988, "text": "—" }, { "code": null, "e": 4267, "s": 3990, "text": "This article is updated with instructions for TensorFlow 2.4 alpha 3. Previously, I mentioned that initial instructions were only for alpha 1 release and that “Any new release can require a different process, you will be able to adapt it by checking install_venv.sh content.”." }, { "code": null, "e": 4400, "s": 4267, "text": "So you can use these instructions for installing TF 2.4 Alpha 3. Alternatively you can also use this process proposed on ATF GitHub." }, { "code": null, "e": 4433, "s": 4400, "text": "Some people reported errors like" }, { "code": null, "e": 4527, "s": 4433, "text": "ERROR: numpy-1.18.5-cp38-cp38-macosx_11_0_arm64.whl is not a supported wheel on this platform" } ]
Predicting survivors of Titanic. Who will survive a shipwreck? We can... | by Dorian Lazar | Towards Data Science
RMS Titanic was a British passenger liner operated by the White Star Line that sank in the North Atlantic Ocean in the early morning hours of April 15, 1912, after striking an iceberg during her maiden voyage from Southampton to New York City. Of the estimated 2,224 passengers and crew aboard, more than 1,500 died, making the sinking one of modern history’s deadliest peacetime commercial marine disasters. What we want now is to create a machine learning model that is able to predict who would survive Titanic’s shipwreck. For that we will use this dataset from Kaggle — there is also a Kaggle competition for this task which is a good place to get started with Kaggle competitions. This dataset contains the following information about the passengers: Now, before doing any machine learning on this dataset, it is a good practice to do some exploratory analysis and see how our data looks like. We also want to prepare/clean it along the way. import numpy as npimport pandas as pddf = pd.read_csv('train.csv')df df.describe() What do we see in our data at first glance? We see that the PassengerId column has an unique number associated with each passenger. This field can easily be used by machine learning algorithms to just memorize the outcomes for each passenger without the ability to generalize. Also, there is the Name variable which I personally don’t think it determines in any way if one person survived or not. So, we will delete these two variables. del df['PassengerId']del df['Name'] Now, let’s see if we have missing values and how many they are. df.isnull().sum() Out of 891 samples, 687 have null values for the Cabin variable. There are too many missing values for this variable to be able to make use of it. We will delete it. del df['Cabin'] We don’t want to delete the other two columns as they have few missing values, we will augment them.For the Embarked variable, as it is a categorical variable, we will look at the counts of each category and replace the 2 null values with the category that has most items. df['Embarked'].value_counts() The most frequent value for Embarked is ‘S’, so we will use it to replace the null values. df['Embarked'].loc[pd.isnull(df['Embarked'])] = 'S' For age we will replace missing values with the average age. mean_age_train = np.mean(df['Age'].loc[pd.isnull(df['Age']) == False].values)df['Age'].loc[pd.isnull(df['Age'])] = mean_age_train Note that we should store everything that we learn from our training data, such as Embarked class frequency or Age mean, as we will use this information when making predictions in case there are also missing values in test data.We will also compute and store Fare mean in case we need it on test data. mean_fare_train = np.mean(df['Fare'].loc[pd.isnull(df['Fare']) == False].values) We got rid of null values, now let’s see what’s next. Machine learning algorithms don’t work with text (at least not directly), we need to convert all strings with numbers. We will use ordinal encoding for this conversion. Ordinal encoding is a way to convert a categorical variable into numbers by assigning each category a number. We’re going to use Scikit-Learn’s OrdinalEncoder to apply this transformation on variables Sex, Ticket, Embarked.Before that, we will backup our current data format for future use. df_bkp = df.copy()from sklearn.preprocessing import OrdinalEncoderdf['Sex'] = OrdinalEncoder().fit_transform(df['Sex'].values.reshape((-1, 1)))df['Ticket'] = OrdinalEncoder().fit_transform(df['Ticket'].values.reshape((-1, 1)))df['Embarked'] = OrdinalEncoder().fit_transform(df['Embarked'].values.reshape((-1, 1))) Now we will visualize our data to see how the distribution of our variables varies across survived and not-survived classes.Below are histograms for each variable in our dataset (along with the code that generated it), in the left is the subset of people who survived, and in the right who didn’t survive. import matplotlib.pyplot as pltfrom IPython.display import display, Markdowndef show(txt): # this function is for printing markdown in jupyter notebook display(Markdown(txt))for i in range(1, 9): show(f'### {df.columns[i]}') f, (survived, not_survived) = plt.subplots(1, 2, sharey=True, figsize=(18, 8)) survived.hist(df.iloc[np.where(df['Survived'] == 1)[0], i]) survived.set_title('Survived')not_survived.hist(df.iloc[np.where(df['Survived'] == 0)[0], i]) not_survived.set_title('Not Survived') plt.show() Now, we will try a couple of machine learning methods on our dataset to see what results we get. The machine learning methods that we will use are: Logistic Regression Support Vector Machine Decision Tree K Nearest Neighbors Multi-Layer Perceptron Instead of choosing a fixed validation set to estimate the accuracy of the test set, we will use (5-fold) cross validation with Scikit-Learn’s cross_val_score which returns an array with scores for each cross validation iteration. from sklearn.model_selection import cross_val_scorefrom sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVCfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.neural_network import MLPClassifierX = df.iloc[:, 1:].valuesy = df.iloc[:, 0].values# Logistic Regressionlr = LogisticRegression()lr_score = np.mean(cross_val_score(lr, X, y))print(f'Logistic Regression: {lr_score}')# Support Vector Machinesvc = SVC()svc_score = np.mean(cross_val_score(svc, X, y))print(f'Support Vector Machine: {svc_score}')# Decision Treedtc = DecisionTreeClassifier()dtc_score = np.mean(cross_val_score(dtc, X, y))print(f'Decision Tree: {dtc_score}')# K Nearest Neighborsknc = KNeighborsClassifier()knc_score = np.mean(cross_val_score(knc, X, y))print(f'K Nearest Neighbors: {knc_score}')# Multi-Layer Perceptronmlpc = MLPClassifier()mlpc_score = np.mean(cross_val_score(mlpc, X, y))print(f'Multi-Layer Perceptron: {mlpc_score}') Running this code we got the following results: Let’s see if we can improve the accuracy by working on our dataset’s features. For that, we will restore first to the backup we made before applying ordinal encoding. df = df_bkp.copy() Instead of ordinal encoding, now we want to apply one-hot encoding to our categorical variables. With one-hot encoding, instead of assigning each class a number, we assign a vector with all 0’s except for one position specific to that class in which we put a 1. That is, we transform each class into a variable on its own that takes the value 0 or 1. We will apply one-hot encoding on the variables Pclass, Sex, Ticket and Embarked using Scikit-Learn’s OneHotEncoder. from sklearn.preprocessing import OneHotEncoder# Pclasspclass_transf = OneHotEncoder(sparse=False, dtype=np.uint8, handle_unknown='ignore')pclass_transf.fit(df['Pclass'].values.reshape((-1, 1)))pclass = pclass_transf.transform(df['Pclass'].values.reshape((-1, 1)))df['Pclass0'] = pclass[:, 0]df['Pclass1'] = pclass[:, 1]df['Pclass2'] = pclass[:, 2]del df['Pclass']# Sexgender_transf = OneHotEncoder(sparse=False, dtype=np.uint8, handle_unknown='ignore')gender_transf.fit(df['Sex'].values.reshape((-1, 1)))gender = gender_transf.transform(df['Sex'].values.reshape((-1, 1)))df['Male'] = gender[:, 0]df['Female'] = gender[:, 1]del df['Sex']# Ticketticket_transf = OneHotEncoder(sparse=False, dtype=np.uint8, handle_unknown='ignore')ticket_transf.fit(df['Ticket'].values.reshape((-1, 1)))ticket = ticket_transf.transform(df['Ticket'].values.reshape((-1, 1)))for i in range(ticket.shape[1]): df[f'Ticket{i}'] = ticket[:, i]del df['Ticket']# Embarkedembarked_transf = OneHotEncoder(sparse=False, dtype=np.uint8, handle_unknown='ignore')embarked_transf.fit(df['Embarked'].values.reshape((-1, 1)))embarked = embarked_transf.transform(df['Embarked'].values.reshape((-1, 1)))for i in range(embarked.shape[1]): df[f'Embarked{i}'] = embarked[:, i]del df['Embarked'] We also want to scale the numerical variables to [0, 1] range. For that we will use MinMaxScaler which scales the variables so that the minimum value is moved to 0, the maximum to 1 and other intermediary values are scaled accordingly in between 0, 1. We will apply this transformation to variables Age, SibSp, Parch, Fare. from sklearn.preprocessing import MinMaxScalerage_transf = MinMaxScaler().fit(df['Age'].values.reshape(-1, 1))df['Age'] = age_transf.transform(df['Age'].values.reshape(-1, 1))sibsp_transf = MinMaxScaler().fit(df['SibSp'].values.reshape(-1, 1))df['SibSp'] = sibsp_transf.transform(df['SibSp'].values.reshape(-1, 1))parch_transf = MinMaxScaler().fit(df['Parch'].values.reshape(-1, 1))df['Parch'] = parch_transf.transform(df['Parch'].values.reshape(-1, 1))fare_transf = MinMaxScaler().fit(df['Fare'].values.reshape(-1, 1))df['Fare'] = fare_transf.transform(df['Fare'].values.reshape(-1, 1)) Now we will run the same machine learning algorithms on this new data format to see what results we get. X = df.iloc[:, 1:].valuesy = df.iloc[:, 0].values# Logistic Regressionlr = LogisticRegression()lr_score = np.mean(cross_val_score(lr, X, y))print(f'Logistic Regression: {lr_score}')# Support Vector Machinesvc = SVC()svc_score = np.mean(cross_val_score(svc, X, y))print(f'Support Vector Machine: {svc_score}')# Decision Treedtc = DecisionTreeClassifier()dtc_score = np.mean(cross_val_score(dtc, X, y))print(f'Decision Tree: {dtc_score}')# K Nearest Neighborsknc = KNeighborsClassifier()knc_score = np.mean(cross_val_score(knc, X, y))print(f'K Nearest Neighbors: {knc_score}')# Multi-Layer Perceptronmlpc = MLPClassifier()mlpc_score = np.mean(cross_val_score(mlpc, X, y))print(f'Multi-Layer Perceptron: {mlpc_score}') After we engineered our features in this way we got an significant improvement in the accuracy of all classifiers. The best classifier among them being Decision Tree Classifier. Now we try to improve it by doing hyper-parameter tuning using GridSearchCV. from sklearn.model_selection import GridSearchCVdtc = DecisionTreeClassifier()params = { 'max_depth': list(range(2, 151)), 'min_samples_split': list(range(2, 15))}clf = GridSearchCV(dtc, params)clf.fit(X, y)print(f'Best params: {clf.best_params_}')print(f'Best score: {clf.best_score_}') The parameters that we got are: And the score that we got is 84.40%, an improvement of 0.9% after hyperparameter tuning. I hope you found this information useful and thanks for reading! This article is also posted on my own website here. Feel free to have a look!
[ { "code": null, "e": 581, "s": 172, "text": "RMS Titanic was a British passenger liner operated by the White Star Line that sank in the North Atlantic Ocean in the early morning hours of April 15, 1912, after striking an iceberg during her maiden voyage from Southampton to New York City. Of the estimated 2,224 passengers and crew aboard, more than 1,500 died, making the sinking one of modern history’s deadliest peacetime commercial marine disasters." }, { "code": null, "e": 929, "s": 581, "text": "What we want now is to create a machine learning model that is able to predict who would survive Titanic’s shipwreck. For that we will use this dataset from Kaggle — there is also a Kaggle competition for this task which is a good place to get started with Kaggle competitions. This dataset contains the following information about the passengers:" }, { "code": null, "e": 1120, "s": 929, "text": "Now, before doing any machine learning on this dataset, it is a good practice to do some exploratory analysis and see how our data looks like. We also want to prepare/clean it along the way." }, { "code": null, "e": 1189, "s": 1120, "text": "import numpy as npimport pandas as pddf = pd.read_csv('train.csv')df" }, { "code": null, "e": 1203, "s": 1189, "text": "df.describe()" }, { "code": null, "e": 1640, "s": 1203, "text": "What do we see in our data at first glance? We see that the PassengerId column has an unique number associated with each passenger. This field can easily be used by machine learning algorithms to just memorize the outcomes for each passenger without the ability to generalize. Also, there is the Name variable which I personally don’t think it determines in any way if one person survived or not. So, we will delete these two variables." }, { "code": null, "e": 1676, "s": 1640, "text": "del df['PassengerId']del df['Name']" }, { "code": null, "e": 1740, "s": 1676, "text": "Now, let’s see if we have missing values and how many they are." }, { "code": null, "e": 1758, "s": 1740, "text": "df.isnull().sum()" }, { "code": null, "e": 1924, "s": 1758, "text": "Out of 891 samples, 687 have null values for the Cabin variable. There are too many missing values for this variable to be able to make use of it. We will delete it." }, { "code": null, "e": 1940, "s": 1924, "text": "del df['Cabin']" }, { "code": null, "e": 2213, "s": 1940, "text": "We don’t want to delete the other two columns as they have few missing values, we will augment them.For the Embarked variable, as it is a categorical variable, we will look at the counts of each category and replace the 2 null values with the category that has most items." }, { "code": null, "e": 2243, "s": 2213, "text": "df['Embarked'].value_counts()" }, { "code": null, "e": 2334, "s": 2243, "text": "The most frequent value for Embarked is ‘S’, so we will use it to replace the null values." }, { "code": null, "e": 2386, "s": 2334, "text": "df['Embarked'].loc[pd.isnull(df['Embarked'])] = 'S'" }, { "code": null, "e": 2447, "s": 2386, "text": "For age we will replace missing values with the average age." }, { "code": null, "e": 2577, "s": 2447, "text": "mean_age_train = np.mean(df['Age'].loc[pd.isnull(df['Age']) == False].values)df['Age'].loc[pd.isnull(df['Age'])] = mean_age_train" }, { "code": null, "e": 2879, "s": 2577, "text": "Note that we should store everything that we learn from our training data, such as Embarked class frequency or Age mean, as we will use this information when making predictions in case there are also missing values in test data.We will also compute and store Fare mean in case we need it on test data." }, { "code": null, "e": 2960, "s": 2879, "text": "mean_fare_train = np.mean(df['Fare'].loc[pd.isnull(df['Fare']) == False].values)" }, { "code": null, "e": 3014, "s": 2960, "text": "We got rid of null values, now let’s see what’s next." }, { "code": null, "e": 3474, "s": 3014, "text": "Machine learning algorithms don’t work with text (at least not directly), we need to convert all strings with numbers. We will use ordinal encoding for this conversion. Ordinal encoding is a way to convert a categorical variable into numbers by assigning each category a number. We’re going to use Scikit-Learn’s OrdinalEncoder to apply this transformation on variables Sex, Ticket, Embarked.Before that, we will backup our current data format for future use." }, { "code": null, "e": 3788, "s": 3474, "text": "df_bkp = df.copy()from sklearn.preprocessing import OrdinalEncoderdf['Sex'] = OrdinalEncoder().fit_transform(df['Sex'].values.reshape((-1, 1)))df['Ticket'] = OrdinalEncoder().fit_transform(df['Ticket'].values.reshape((-1, 1)))df['Embarked'] = OrdinalEncoder().fit_transform(df['Embarked'].values.reshape((-1, 1)))" }, { "code": null, "e": 4094, "s": 3788, "text": "Now we will visualize our data to see how the distribution of our variables varies across survived and not-survived classes.Below are histograms for each variable in our dataset (along with the code that generated it), in the left is the subset of people who survived, and in the right who didn’t survive." }, { "code": null, "e": 4626, "s": 4094, "text": "import matplotlib.pyplot as pltfrom IPython.display import display, Markdowndef show(txt): # this function is for printing markdown in jupyter notebook display(Markdown(txt))for i in range(1, 9): show(f'### {df.columns[i]}') f, (survived, not_survived) = plt.subplots(1, 2, sharey=True, figsize=(18, 8)) survived.hist(df.iloc[np.where(df['Survived'] == 1)[0], i]) survived.set_title('Survived')not_survived.hist(df.iloc[np.where(df['Survived'] == 0)[0], i]) not_survived.set_title('Not Survived') plt.show()" }, { "code": null, "e": 4774, "s": 4626, "text": "Now, we will try a couple of machine learning methods on our dataset to see what results we get. The machine learning methods that we will use are:" }, { "code": null, "e": 4794, "s": 4774, "text": "Logistic Regression" }, { "code": null, "e": 4817, "s": 4794, "text": "Support Vector Machine" }, { "code": null, "e": 4831, "s": 4817, "text": "Decision Tree" }, { "code": null, "e": 4851, "s": 4831, "text": "K Nearest Neighbors" }, { "code": null, "e": 4874, "s": 4851, "text": "Multi-Layer Perceptron" }, { "code": null, "e": 5105, "s": 4874, "text": "Instead of choosing a fixed validation set to estimate the accuracy of the test set, we will use (5-fold) cross validation with Scikit-Learn’s cross_val_score which returns an array with scores for each cross validation iteration." }, { "code": null, "e": 6095, "s": 5105, "text": "from sklearn.model_selection import cross_val_scorefrom sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVCfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.neural_network import MLPClassifierX = df.iloc[:, 1:].valuesy = df.iloc[:, 0].values# Logistic Regressionlr = LogisticRegression()lr_score = np.mean(cross_val_score(lr, X, y))print(f'Logistic Regression: {lr_score}')# Support Vector Machinesvc = SVC()svc_score = np.mean(cross_val_score(svc, X, y))print(f'Support Vector Machine: {svc_score}')# Decision Treedtc = DecisionTreeClassifier()dtc_score = np.mean(cross_val_score(dtc, X, y))print(f'Decision Tree: {dtc_score}')# K Nearest Neighborsknc = KNeighborsClassifier()knc_score = np.mean(cross_val_score(knc, X, y))print(f'K Nearest Neighbors: {knc_score}')# Multi-Layer Perceptronmlpc = MLPClassifier()mlpc_score = np.mean(cross_val_score(mlpc, X, y))print(f'Multi-Layer Perceptron: {mlpc_score}')" }, { "code": null, "e": 6143, "s": 6095, "text": "Running this code we got the following results:" }, { "code": null, "e": 6310, "s": 6143, "text": "Let’s see if we can improve the accuracy by working on our dataset’s features. For that, we will restore first to the backup we made before applying ordinal encoding." }, { "code": null, "e": 6329, "s": 6310, "text": "df = df_bkp.copy()" }, { "code": null, "e": 6797, "s": 6329, "text": "Instead of ordinal encoding, now we want to apply one-hot encoding to our categorical variables. With one-hot encoding, instead of assigning each class a number, we assign a vector with all 0’s except for one position specific to that class in which we put a 1. That is, we transform each class into a variable on its own that takes the value 0 or 1. We will apply one-hot encoding on the variables Pclass, Sex, Ticket and Embarked using Scikit-Learn’s OneHotEncoder." }, { "code": null, "e": 8057, "s": 6797, "text": "from sklearn.preprocessing import OneHotEncoder# Pclasspclass_transf = OneHotEncoder(sparse=False, dtype=np.uint8, handle_unknown='ignore')pclass_transf.fit(df['Pclass'].values.reshape((-1, 1)))pclass = pclass_transf.transform(df['Pclass'].values.reshape((-1, 1)))df['Pclass0'] = pclass[:, 0]df['Pclass1'] = pclass[:, 1]df['Pclass2'] = pclass[:, 2]del df['Pclass']# Sexgender_transf = OneHotEncoder(sparse=False, dtype=np.uint8, handle_unknown='ignore')gender_transf.fit(df['Sex'].values.reshape((-1, 1)))gender = gender_transf.transform(df['Sex'].values.reshape((-1, 1)))df['Male'] = gender[:, 0]df['Female'] = gender[:, 1]del df['Sex']# Ticketticket_transf = OneHotEncoder(sparse=False, dtype=np.uint8, handle_unknown='ignore')ticket_transf.fit(df['Ticket'].values.reshape((-1, 1)))ticket = ticket_transf.transform(df['Ticket'].values.reshape((-1, 1)))for i in range(ticket.shape[1]): df[f'Ticket{i}'] = ticket[:, i]del df['Ticket']# Embarkedembarked_transf = OneHotEncoder(sparse=False, dtype=np.uint8, handle_unknown='ignore')embarked_transf.fit(df['Embarked'].values.reshape((-1, 1)))embarked = embarked_transf.transform(df['Embarked'].values.reshape((-1, 1)))for i in range(embarked.shape[1]): df[f'Embarked{i}'] = embarked[:, i]del df['Embarked']" }, { "code": null, "e": 8381, "s": 8057, "text": "We also want to scale the numerical variables to [0, 1] range. For that we will use MinMaxScaler which scales the variables so that the minimum value is moved to 0, the maximum to 1 and other intermediary values are scaled accordingly in between 0, 1. We will apply this transformation to variables Age, SibSp, Parch, Fare." }, { "code": null, "e": 8969, "s": 8381, "text": "from sklearn.preprocessing import MinMaxScalerage_transf = MinMaxScaler().fit(df['Age'].values.reshape(-1, 1))df['Age'] = age_transf.transform(df['Age'].values.reshape(-1, 1))sibsp_transf = MinMaxScaler().fit(df['SibSp'].values.reshape(-1, 1))df['SibSp'] = sibsp_transf.transform(df['SibSp'].values.reshape(-1, 1))parch_transf = MinMaxScaler().fit(df['Parch'].values.reshape(-1, 1))df['Parch'] = parch_transf.transform(df['Parch'].values.reshape(-1, 1))fare_transf = MinMaxScaler().fit(df['Fare'].values.reshape(-1, 1))df['Fare'] = fare_transf.transform(df['Fare'].values.reshape(-1, 1))" }, { "code": null, "e": 9074, "s": 8969, "text": "Now we will run the same machine learning algorithms on this new data format to see what results we get." }, { "code": null, "e": 9790, "s": 9074, "text": "X = df.iloc[:, 1:].valuesy = df.iloc[:, 0].values# Logistic Regressionlr = LogisticRegression()lr_score = np.mean(cross_val_score(lr, X, y))print(f'Logistic Regression: {lr_score}')# Support Vector Machinesvc = SVC()svc_score = np.mean(cross_val_score(svc, X, y))print(f'Support Vector Machine: {svc_score}')# Decision Treedtc = DecisionTreeClassifier()dtc_score = np.mean(cross_val_score(dtc, X, y))print(f'Decision Tree: {dtc_score}')# K Nearest Neighborsknc = KNeighborsClassifier()knc_score = np.mean(cross_val_score(knc, X, y))print(f'K Nearest Neighbors: {knc_score}')# Multi-Layer Perceptronmlpc = MLPClassifier()mlpc_score = np.mean(cross_val_score(mlpc, X, y))print(f'Multi-Layer Perceptron: {mlpc_score}')" }, { "code": null, "e": 10045, "s": 9790, "text": "After we engineered our features in this way we got an significant improvement in the accuracy of all classifiers. The best classifier among them being Decision Tree Classifier. Now we try to improve it by doing hyper-parameter tuning using GridSearchCV." }, { "code": null, "e": 10339, "s": 10045, "text": "from sklearn.model_selection import GridSearchCVdtc = DecisionTreeClassifier()params = { 'max_depth': list(range(2, 151)), 'min_samples_split': list(range(2, 15))}clf = GridSearchCV(dtc, params)clf.fit(X, y)print(f'Best params: {clf.best_params_}')print(f'Best score: {clf.best_score_}')" }, { "code": null, "e": 10371, "s": 10339, "text": "The parameters that we got are:" }, { "code": null, "e": 10460, "s": 10371, "text": "And the score that we got is 84.40%, an improvement of 0.9% after hyperparameter tuning." }, { "code": null, "e": 10525, "s": 10460, "text": "I hope you found this information useful and thanks for reading!" } ]
DynamoDB - Create Table
Creating a table generally consists of spawning the table, naming it, establishing its primary key attributes, and setting attribute data types. Utilize the GUI Console, Java, or another option to perform these tasks. Create a table by accessing the console at https://console.aws.amazon.com/dynamodb. Then choose the “Create Table” option. Our example generates a table populated with product information, with products of unique attributes identified by an ID number (numeric attribute). In the Create Table screen, enter the table name within the table name field; enter the primary key (ID) within the partition key field; and enter “Number” for the data type. After entering all information, select Create. Use Java to create the same table. Its primary key consists of the following two attributes − ID − Use a partition key, and the ScalarAttributeType N, meaning number. ID − Use a partition key, and the ScalarAttributeType N, meaning number. Nomenclature − Use a sort key, and the ScalarAttributeType S, meaning string. Nomenclature − Use a sort key, and the ScalarAttributeType S, meaning string. Java uses the createTable method to generate a table; and within the call, table name, primary key attributes, and attribute data types are specified. You can review the following example − import java.util.Arrays; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; public class ProductsCreateTable { public static void main(String[] args) throws Exception { AmazonDynamoDBClient client = new AmazonDynamoDBClient() .withEndpoint("http://localhost:8000"); DynamoDB dynamoDB = new DynamoDB(client); String tableName = "Products"; try { System.out.println("Creating the table, wait..."); Table table = dynamoDB.createTable (tableName, Arrays.asList ( new KeySchemaElement("ID", KeyType.HASH), // the partition key // the sort key new KeySchemaElement("Nomenclature", KeyType.RANGE) ), Arrays.asList ( new AttributeDefinition("ID", ScalarAttributeType.N), new AttributeDefinition("Nomenclature", ScalarAttributeType.S) ), new ProvisionedThroughput(10L, 10L) ); table.waitForActive(); System.out.println("Table created successfully. Status: " + table.getDescription().getTableStatus()); } catch (Exception e) { System.err.println("Cannot create the table: "); System.err.println(e.getMessage()); } } } In the above example, note the endpoint: .withEndpoint. It indicates the use of a local install by using the localhost. Also, note the required ProvisionedThroughput parameter, which the local install ignores. 16 Lectures 1.5 hours Harshit Srivastava 49 Lectures 3.5 hours Niyazi Erdogan 48 Lectures 3 hours Niyazi Erdogan 13 Lectures 1 hours Harshit Srivastava 45 Lectures 4 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2536, "s": 2391, "text": "Creating a table generally consists of spawning the table, naming it, establishing its primary key attributes, and setting attribute data types." }, { "code": null, "e": 2609, "s": 2536, "text": "Utilize the GUI Console, Java, or another option to perform these tasks." }, { "code": null, "e": 2732, "s": 2609, "text": "Create a table by accessing the console at https://console.aws.amazon.com/dynamodb. Then choose the “Create Table” option." }, { "code": null, "e": 3056, "s": 2732, "text": "Our example generates a table populated with product information, with products of unique attributes identified by an ID number (numeric attribute). In the Create Table screen, enter the table name within the table name field; enter the primary key (ID) within the partition key field; and enter “Number” for the data type." }, { "code": null, "e": 3103, "s": 3056, "text": "After entering all information, select Create." }, { "code": null, "e": 3197, "s": 3103, "text": "Use Java to create the same table. Its primary key consists of the following two attributes −" }, { "code": null, "e": 3270, "s": 3197, "text": "ID − Use a partition key, and the ScalarAttributeType N, meaning number." }, { "code": null, "e": 3343, "s": 3270, "text": "ID − Use a partition key, and the ScalarAttributeType N, meaning number." }, { "code": null, "e": 3421, "s": 3343, "text": "Nomenclature − Use a sort key, and the ScalarAttributeType S, meaning string." }, { "code": null, "e": 3499, "s": 3421, "text": "Nomenclature − Use a sort key, and the ScalarAttributeType S, meaning string." }, { "code": null, "e": 3650, "s": 3499, "text": "Java uses the createTable method to generate a table; and within the call, table name, primary key attributes, and attribute data types are specified." }, { "code": null, "e": 3689, "s": 3650, "text": "You can review the following example −" }, { "code": null, "e": 5512, "s": 3689, "text": "import java.util.Arrays;\n \nimport com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; \nimport com.amazonaws.services.dynamodbv2.document.DynamoDB; \nimport com.amazonaws.services.dynamodbv2.document.Table; \n\nimport com.amazonaws.services.dynamodbv2.model.AttributeDefinition; \nimport com.amazonaws.services.dynamodbv2.model.KeySchemaElement; \nimport com.amazonaws.services.dynamodbv2.model.KeyType; \nimport com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; \nimport com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;\n \npublic class ProductsCreateTable { \n public static void main(String[] args) throws Exception { \n AmazonDynamoDBClient client = new AmazonDynamoDBClient() \n .withEndpoint(\"http://localhost:8000\"); \n \n DynamoDB dynamoDB = new DynamoDB(client); \n String tableName = \"Products\"; \n try { \n System.out.println(\"Creating the table, wait...\"); \n Table table = dynamoDB.createTable (tableName, \n Arrays.asList ( \n new KeySchemaElement(\"ID\", KeyType.HASH), // the partition key \n // the sort key \n new KeySchemaElement(\"Nomenclature\", KeyType.RANGE)\n ),\n Arrays.asList ( \n new AttributeDefinition(\"ID\", ScalarAttributeType.N), \n new AttributeDefinition(\"Nomenclature\", ScalarAttributeType.S)\n ),\n new ProvisionedThroughput(10L, 10L)\n );\n table.waitForActive(); \n System.out.println(\"Table created successfully. Status: \" + \n table.getDescription().getTableStatus());\n \n } catch (Exception e) {\n System.err.println(\"Cannot create the table: \"); \n System.err.println(e.getMessage()); \n } \n } \n}" }, { "code": null, "e": 5568, "s": 5512, "text": "In the above example, note the endpoint: .withEndpoint." }, { "code": null, "e": 5722, "s": 5568, "text": "It indicates the use of a local install by using the localhost. Also, note the required ProvisionedThroughput parameter, which the local install ignores." }, { "code": null, "e": 5757, "s": 5722, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5777, "s": 5757, "text": " Harshit Srivastava" }, { "code": null, "e": 5812, "s": 5777, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5828, "s": 5812, "text": " Niyazi Erdogan" }, { "code": null, "e": 5861, "s": 5828, "text": "\n 48 Lectures \n 3 hours \n" }, { "code": null, "e": 5877, "s": 5861, "text": " Niyazi Erdogan" }, { "code": null, "e": 5910, "s": 5877, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 5930, "s": 5910, "text": " Harshit Srivastava" }, { "code": null, "e": 5963, "s": 5930, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 6003, "s": 5963, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 6010, "s": 6003, "text": " Print" }, { "code": null, "e": 6021, "s": 6010, "text": " Add Notes" } ]
How to change the color of gridlines of a ggplot2 graph in R?
To change the color of gridlines of a ggplot2 graph in R, we can use theme function with panel.grid.major and panel.grid.minor arguments where we can set the minor and major gridlines color of the plot panel to desired color. To understand how it can be done, check out the below Example. Following snippet creates a sample data frame − x<-sample(0:9,20,replace=TRUE) y<-sample(0:9,20,replace=TRUE) df<-data.frame(x,y) df The following dataframe is created x y 1 5 7 2 7 5 3 1 5 4 5 9 5 6 4 6 2 5 7 4 2 8 7 7 9 6 7 10 7 2 11 1 3 12 2 9 13 7 0 14 6 9 15 5 7 16 6 6 17 5 9 18 5 7 19 4 5 20 4 4 To load ggplot2 package and create scatterplot between x and y on the above created data frame, add the following code to the above snippet − x<-sample(0:9,20,replace=TRUE) y<-sample(0:9,20,replace=TRUE) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point() If you execute all the above given snippets as a single program, it generates the following Output − To create scatterplot between x and y with red color gridlines on the above created data frame, add the following code to the above snippet − x<-sample(0:9,20,replace=TRUE) y<-sample(0:9,20,replace=TRUE) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+theme(panel.grid.major=element_line(colour="re d"),panel.grid.minor=element_line(colour="red")) If you execute all the above given snippets as a single program, it generates the following Output −
[ { "code": null, "e": 1288, "s": 1062, "text": "To change the color of gridlines of a ggplot2 graph in R, we can use theme function with\npanel.grid.major and panel.grid.minor arguments where we can set the minor and major\ngridlines color of the plot panel to desired color." }, { "code": null, "e": 1351, "s": 1288, "text": "To understand how it can be done, check out the below Example." }, { "code": null, "e": 1399, "s": 1351, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1484, "s": 1399, "text": "x<-sample(0:9,20,replace=TRUE)\ny<-sample(0:9,20,replace=TRUE)\ndf<-data.frame(x,y)\ndf" }, { "code": null, "e": 1519, "s": 1484, "text": "The following dataframe is created" }, { "code": null, "e": 1665, "s": 1519, "text": " x y\n1 5 7\n2 7 5\n3 1 5\n4 5 9\n5 6 4\n6 2 5\n7 4 2\n8 7 7\n9 6 7\n10 7 2\n11 1 3\n12 2 9\n13 7 0\n14 6 9\n15 5 7\n16 6 6\n17 5 9\n18 5 7\n19 4 5\n20 4 4" }, { "code": null, "e": 1807, "s": 1665, "text": "To load ggplot2 package and create scatterplot between x and y on the above created\ndata frame, add the following code to the above snippet −" }, { "code": null, "e": 1939, "s": 1807, "text": "x<-sample(0:9,20,replace=TRUE)\ny<-sample(0:9,20,replace=TRUE)\ndf<-data.frame(x,y)\nlibrary(ggplot2)\nggplot(df,aes(x,y))+geom_point()" }, { "code": null, "e": 2040, "s": 1939, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 2182, "s": 2040, "text": "To create scatterplot between x and y with red color gridlines on the above created data\nframe, add the following code to the above snippet −" }, { "code": null, "e": 2410, "s": 2182, "text": "x<-sample(0:9,20,replace=TRUE)\ny<-sample(0:9,20,replace=TRUE)\ndf<-data.frame(x,y)\nlibrary(ggplot2)\nggplot(df,aes(x,y))+geom_point()+theme(panel.grid.major=element_line(colour=\"re\nd\"),panel.grid.minor=element_line(colour=\"red\"))" }, { "code": null, "e": 2511, "s": 2410, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" } ]
Apply a Function over a List of elements in R Programming - lapply() Function - GeeksforGeeks
16 Dec, 2021 lapply() function in R Programming Language is used to apply a function over a list of elements. Syntax: lapply(list, func) Parameters: list: list of elements func: operation to be applied R # R program to illustrate# lapply() function # Creating a matrixA = matrix(1:9, 3, 3) # Creating another matrixB = matrix(10:18, 3, 3) # Creating a listmyList = list(A, B) # applying lapply()determinant = lapply(myList, det)print(determinant) Output: [[1]] [1] 0 [[2]] [1] 5.329071e-15 R # R program to illustrate# lapply() function # Creating a matrixA = matrix(1:9, 3, 3) # Creating another matrixB = matrix(10:18, 3, 3) # Creating a listmyList = list(A, B) # applying lapply()sum = lapply(myList, sum)print(sum) Output: [, 1] [, 2] [, 3] [1, ] 1 4 7 [2, ] 2 5 8 [3, ] 3 6 9 [1] 28 80 162 [1] 6 120 504 kumar_satyam R List-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr Logistic Regression in R Programming How to Split Column Into Multiple Columns in R DataFrame? Control Statements in R Programming How to import an Excel File into R ? Replace Specific Characters in String in R How to filter R DataFrame by values in a column?
[ { "code": null, "e": 25162, "s": 25134, "text": "\n16 Dec, 2021" }, { "code": null, "e": 25260, "s": 25162, "text": "lapply() function in R Programming Language is used to apply a function over a list of elements. " }, { "code": null, "e": 25287, "s": 25260, "text": "Syntax: lapply(list, func)" }, { "code": null, "e": 25300, "s": 25287, "text": "Parameters: " }, { "code": null, "e": 25323, "s": 25300, "text": "list: list of elements" }, { "code": null, "e": 25353, "s": 25323, "text": "func: operation to be applied" }, { "code": null, "e": 25355, "s": 25353, "text": "R" }, { "code": "# R program to illustrate# lapply() function # Creating a matrixA = matrix(1:9, 3, 3) # Creating another matrixB = matrix(10:18, 3, 3) # Creating a listmyList = list(A, B) # applying lapply()determinant = lapply(myList, det)print(determinant)", "e": 25607, "s": 25355, "text": null }, { "code": null, "e": 25616, "s": 25607, "text": "Output: " }, { "code": null, "e": 25652, "s": 25616, "text": "[[1]]\n[1] 0\n\n[[2]]\n[1] 5.329071e-15" }, { "code": null, "e": 25654, "s": 25652, "text": "R" }, { "code": "# R program to illustrate# lapply() function # Creating a matrixA = matrix(1:9, 3, 3) # Creating another matrixB = matrix(10:18, 3, 3) # Creating a listmyList = list(A, B) # applying lapply()sum = lapply(myList, sum)print(sum)", "e": 25890, "s": 25654, "text": null }, { "code": null, "e": 25899, "s": 25890, "text": "Output: " }, { "code": null, "e": 26017, "s": 25899, "text": " [, 1] [, 2] [, 3]\n[1, ] 1 4 7\n[2, ] 2 5 8\n[3, ] 3 6 9\n[1] 28 80 162\n[1] 6 120 504" }, { "code": null, "e": 26030, "s": 26017, "text": "kumar_satyam" }, { "code": null, "e": 26046, "s": 26030, "text": "R List-Function" }, { "code": null, "e": 26057, "s": 26046, "text": "R Language" }, { "code": null, "e": 26155, "s": 26057, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26164, "s": 26155, "text": "Comments" }, { "code": null, "e": 26177, "s": 26164, "text": "Old Comments" }, { "code": null, "e": 26229, "s": 26177, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26253, "s": 26229, "text": "Data Visualization in R" }, { "code": null, "e": 26291, "s": 26253, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26326, "s": 26291, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26363, "s": 26326, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 26421, "s": 26363, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26457, "s": 26421, "text": "Control Statements in R Programming" }, { "code": null, "e": 26494, "s": 26457, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 26537, "s": 26494, "text": "Replace Specific Characters in String in R" } ]
A Python Pandas Introduction to Excel Users | by Frank Andrade | Towards Data Science
Pandas is probably the best tool to do real-world data analysis in Python. It allows us to clean data, wrangle data, make visualizations, and more. You can think of Pandas as a supercharged Microsoft Excel. Most of the tasks you can do in Excel can be done in Pandas too and vice versa. That said, there are many areas where Pandas outperforms Excel. In this introduction to Pandas, we will compare Pandas dataframes and Excel Spreadsheet, learn different ways to create a dataframe, and how to make pivot tables. Note: Before learning Pandas, you should know at least know the basics of Python. If you’re new to Python, check this guide I made to get started with Python in no time. Table of Contents1. Why Excel Users Should Learn Python/Pandas2. Pandas DataFrames & Excel Spreadsheets3. How to Create a Dataframe - Creating a dataframe by reading an Excel/CSV file - Creating a dataframe with arrays - Creating a dataframe with a dictionary Tasks such as data cleaning, data normalization, visualization, and statistical analysis can be performed on both Excel and Pandas. That said, Pandas has some major benefits over Excel. To name a few: Limitation by size: Excel can handle around 1 million rows, while Python can handle millions and millions of rows (the limitation is on PC computing power) Complex data transformation: Memory-intensive computations in Excel can crash a workbook. Python can handle complex computations without any major problem. Automation: Excel was not designed to automate tasks. You can create a macro or use VBA to simplify some tasks, but that’s the limit. However, Python can go beyond that with its hundreds of free libraries available. Cross-platform capabilities: On Excel, you might find some incompatibilities between formulas in Windows and macOS. This also happens when sharing Excel files with people that don’t have English as the default language on their version of Microsoft Excel. In contrast, Python code remains the same regardless of the operating system or language set on a computer. Before showing you how to replace Excel with Pandas (creating pivot tables, visualizations, etc), I will explain to you the core concepts of Pandas. Throughout this guide, I will mention Excel to provide some examples and compare it with Pandas. Excel is the most popular spreadsheet, so some analogies will help you grasp Pandas concepts fast. Let’s get started! The two main data structures in Pandas are series and dataframe. The first is a 1-dimensional array, while the second is a 2-dimensional array. In Pandas, we mainly work with dataframes. A Pandas dataframe is the equivalent of an Excel spreadsheet. Pandas dataframes — just like Excel spreadsheets — have 2 dimensions or axes. A dataframe has rows and columns (also known as series). On top of a dataframe, you will see the name of the columns and on the left side, there’s the index. By default index in Pandas start with 0. The intersection of a row and a column is called a data value or simply data. We can store different types of data such as integers, strings, boolean, and so on. Here’s a picture of a dataframe that shows US states ranked by population. I’m going to show you the code to create a dataframe like this later, but now let’s analyze this dataframe. The column names (states, population, and postal) are also known as features, while each row value is known as observation. We can say that there are 3 features and 4 observations. Keep in mind that a single column should have the same type of data. In our example, the states and postal columns only contain strings, while the population column only contains integers. We might get errors when trying to insert different data types into a column, so avoid doing this. To sum it up, this is the terminology translation between Pandas and Excel. We haven’t talked so much about empty cells so far, but it’s good for you to know that in Python missing data is represented with NaN, which stands for “Not a Number”. Whenever there’s an empty value in a dataframe, you’ll see an NaN. There are multiple ways to create a dataframe. We can create a dataframe by reading an Excel/CSV file, using arrays, and also with dictionaries. But before creating a dataframe, make sure you have Python and Pandas installed. In case you’re new to Python, you can install it by watching this video. To install Pandas, run the command pip install pandas on the terminal or command prompt. In case you have Jupyter Notebook, you can install it from a code cell by running !pip install pandas This is without a doubt the easiest way to create a dataframe in Pandas. We only need to import pandas, use the read_csv() method and write the name of the Excel/CSV file within parentheses. Let’s read a CSV file that contains data about the GDP of countries around the world (You can find this file on this link) import pandas as pddf_gdp = pd.read_csv('gdp.csv')df_gdp In the code above, we renamed pandas as “pd.” This is only a convention to name pandas. After running the code above, you will see the following dataframe. That’s all you need to create a dataframe! Now you can start creating a pivot table from this dataframe by watching my video tutorial below. To create a dataframe with arrays we need to import Numpy first. Let’s import this library and create an array with random numbers. import numpy as npdata = np.array([[1, 4], [2, 5], [3, 6]]) That said, if you don’t feel comfortable working with Numpy yet, you can create the same arrays using a list notation. The result will be the same when creating a dataframe in the next step. data = [[1, 4], [2, 5], [3, 6]] To create a dataframe, we import pandas and use the .Dataframe() method. Inside parentheses, we can add the index and columns arguments to assign names. import pandas as pddf = pd.DataFrame(data, index=['row1', 'row2', 'row3'], columns=['col1', 'col2']) df is the standard name for a dataframe. If we print this df object, we obtain the following: We can also create a dataframe from a dictionary. This is my favorite choice because a dictionary allows us to organize data properly. As you might remember, a dictionary is made of a key and a value. We can set lists as data values and the key as the name of a column. Let’s create the population dataframe we’ve seen before using a dictionary. First, we create 2 lists: states, and population. # data used for the example (stored in lists)states = ["California", "Texas", "Florida", "New York"]population = [39613493, 29730311, 21944577, 19299981] Now we create a dictionary setting the stringsStates and Population as keys and the lists created before as data values. # Storing lists within a dictionarydict_states = {'States': states, 'Population': population} Once the dictionary is created, making a dataframe is as easy as using the .Dataframe() method, but this time we don’t need to specify the column argument because it’s already specified in the keys. df_population = pd.DataFrame(dict_states) If you print df_population, you will get this dataframe: Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF) If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to thousands of Python guides and Data science articles. If you sign up using my link, I’ll earn a small commission with no extra cost to you.
[ { "code": null, "e": 320, "s": 172, "text": "Pandas is probably the best tool to do real-world data analysis in Python. It allows us to clean data, wrangle data, make visualizations, and more." }, { "code": null, "e": 523, "s": 320, "text": "You can think of Pandas as a supercharged Microsoft Excel. Most of the tasks you can do in Excel can be done in Pandas too and vice versa. That said, there are many areas where Pandas outperforms Excel." }, { "code": null, "e": 686, "s": 523, "text": "In this introduction to Pandas, we will compare Pandas dataframes and Excel Spreadsheet, learn different ways to create a dataframe, and how to make pivot tables." }, { "code": null, "e": 856, "s": 686, "text": "Note: Before learning Pandas, you should know at least know the basics of Python. If you’re new to Python, check this guide I made to get started with Python in no time." }, { "code": null, "e": 1116, "s": 856, "text": "Table of Contents1. Why Excel Users Should Learn Python/Pandas2. Pandas DataFrames & Excel Spreadsheets3. How to Create a Dataframe - Creating a dataframe by reading an Excel/CSV file - Creating a dataframe with arrays - Creating a dataframe with a dictionary" }, { "code": null, "e": 1317, "s": 1116, "text": "Tasks such as data cleaning, data normalization, visualization, and statistical analysis can be performed on both Excel and Pandas. That said, Pandas has some major benefits over Excel. To name a few:" }, { "code": null, "e": 1473, "s": 1317, "text": "Limitation by size: Excel can handle around 1 million rows, while Python can handle millions and millions of rows (the limitation is on PC computing power)" }, { "code": null, "e": 1629, "s": 1473, "text": "Complex data transformation: Memory-intensive computations in Excel can crash a workbook. Python can handle complex computations without any major problem." }, { "code": null, "e": 1845, "s": 1629, "text": "Automation: Excel was not designed to automate tasks. You can create a macro or use VBA to simplify some tasks, but that’s the limit. However, Python can go beyond that with its hundreds of free libraries available." }, { "code": null, "e": 2209, "s": 1845, "text": "Cross-platform capabilities: On Excel, you might find some incompatibilities between formulas in Windows and macOS. This also happens when sharing Excel files with people that don’t have English as the default language on their version of Microsoft Excel. In contrast, Python code remains the same regardless of the operating system or language set on a computer." }, { "code": null, "e": 2554, "s": 2209, "text": "Before showing you how to replace Excel with Pandas (creating pivot tables, visualizations, etc), I will explain to you the core concepts of Pandas. Throughout this guide, I will mention Excel to provide some examples and compare it with Pandas. Excel is the most popular spreadsheet, so some analogies will help you grasp Pandas concepts fast." }, { "code": null, "e": 2573, "s": 2554, "text": "Let’s get started!" }, { "code": null, "e": 2717, "s": 2573, "text": "The two main data structures in Pandas are series and dataframe. The first is a 1-dimensional array, while the second is a 2-dimensional array." }, { "code": null, "e": 2900, "s": 2717, "text": "In Pandas, we mainly work with dataframes. A Pandas dataframe is the equivalent of an Excel spreadsheet. Pandas dataframes — just like Excel spreadsheets — have 2 dimensions or axes." }, { "code": null, "e": 3099, "s": 2900, "text": "A dataframe has rows and columns (also known as series). On top of a dataframe, you will see the name of the columns and on the left side, there’s the index. By default index in Pandas start with 0." }, { "code": null, "e": 3261, "s": 3099, "text": "The intersection of a row and a column is called a data value or simply data. We can store different types of data such as integers, strings, boolean, and so on." }, { "code": null, "e": 3444, "s": 3261, "text": "Here’s a picture of a dataframe that shows US states ranked by population. I’m going to show you the code to create a dataframe like this later, but now let’s analyze this dataframe." }, { "code": null, "e": 3625, "s": 3444, "text": "The column names (states, population, and postal) are also known as features, while each row value is known as observation. We can say that there are 3 features and 4 observations." }, { "code": null, "e": 3913, "s": 3625, "text": "Keep in mind that a single column should have the same type of data. In our example, the states and postal columns only contain strings, while the population column only contains integers. We might get errors when trying to insert different data types into a column, so avoid doing this." }, { "code": null, "e": 3989, "s": 3913, "text": "To sum it up, this is the terminology translation between Pandas and Excel." }, { "code": null, "e": 4224, "s": 3989, "text": "We haven’t talked so much about empty cells so far, but it’s good for you to know that in Python missing data is represented with NaN, which stands for “Not a Number”. Whenever there’s an empty value in a dataframe, you’ll see an NaN." }, { "code": null, "e": 4369, "s": 4224, "text": "There are multiple ways to create a dataframe. We can create a dataframe by reading an Excel/CSV file, using arrays, and also with dictionaries." }, { "code": null, "e": 4523, "s": 4369, "text": "But before creating a dataframe, make sure you have Python and Pandas installed. In case you’re new to Python, you can install it by watching this video." }, { "code": null, "e": 4714, "s": 4523, "text": "To install Pandas, run the command pip install pandas on the terminal or command prompt. In case you have Jupyter Notebook, you can install it from a code cell by running !pip install pandas" }, { "code": null, "e": 4905, "s": 4714, "text": "This is without a doubt the easiest way to create a dataframe in Pandas. We only need to import pandas, use the read_csv() method and write the name of the Excel/CSV file within parentheses." }, { "code": null, "e": 5028, "s": 4905, "text": "Let’s read a CSV file that contains data about the GDP of countries around the world (You can find this file on this link)" }, { "code": null, "e": 5085, "s": 5028, "text": "import pandas as pddf_gdp = pd.read_csv('gdp.csv')df_gdp" }, { "code": null, "e": 5241, "s": 5085, "text": "In the code above, we renamed pandas as “pd.” This is only a convention to name pandas. After running the code above, you will see the following dataframe." }, { "code": null, "e": 5382, "s": 5241, "text": "That’s all you need to create a dataframe! Now you can start creating a pivot table from this dataframe by watching my video tutorial below." }, { "code": null, "e": 5514, "s": 5382, "text": "To create a dataframe with arrays we need to import Numpy first. Let’s import this library and create an array with random numbers." }, { "code": null, "e": 5574, "s": 5514, "text": "import numpy as npdata = np.array([[1, 4], [2, 5], [3, 6]])" }, { "code": null, "e": 5765, "s": 5574, "text": "That said, if you don’t feel comfortable working with Numpy yet, you can create the same arrays using a list notation. The result will be the same when creating a dataframe in the next step." }, { "code": null, "e": 5797, "s": 5765, "text": "data = [[1, 4], [2, 5], [3, 6]]" }, { "code": null, "e": 5950, "s": 5797, "text": "To create a dataframe, we import pandas and use the .Dataframe() method. Inside parentheses, we can add the index and columns arguments to assign names." }, { "code": null, "e": 6067, "s": 5950, "text": "import pandas as pddf = pd.DataFrame(data, index=['row1', 'row2', 'row3'], columns=['col1', 'col2'])" }, { "code": null, "e": 6161, "s": 6067, "text": "df is the standard name for a dataframe. If we print this df object, we obtain the following:" }, { "code": null, "e": 6431, "s": 6161, "text": "We can also create a dataframe from a dictionary. This is my favorite choice because a dictionary allows us to organize data properly. As you might remember, a dictionary is made of a key and a value. We can set lists as data values and the key as the name of a column." }, { "code": null, "e": 6557, "s": 6431, "text": "Let’s create the population dataframe we’ve seen before using a dictionary. First, we create 2 lists: states, and population." }, { "code": null, "e": 6711, "s": 6557, "text": "# data used for the example (stored in lists)states = [\"California\", \"Texas\", \"Florida\", \"New York\"]population = [39613493, 29730311, 21944577, 19299981]" }, { "code": null, "e": 6832, "s": 6711, "text": "Now we create a dictionary setting the stringsStates and Population as keys and the lists created before as data values." }, { "code": null, "e": 6926, "s": 6832, "text": "# Storing lists within a dictionarydict_states = {'States': states, 'Population': population}" }, { "code": null, "e": 7125, "s": 6926, "text": "Once the dictionary is created, making a dataframe is as easy as using the .Dataframe() method, but this time we don’t need to specify the column argument because it’s already specified in the keys." }, { "code": null, "e": 7167, "s": 7125, "text": "df_population = pd.DataFrame(dict_states)" }, { "code": null, "e": 7224, "s": 7167, "text": "If you print df_population, you will get this dataframe:" }, { "code": null, "e": 7342, "s": 7224, "text": "Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)" } ]
InfluxDB Data Retention. How to down-sample data and keep it for... | by Shawn Stafford | Towards Data Science
Time series data is often used by operations teams to investigate performance issues. Since we cannot anticipate the source of a performance issue ahead of time, we often err on the side of caution and collect as much data as possible as frequently as possible. This makes it easy to get a very granular picture of what was happening in an environment within the last hour, day, or week. However, keeping more than a week or two of data can become difficult as the number of hosts and volume of data increases. There are many reasons why it may be necessary to retain data for longer periods of time. It is often useful to refer to data that is weeks, months, or even years old in the following cases: Capacity planning — by reviewing resource utilization over the past 12 to 24 months, you can project usage forward in order to forecast your budget requirements for the next fiscal year. Performance degradation — users often report that application performance “seems slower” than it did a few weeks or months ago. Having historical data at your fingertips makes it possible to quantify how much longer tasks are taking or whether there is a correlation between increased load and slower performance. When dealing with time series data, you will inevitably reach a point where you cannot retain all of the data at full granularity for an indefinite amount of time. A trade-off must be made between how long you retain the data, how much data you retain, and how granular the data is. This article covers how to implement a data retention policy in InfluxDB to ensure that you can down-sample your data, retain it for a specified duration, and perform regular backups to avoid data loss. For the purpose of this example, we will focus on CPU utilization metrics being collected by a collectd system daemon running on 3 hosts. In this scenario, collectd is submitting CPU data (“load_shortterm”) at 10 second intervals from every host being monitored. The data is being sent directly to InfluxDB using the collectd daemon and stored in a “metrics” database which is defined with a 7-day retention policy. The goal is to retain this data in a “longterm” database with a retention policy of 3 years. InfluxDB does not listen for collectd input by default. In order to allow data to be submitted by a collectd agent, the InfluxDB server must be configured to listen for collectd connections. This section describes how to configure collectd on a RHEL/CentOS system. The first step is to create a database on the InfluxDB server to store the incoming collectd data for 7 days. To do this, open a terminal window on the InfluxDB server and use the influx command to connect to the server. Run the following command to create a new database: CREATE DATABASE metrics WITH DURATION 7d The next step is to install collectd on the InfluxDB server so that the types.db specification file is available to InfluxDB: # Install the collectd RPM (available from the EPEL repo)yum install collectd# Locate the types.db file installed by the RPMrpm -ql collectd | grep types.db Update the InfluxDB config file (/etc/influxdb/influxdb.conf) to listen for collectd data and then restart the influxd service: [[collectd]] enabled = true bind-address = ":8096" database = "metrics" typesdb = "/usr/share/collectd/types.db" Once InfluxDB is listening for collectd input, you will need to install the collectd agent on each of the 3 hosts and configure it to send data to your InfluxDB server. If you’re not familiar with the InfluxDB data model, figuring out how to locate the data can be the first challenge. Each type of data being collected is referred to as a “measurement” and each measurement can have any number of “tags” associated with it. In the case of data reported by the collectd agent, a measurement will exist for each type of data you have configured the agent to report. The following commands can be executed in the influx command window to query the database and identify the measurements that will be used in later steps to define a continuous query. # Switch to the InfluxDB database containing the CollectD dataUSE metrics# Display a list of metrics in the databaseSHOW MEASUREMENTS# Display the tags (keys) used to uniquely identify CPU loadSHOW SERIES FROM load_shortterm The SHOW SERIES command should produce output similar to the following: load_shortterm,host=host1,type=loadload_shortterm,host=host2,type=loadload_shortterm,host=host3,type=load There are many options for defining a long-term retention policy in InfluxDB. One option is to create a new retention policy within the existing metrics database and store the long-term data alongside your short-term data: CREATE RETENTION POLICY longterm_policy ON metrics DURATION 156w REPLICATION 1 However, I would avoid creating multiple retention policies within a single database unless you have a particular justification for doing so. If there are multiple retention policies within a single database, your queries will need to reference the retention policy explicitly (database.policy.measurement) when operating on the data. This will make your queries more fragile because of the explicit references to a retention policy. In addition, the incoming data in the metrics database is high-volume transient data. It would be very expensive to back up the entire database and the impact of losing 1 week of very granular data would not be worth the effort. A better approach would be to define a separate database specifically for any long-term data you wish to retain. Doing so will make it easy to change the retention policy later or back up the entire database without affecting any external reports or queries. The following example shows how to create a database with a retention policy of 3 years (156 weeks): CREATE DATABASE longterm WITH DURATION 156w Create a continuous query to down-sample the data from 10 second intervals down to 15 minute intervals: CREATE CONTINUOUS QUERY aggregate_load ON longtermBEGIN SELECT max(value) AS value INTO longterm.autogen.load_shortterm FROM metrics.autogen.load_shortterm GROUP BY time(15m),* END Important Notes: The aggregation function you choose will depend on your use case. The max function is being used in this case because we typically care about the peak load average during an interval. Using a mean calculation would dilute these spikes and make it harder to identify short spikes in activity. The INTO and FROM clause require a fully qualified measurement (database.policy.measurement). If you define the default retention policy as part of the database creation as shown in the examples above, the retention policy will be called “autogen” by default. The GROUP BY clause contains a * wildcard, which means “all tags.” This ensures that the aggregation is performed across only the data points where all tags are identical. Without that wildcard (or an explicit list of tags), the aggregation would be performed across all data for all hosts, resulting in a single meaningless aggregation. In most cases a wildcard should be used in the GROUP BY to ensure that aggregation is performed on the same unique item. The multi-line formatting shown above is for readability. You’ll need to structure the command on a single line when executing it within the influx command. Once you have successfully created a continuous query, you should see measurements appear at the end of the first time interval. This can be verified by listing the measurements in the same way you discovered them previously: USE longtermSHOW MEASUREMENTSSHOW SERIES FROM load_shortterm The Grafana charts below show the difference between raw data (10 second intervals) and aggregated data (15 minute intervals). InfluxDB comes with a command-line utility for performing database backups. Execution is reasonably straight forward: influxd backup -portable -database longterm /backup/longterm Additional arguments can be specified to restrict the export by a specific retention policy, shard, or date range. By default, the InfluxDB service writes its logging output to /var/log/messages. Several lines of output are generated each time a continuous query is run. The following command can be used to look for continuous query execution messages: tail -f /var/log/messages | grep "Finished continuous" The matching lines will look something like this: Jan 7 15:00:00 influxdbhost01 influxd: ts=2019-01-07T20:00:00.127002Z lvl=info msg="Finished continuous query" log_id=0BoYFF20000 service=continuous_querier trace_id=0CrUFfTl000 op_name=continuous_querier_execute name=aggregate_load db_instance=longterm written=129 start=2019-01-07T19:59:00.000000Z end=2019-01-07T20:00:00.000000Z duration=7ms The log output contains several important pieces of information: name — the name of the continuous query written — the number of measurement records that were written duration — how long the query took to execute Obviously it would be a bad idea to define a continuous query that is scheduled to run more frequently than the time it takes to complete the query. Continuous queries are a convenient way to selectively down-sample data and retain it for longer periods of time. By creating thoughtful retention policies and backup procedures, it is possible to retain historical time series data for months or even years. Making this historical data readily accessible within the same visualization interface as your real-time metrics will empower application owners and operations staff to make informed decisions based on historical context and trends, rather than relying on a “gut feel” approach to budgeting, capacity planning, or problem investigation.
[ { "code": null, "e": 682, "s": 171, "text": "Time series data is often used by operations teams to investigate performance issues. Since we cannot anticipate the source of a performance issue ahead of time, we often err on the side of caution and collect as much data as possible as frequently as possible. This makes it easy to get a very granular picture of what was happening in an environment within the last hour, day, or week. However, keeping more than a week or two of data can become difficult as the number of hosts and volume of data increases." }, { "code": null, "e": 873, "s": 682, "text": "There are many reasons why it may be necessary to retain data for longer periods of time. It is often useful to refer to data that is weeks, months, or even years old in the following cases:" }, { "code": null, "e": 1060, "s": 873, "text": "Capacity planning — by reviewing resource utilization over the past 12 to 24 months, you can project usage forward in order to forecast your budget requirements for the next fiscal year." }, { "code": null, "e": 1374, "s": 1060, "text": "Performance degradation — users often report that application performance “seems slower” than it did a few weeks or months ago. Having historical data at your fingertips makes it possible to quantify how much longer tasks are taking or whether there is a correlation between increased load and slower performance." }, { "code": null, "e": 1860, "s": 1374, "text": "When dealing with time series data, you will inevitably reach a point where you cannot retain all of the data at full granularity for an indefinite amount of time. A trade-off must be made between how long you retain the data, how much data you retain, and how granular the data is. This article covers how to implement a data retention policy in InfluxDB to ensure that you can down-sample your data, retain it for a specified duration, and perform regular backups to avoid data loss." }, { "code": null, "e": 2369, "s": 1860, "text": "For the purpose of this example, we will focus on CPU utilization metrics being collected by a collectd system daemon running on 3 hosts. In this scenario, collectd is submitting CPU data (“load_shortterm”) at 10 second intervals from every host being monitored. The data is being sent directly to InfluxDB using the collectd daemon and stored in a “metrics” database which is defined with a 7-day retention policy. The goal is to retain this data in a “longterm” database with a retention policy of 3 years." }, { "code": null, "e": 2634, "s": 2369, "text": "InfluxDB does not listen for collectd input by default. In order to allow data to be submitted by a collectd agent, the InfluxDB server must be configured to listen for collectd connections. This section describes how to configure collectd on a RHEL/CentOS system." }, { "code": null, "e": 2907, "s": 2634, "text": "The first step is to create a database on the InfluxDB server to store the incoming collectd data for 7 days. To do this, open a terminal window on the InfluxDB server and use the influx command to connect to the server. Run the following command to create a new database:" }, { "code": null, "e": 2948, "s": 2907, "text": "CREATE DATABASE metrics WITH DURATION 7d" }, { "code": null, "e": 3074, "s": 2948, "text": "The next step is to install collectd on the InfluxDB server so that the types.db specification file is available to InfluxDB:" }, { "code": null, "e": 3231, "s": 3074, "text": "# Install the collectd RPM (available from the EPEL repo)yum install collectd# Locate the types.db file installed by the RPMrpm -ql collectd | grep types.db" }, { "code": null, "e": 3359, "s": 3231, "text": "Update the InfluxDB config file (/etc/influxdb/influxdb.conf) to listen for collectd data and then restart the influxd service:" }, { "code": null, "e": 3476, "s": 3359, "text": "[[collectd]] enabled = true bind-address = \":8096\" database = \"metrics\" typesdb = \"/usr/share/collectd/types.db\"" }, { "code": null, "e": 3645, "s": 3476, "text": "Once InfluxDB is listening for collectd input, you will need to install the collectd agent on each of the 3 hosts and configure it to send data to your InfluxDB server." }, { "code": null, "e": 4041, "s": 3645, "text": "If you’re not familiar with the InfluxDB data model, figuring out how to locate the data can be the first challenge. Each type of data being collected is referred to as a “measurement” and each measurement can have any number of “tags” associated with it. In the case of data reported by the collectd agent, a measurement will exist for each type of data you have configured the agent to report." }, { "code": null, "e": 4224, "s": 4041, "text": "The following commands can be executed in the influx command window to query the database and identify the measurements that will be used in later steps to define a continuous query." }, { "code": null, "e": 4449, "s": 4224, "text": "# Switch to the InfluxDB database containing the CollectD dataUSE metrics# Display a list of metrics in the databaseSHOW MEASUREMENTS# Display the tags (keys) used to uniquely identify CPU loadSHOW SERIES FROM load_shortterm" }, { "code": null, "e": 4521, "s": 4449, "text": "The SHOW SERIES command should produce output similar to the following:" }, { "code": null, "e": 4627, "s": 4521, "text": "load_shortterm,host=host1,type=loadload_shortterm,host=host2,type=loadload_shortterm,host=host3,type=load" }, { "code": null, "e": 4850, "s": 4627, "text": "There are many options for defining a long-term retention policy in InfluxDB. One option is to create a new retention policy within the existing metrics database and store the long-term data alongside your short-term data:" }, { "code": null, "e": 4929, "s": 4850, "text": "CREATE RETENTION POLICY longterm_policy ON metrics DURATION 156w REPLICATION 1" }, { "code": null, "e": 5363, "s": 4929, "text": "However, I would avoid creating multiple retention policies within a single database unless you have a particular justification for doing so. If there are multiple retention policies within a single database, your queries will need to reference the retention policy explicitly (database.policy.measurement) when operating on the data. This will make your queries more fragile because of the explicit references to a retention policy." }, { "code": null, "e": 5592, "s": 5363, "text": "In addition, the incoming data in the metrics database is high-volume transient data. It would be very expensive to back up the entire database and the impact of losing 1 week of very granular data would not be worth the effort." }, { "code": null, "e": 5952, "s": 5592, "text": "A better approach would be to define a separate database specifically for any long-term data you wish to retain. Doing so will make it easy to change the retention policy later or back up the entire database without affecting any external reports or queries. The following example shows how to create a database with a retention policy of 3 years (156 weeks):" }, { "code": null, "e": 5996, "s": 5952, "text": "CREATE DATABASE longterm WITH DURATION 156w" }, { "code": null, "e": 6100, "s": 5996, "text": "Create a continuous query to down-sample the data from 10 second intervals down to 15 minute intervals:" }, { "code": null, "e": 6288, "s": 6100, "text": "CREATE CONTINUOUS QUERY aggregate_load ON longtermBEGIN SELECT max(value) AS value INTO longterm.autogen.load_shortterm FROM metrics.autogen.load_shortterm GROUP BY time(15m),* END" }, { "code": null, "e": 6305, "s": 6288, "text": "Important Notes:" }, { "code": null, "e": 6597, "s": 6305, "text": "The aggregation function you choose will depend on your use case. The max function is being used in this case because we typically care about the peak load average during an interval. Using a mean calculation would dilute these spikes and make it harder to identify short spikes in activity." }, { "code": null, "e": 6857, "s": 6597, "text": "The INTO and FROM clause require a fully qualified measurement (database.policy.measurement). If you define the default retention policy as part of the database creation as shown in the examples above, the retention policy will be called “autogen” by default." }, { "code": null, "e": 7316, "s": 6857, "text": "The GROUP BY clause contains a * wildcard, which means “all tags.” This ensures that the aggregation is performed across only the data points where all tags are identical. Without that wildcard (or an explicit list of tags), the aggregation would be performed across all data for all hosts, resulting in a single meaningless aggregation. In most cases a wildcard should be used in the GROUP BY to ensure that aggregation is performed on the same unique item." }, { "code": null, "e": 7473, "s": 7316, "text": "The multi-line formatting shown above is for readability. You’ll need to structure the command on a single line when executing it within the influx command." }, { "code": null, "e": 7699, "s": 7473, "text": "Once you have successfully created a continuous query, you should see measurements appear at the end of the first time interval. This can be verified by listing the measurements in the same way you discovered them previously:" }, { "code": null, "e": 7760, "s": 7699, "text": "USE longtermSHOW MEASUREMENTSSHOW SERIES FROM load_shortterm" }, { "code": null, "e": 7887, "s": 7760, "text": "The Grafana charts below show the difference between raw data (10 second intervals) and aggregated data (15 minute intervals)." }, { "code": null, "e": 8005, "s": 7887, "text": "InfluxDB comes with a command-line utility for performing database backups. Execution is reasonably straight forward:" }, { "code": null, "e": 8066, "s": 8005, "text": "influxd backup -portable -database longterm /backup/longterm" }, { "code": null, "e": 8181, "s": 8066, "text": "Additional arguments can be specified to restrict the export by a specific retention policy, shard, or date range." }, { "code": null, "e": 8420, "s": 8181, "text": "By default, the InfluxDB service writes its logging output to /var/log/messages. Several lines of output are generated each time a continuous query is run. The following command can be used to look for continuous query execution messages:" }, { "code": null, "e": 8475, "s": 8420, "text": "tail -f /var/log/messages | grep \"Finished continuous\"" }, { "code": null, "e": 8525, "s": 8475, "text": "The matching lines will look something like this:" }, { "code": null, "e": 8910, "s": 8525, "text": "Jan 7 15:00:00 influxdbhost01 influxd: ts=2019-01-07T20:00:00.127002Z lvl=info msg=\"Finished continuous query\" log_id=0BoYFF20000 service=continuous_querier trace_id=0CrUFfTl000 op_name=continuous_querier_execute name=aggregate_load db_instance=longterm written=129 start=2019-01-07T19:59:00.000000Z end=2019-01-07T20:00:00.000000Z duration=7ms" }, { "code": null, "e": 8975, "s": 8910, "text": "The log output contains several important pieces of information:" }, { "code": null, "e": 9015, "s": 8975, "text": "name — the name of the continuous query" }, { "code": null, "e": 9077, "s": 9015, "text": "written — the number of measurement records that were written" }, { "code": null, "e": 9123, "s": 9077, "text": "duration — how long the query took to execute" }, { "code": null, "e": 9272, "s": 9123, "text": "Obviously it would be a bad idea to define a continuous query that is scheduled to run more frequently than the time it takes to complete the query." } ]
Java Program to create DefaultTableModel from two dimensional array
The DefaultTableModel is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects. At first create a two dimensional array for rows and columns − DefaultTableModel tableModel = new DefaultTableModel(new Object[][] { { "India", "Asia" }, { "Canada", "North America" }, { "Singapore", "Asia" }, { "Malaysia", "Asia" }, { "Philippins", "Asia" }, { "Oman", "Asia" }, { "Germany", "Europe" }, { "France", "Europe" } }, new Object[] { "Country", "Continent" }); Above, “Country” and “Continent” are the columns. Now, set the above set of rows and columns to JTable − JTable table = new JTable(tableModel); The following is an example to create DefaultTableModel from two dimensional array − package my; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SwingDemo { public static void main(String[] argv) throws Exception { DefaultTableModel tableModel = new DefaultTableModel(new Object[][] { { "India", "Asia" }, { "Canada", "North America" }, { "Singapore", "Asia" }, { "Malaysia", "Asia" }, { "Philippins", "Asia" }, { "Oman", "Asia" }, { "Germany", "Europe" }, { "France", "Europe" } }, new Object[] { "Country", "Continent" }); JTable table = new JTable(tableModel); Font font = new Font("Verdana", Font.PLAIN, 12); table.setFont(font); table.setRowHeight(30); JFrame frame = new JFrame(); frame.setSize(600, 400); frame.add(new JScrollPane(table)); frame.setVisible(true); } }
[ { "code": null, "e": 1245, "s": 1062, "text": "The DefaultTableModel is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects. At first create a two dimensional array for rows and columns −" }, { "code": null, "e": 1565, "s": 1245, "text": "DefaultTableModel tableModel = new DefaultTableModel(new Object[][] {\n { \"India\", \"Asia\" }, { \"Canada\", \"North America\" }, { \"Singapore\", \"Asia\" },\n { \"Malaysia\", \"Asia\" }, { \"Philippins\", \"Asia\" }, { \"Oman\", \"Asia\" },\n { \"Germany\", \"Europe\" }, { \"France\", \"Europe\" }\n },\nnew Object[] { \"Country\", \"Continent\" });" }, { "code": null, "e": 1670, "s": 1565, "text": "Above, “Country” and “Continent” are the columns. Now, set the above set of rows and columns to JTable −" }, { "code": null, "e": 1709, "s": 1670, "text": "JTable table = new JTable(tableModel);" }, { "code": null, "e": 1794, "s": 1709, "text": "The following is an example to create DefaultTableModel from two dimensional array −" }, { "code": null, "e": 2700, "s": 1794, "text": "package my;\nimport java.awt.Font;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.DefaultTableModel;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n DefaultTableModel tableModel = new DefaultTableModel(new Object[][] {\n { \"India\", \"Asia\" }, { \"Canada\", \"North America\" }, { \"Singapore\", \"Asia\" },\n { \"Malaysia\", \"Asia\" }, { \"Philippins\", \"Asia\" }, { \"Oman\", \"Asia\" },\n { \"Germany\", \"Europe\" }, { \"France\", \"Europe\" }\n },\n new Object[] { \"Country\", \"Continent\" });\n JTable table = new JTable(tableModel);\n Font font = new Font(\"Verdana\", Font.PLAIN, 12);\n table.setFont(font);\n table.setRowHeight(30);\n JFrame frame = new JFrame();\n frame.setSize(600, 400);\n frame.add(new JScrollPane(table));\n frame.setVisible(true);\n }\n}" } ]
Tolerance Stackups. And how to use Monte Carlo Simulations... | by Marguerite Siboni | Towards Data Science
Imagine you have 2 pucks that you want to fit tightly in an opening. If you just needed these three parts to fit together once, you could measure how tall the pucks were and then make your cut to that size and adjust it until it’s perfect. If you are trying to fit these three parts together a lot of times, that’s when things get dicey. Some of your stacks of pucks could be bigger than your opening and not fit. Some of your stacks of pucks could be much smaller than the opening and your parts will fit looser than you’d like. You may design your yellow puck to be 30 mm tall, but the pucks will more likely be sized somewhere between 29 and 31 mm tall. In this scenario, your yellow puck height has a tolerance1 of ± 1 mm. You could measure each part and pair the larger yellow pucks with the smaller red pucks and force everything to work. (This is a process known as binning). This does work, but measuring parts takes time. And as the old adage goes, time = money. Incidentally, time also equals time. So if you want to bin, you will need to be willing to spend a lot of time and money doing it. This is where tolerance stackups come in. When you have parts that you want to fit in an opening, tolerance stackups are a tool that allow you to determine whether or not your parts will always2 fit in your opening, even if you are making hundreds of thousands of these assemblies. A tolerance stackup is a way to create a loop that includes each critical dimension in the “stack.” It enables you to look at the dimensions and the tolerances for these values to figure out if your design will work and update accordingly. It typically looks like this: In situations like the example above, a tolerance stackup is fairly easy to put together and it gives you all the information you need to create a good design. A tolerance stackup stops being quite so useful if: You have many more dimensions in your stackupYou are looking at the tolerance of round parts and their radial fit.You already know the distribution your parts are coming in at You have many more dimensions in your stackup You are looking at the tolerance of round parts and their radial fit. You already know the distribution your parts are coming in at Each of these scenarios calls for a Monte Carlo simulation. In a Monte Carlo simulation, you generate realistic values3 for every dimension that you had included in your tolerance stack up. Once you’ve generated these values, you can add and subtract values going through the same loop to generate a distribution for the critical dimension (in our example, the gap from 4 to 1). Finally, you’ll want to set an intended yield4 and see what that critical dimension is for your yield. This may tell you that you can make your design gap smaller or that you need to make it larger. The distribution might tell you there’s a strong case for binning. Notice that the piece parts follow the specs of the parts as anticipated in the tolerance stackup. However, the resultant gap is distributed tightly enough that the tolerance on the gap is tighter than the RSS value from the tolerance stackup. To make things more interesting, let’s look at a radial example. Imagine you are fitting a plastic peg in to a metal opening as shown to the left. This peg has crush ribs on it5. You’d like to make the gap between the top plastic portion and the top metal portion as small as possible all around without ever crashing in to it. Seems simple, right? Unfortunately, it’s not. If everything was perfectly round, this would work well. But if you consider the scenarios drawn below, you’ll see that the tolerance stack up is missing some information. These images are exaggerations of realistic scenarios. A Monte Carlo simulation allows you to simulate a radial angle that each part is off center by and a radial angle that each part is the furthest from round at. By simulating your result, you can account for the times that the off center features coincidentally cause parts to fit and the times that they coincidentally cause parts to interfere. This often leads to a tighter and more realistic resultant tolerance than a tolerance stackup. This is because a tolerance stackup forces you to assume that the problem dimensions are all at the same radial angle when in reality, they almost certainly aren’t. I have pasted the code I used to generate this simulation below: # importing librariesimport numpy as np import pandas as pd import matplotlib.pyplot as plt%matplotlib inline # Generating part measurement datadf['purple_r'] = np.random.normal(15.05, .1, 1000)df['purple_off_center'] = np.random.normal(0, .02, 1000)df['angle_purple_off_center'] = np.random.uniform(0, 6.283185, 1000)df['grey_off_center'] = np.random.normal(0, .02, 1000)df['grey_r'] = np.random.normal(15.5, .03, 1000)df['angle_grey_off_center'] = np.random.uniform(0, 6.283185, 1000)# Generating assembly measurement data# Using df['angle_purple off center'] as direction of gapdf['Circularity Contribution Purple'] = df['purple_r']df['Concentricity Contribution Purple'] = df['purple_off_center']df['Circularity Contribution Grey'] = df['grey_r'] df['Concentricity Contribution Purple'] = df['grey_off_center'] * \np.cos(df['angle_purple_off_center']-df['angle_grey_off_center'])df['gap'] = np.abs(df['Circularity Contribution Purple']) + \df['Concentricity Contribution Purple'] - np.abs(df['Circularity Contribution Grey']) \- df['Concentricity Contribution Purple']# Part measurement data graphfig, ax = plt.subplots(2, ncols=3, figsize = (14, 8))ax = ax.ravel()ax[0].hist(df['purple_r'], bins =20, color='purple')ax[0].set_title('Distribution of \n- Purple Large Radius')ax[0].set_xlabel('mm')ax[1].hist(df['purple_off_center'], bins =20, color='purple')ax[1].set_title('Distribution of Concentricity\nof Features on Purple Part')ax[1].set_xlabel('mm')ax[2].hist(df['angle_purple_off_center'], bins =20, color='violet')ax[2].set_title('Distribution of Angle of\n Off Center for Purple Part')ax[2].set_xlabel('radians')ax[3].hist(df['grey_off_center'], bins =20, color='dimgray')ax[3].set_title('Distribution of Concentricity\nof Features on Grey Part')ax[3].set_xlabel('mm')ax[4].hist(df['angle_grey_off_center'], bins =20, color='lightgray')ax[4].set_title('Distribution of Angle of\n Off Center for Gray Part')ax[4].set_xlabel('radians')ax[5].hist(df['grey_r'], bins =20, color='dimgray')ax[5].set_title('Distribution of \n - Grey Large Radius')ax[5].set_xlabel('mm')plt.tight_layout();# Assembly measurement data graphfig, ax = plt.subplots(1, ncols=4, figsize = (14, 4))ax = ax.ravel()ax[0].hist(df['Circularity Contribution Purple'], bins =20, color='purple')ax[0].set_title('Circularity Contribution Distribution \n Purple Outer Radius')ax[1].hist(df['Concentricity Contribution Purple'], bins =20, color='violet')ax[1].set_title('Concentricty Contribution Distribution \n Purple Radii Relative to Each Other')ax[2].hist(df['Circularity Contribution Grey'], bins =20, color='dimgray')ax[2].set_title('Circularity Contribution Distribution \n Grey Outer Radius')ax[3].hist(df['Concentricity Contribution Purple'], bins =20, color='lightgray')ax[3].set_title('Concentricty Contribution Distribution \n Purple Radii Relative to Each Other')plt.tight_layout();# Final Gap Graphmu = df['gap'].mean()sigma = df['gap'].std()plt.hist(df['gap'], bins =20, color='black')plt.title('Resultant Gap Distributions', fontsize = 16)plt.axvline((mu-(3*sigma)), color='green', alpha=0.5)plt.axvline((mu+(3*sigma)), color='green', alpha=0.5)plt.axvline((mu+(3*sigma)), color='green', alpha=0.5)plt.xlabel("Gap (mm)")plt.ylabel("Assembly Count")plt.tight_layout(); [1] Tolerances are determined in a number of ways. The design engineer will specify in a part drawing the tolerance for each critical dimension. This tolerance is usually created based on best practices for part tolerances of that manufacturing method and based on feedback from the vendor who is creating the part. If the tolerance stackup indicates that it needs to be tighter than best practices, in many cases that can be done too, but will increase the cost of the part. [2] By always, I mean almost always. Outliers are always going to happen. Parts will be out of spec. You may even be willing to design knowing that you’ll throw away parts. For the purposes of this blog “always” actually means “as often as your intended yield.” [3] If this is being done before data is available, you can generate values based on how you would expect them to come in given your manufacturing process and quality. If you are already making parts, you can use the mean and standard deviation of each of your tools to generate data. [4] If you’ve heard the term “Six Sigma” before and ever wondered what it means, nothing you’ve heard from Jack Donaghy is real. It refers to setting your yield such that ± 3 standard deviations (six sigma) are in spec (i.e. you have a yield of 99.99966%) [5] Crush ribs are small ribs included in a softer part that will be crushed as it is pushed in to a harder part. Barring major issues with the circularity of the hard part or the crush ribs in the small part, this tends to create a fit close enough to centering the crushed feature within the crushing feature that you can assume the tolerance of the fit is zero.
[ { "code": null, "e": 702, "s": 172, "text": "Imagine you have 2 pucks that you want to fit tightly in an opening. If you just needed these three parts to fit together once, you could measure how tall the pucks were and then make your cut to that size and adjust it until it’s perfect. If you are trying to fit these three parts together a lot of times, that’s when things get dicey. Some of your stacks of pucks could be bigger than your opening and not fit. Some of your stacks of pucks could be much smaller than the opening and your parts will fit looser than you’d like." }, { "code": null, "e": 899, "s": 702, "text": "You may design your yellow puck to be 30 mm tall, but the pucks will more likely be sized somewhere between 29 and 31 mm tall. In this scenario, your yellow puck height has a tolerance1 of ± 1 mm." }, { "code": null, "e": 1275, "s": 899, "text": "You could measure each part and pair the larger yellow pucks with the smaller red pucks and force everything to work. (This is a process known as binning). This does work, but measuring parts takes time. And as the old adage goes, time = money. Incidentally, time also equals time. So if you want to bin, you will need to be willing to spend a lot of time and money doing it." }, { "code": null, "e": 1557, "s": 1275, "text": "This is where tolerance stackups come in. When you have parts that you want to fit in an opening, tolerance stackups are a tool that allow you to determine whether or not your parts will always2 fit in your opening, even if you are making hundreds of thousands of these assemblies." }, { "code": null, "e": 1827, "s": 1557, "text": "A tolerance stackup is a way to create a loop that includes each critical dimension in the “stack.” It enables you to look at the dimensions and the tolerances for these values to figure out if your design will work and update accordingly. It typically looks like this:" }, { "code": null, "e": 2039, "s": 1827, "text": "In situations like the example above, a tolerance stackup is fairly easy to put together and it gives you all the information you need to create a good design. A tolerance stackup stops being quite so useful if:" }, { "code": null, "e": 2215, "s": 2039, "text": "You have many more dimensions in your stackupYou are looking at the tolerance of round parts and their radial fit.You already know the distribution your parts are coming in at" }, { "code": null, "e": 2261, "s": 2215, "text": "You have many more dimensions in your stackup" }, { "code": null, "e": 2331, "s": 2261, "text": "You are looking at the tolerance of round parts and their radial fit." }, { "code": null, "e": 2393, "s": 2331, "text": "You already know the distribution your parts are coming in at" }, { "code": null, "e": 2453, "s": 2393, "text": "Each of these scenarios calls for a Monte Carlo simulation." }, { "code": null, "e": 3038, "s": 2453, "text": "In a Monte Carlo simulation, you generate realistic values3 for every dimension that you had included in your tolerance stack up. Once you’ve generated these values, you can add and subtract values going through the same loop to generate a distribution for the critical dimension (in our example, the gap from 4 to 1). Finally, you’ll want to set an intended yield4 and see what that critical dimension is for your yield. This may tell you that you can make your design gap smaller or that you need to make it larger. The distribution might tell you there’s a strong case for binning." }, { "code": null, "e": 3282, "s": 3038, "text": "Notice that the piece parts follow the specs of the parts as anticipated in the tolerance stackup. However, the resultant gap is distributed tightly enough that the tolerance on the gap is tighter than the RSS value from the tolerance stackup." }, { "code": null, "e": 3347, "s": 3282, "text": "To make things more interesting, let’s look at a radial example." }, { "code": null, "e": 3610, "s": 3347, "text": "Imagine you are fitting a plastic peg in to a metal opening as shown to the left. This peg has crush ribs on it5. You’d like to make the gap between the top plastic portion and the top metal portion as small as possible all around without ever crashing in to it." }, { "code": null, "e": 3883, "s": 3610, "text": "Seems simple, right? Unfortunately, it’s not. If everything was perfectly round, this would work well. But if you consider the scenarios drawn below, you’ll see that the tolerance stack up is missing some information. These images are exaggerations of realistic scenarios." }, { "code": null, "e": 4488, "s": 3883, "text": "A Monte Carlo simulation allows you to simulate a radial angle that each part is off center by and a radial angle that each part is the furthest from round at. By simulating your result, you can account for the times that the off center features coincidentally cause parts to fit and the times that they coincidentally cause parts to interfere. This often leads to a tighter and more realistic resultant tolerance than a tolerance stackup. This is because a tolerance stackup forces you to assume that the problem dimensions are all at the same radial angle when in reality, they almost certainly aren’t." }, { "code": null, "e": 4553, "s": 4488, "text": "I have pasted the code I used to generate this simulation below:" }, { "code": null, "e": 7812, "s": 4553, "text": "# importing librariesimport numpy as np import pandas as pd import matplotlib.pyplot as plt%matplotlib inline # Generating part measurement datadf['purple_r'] = np.random.normal(15.05, .1, 1000)df['purple_off_center'] = np.random.normal(0, .02, 1000)df['angle_purple_off_center'] = np.random.uniform(0, 6.283185, 1000)df['grey_off_center'] = np.random.normal(0, .02, 1000)df['grey_r'] = np.random.normal(15.5, .03, 1000)df['angle_grey_off_center'] = np.random.uniform(0, 6.283185, 1000)# Generating assembly measurement data# Using df['angle_purple off center'] as direction of gapdf['Circularity Contribution Purple'] = df['purple_r']df['Concentricity Contribution Purple'] = df['purple_off_center']df['Circularity Contribution Grey'] = df['grey_r'] df['Concentricity Contribution Purple'] = df['grey_off_center'] * \\np.cos(df['angle_purple_off_center']-df['angle_grey_off_center'])df['gap'] = np.abs(df['Circularity Contribution Purple']) + \\df['Concentricity Contribution Purple'] - np.abs(df['Circularity Contribution Grey']) \\- df['Concentricity Contribution Purple']# Part measurement data graphfig, ax = plt.subplots(2, ncols=3, figsize = (14, 8))ax = ax.ravel()ax[0].hist(df['purple_r'], bins =20, color='purple')ax[0].set_title('Distribution of \\n- Purple Large Radius')ax[0].set_xlabel('mm')ax[1].hist(df['purple_off_center'], bins =20, color='purple')ax[1].set_title('Distribution of Concentricity\\nof Features on Purple Part')ax[1].set_xlabel('mm')ax[2].hist(df['angle_purple_off_center'], bins =20, color='violet')ax[2].set_title('Distribution of Angle of\\n Off Center for Purple Part')ax[2].set_xlabel('radians')ax[3].hist(df['grey_off_center'], bins =20, color='dimgray')ax[3].set_title('Distribution of Concentricity\\nof Features on Grey Part')ax[3].set_xlabel('mm')ax[4].hist(df['angle_grey_off_center'], bins =20, color='lightgray')ax[4].set_title('Distribution of Angle of\\n Off Center for Gray Part')ax[4].set_xlabel('radians')ax[5].hist(df['grey_r'], bins =20, color='dimgray')ax[5].set_title('Distribution of \\n - Grey Large Radius')ax[5].set_xlabel('mm')plt.tight_layout();# Assembly measurement data graphfig, ax = plt.subplots(1, ncols=4, figsize = (14, 4))ax = ax.ravel()ax[0].hist(df['Circularity Contribution Purple'], bins =20, color='purple')ax[0].set_title('Circularity Contribution Distribution \\n Purple Outer Radius')ax[1].hist(df['Concentricity Contribution Purple'], bins =20, color='violet')ax[1].set_title('Concentricty Contribution Distribution \\n Purple Radii Relative to Each Other')ax[2].hist(df['Circularity Contribution Grey'], bins =20, color='dimgray')ax[2].set_title('Circularity Contribution Distribution \\n Grey Outer Radius')ax[3].hist(df['Concentricity Contribution Purple'], bins =20, color='lightgray')ax[3].set_title('Concentricty Contribution Distribution \\n Purple Radii Relative to Each Other')plt.tight_layout();# Final Gap Graphmu = df['gap'].mean()sigma = df['gap'].std()plt.hist(df['gap'], bins =20, color='black')plt.title('Resultant Gap Distributions', fontsize = 16)plt.axvline((mu-(3*sigma)), color='green', alpha=0.5)plt.axvline((mu+(3*sigma)), color='green', alpha=0.5)plt.axvline((mu+(3*sigma)), color='green', alpha=0.5)plt.xlabel(\"Gap (mm)\")plt.ylabel(\"Assembly Count\")plt.tight_layout();" }, { "code": null, "e": 8288, "s": 7812, "text": "[1] Tolerances are determined in a number of ways. The design engineer will specify in a part drawing the tolerance for each critical dimension. This tolerance is usually created based on best practices for part tolerances of that manufacturing method and based on feedback from the vendor who is creating the part. If the tolerance stackup indicates that it needs to be tighter than best practices, in many cases that can be done too, but will increase the cost of the part." }, { "code": null, "e": 8550, "s": 8288, "text": "[2] By always, I mean almost always. Outliers are always going to happen. Parts will be out of spec. You may even be willing to design knowing that you’ll throw away parts. For the purposes of this blog “always” actually means “as often as your intended yield.”" }, { "code": null, "e": 8835, "s": 8550, "text": "[3] If this is being done before data is available, you can generate values based on how you would expect them to come in given your manufacturing process and quality. If you are already making parts, you can use the mean and standard deviation of each of your tools to generate data." }, { "code": null, "e": 9091, "s": 8835, "text": "[4] If you’ve heard the term “Six Sigma” before and ever wondered what it means, nothing you’ve heard from Jack Donaghy is real. It refers to setting your yield such that ± 3 standard deviations (six sigma) are in spec (i.e. you have a yield of 99.99966%)" } ]
How do you test if a value is equal to NaN in Javascript?
The global NaN property in javascript is a value representing Not-A-Number. It is the returned value When Math functions fail (Math.sqrt(-500)) When a function trying to parse a number fails (parseFloat("test")) NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value. To test if a value is NaN, we must use Number.isNaN method. let a = Math.sqrt(-500); console.log(Number.isNaN(a)) true Note − isNaN() and Number.isNaN(): the former returns true if the value is currently NaN, or if it is going to be NaN after it is coerced to a number, while the latter will return true only if the value is currently NaN. isNaN('hello world'); Number.isNaN('hello world'); true false
[ { "code": null, "e": 1163, "s": 1062, "text": "The global NaN property in javascript is a value representing Not-A-Number. It is the returned value" }, { "code": null, "e": 1206, "s": 1163, "text": "When Math functions fail (Math.sqrt(-500))" }, { "code": null, "e": 1274, "s": 1206, "text": "When a function trying to parse a number fails (parseFloat(\"test\"))" }, { "code": null, "e": 1374, "s": 1274, "text": "NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value." }, { "code": null, "e": 1434, "s": 1374, "text": "To test if a value is NaN, we must use Number.isNaN method." }, { "code": null, "e": 1488, "s": 1434, "text": "let a = Math.sqrt(-500);\nconsole.log(Number.isNaN(a))" }, { "code": null, "e": 1493, "s": 1488, "text": "true" }, { "code": null, "e": 1714, "s": 1493, "text": "Note − isNaN() and Number.isNaN(): the former returns true if the value is currently NaN, or if it is going to be NaN after it is coerced to a number, while the latter will return true only if the value is currently NaN." }, { "code": null, "e": 1765, "s": 1714, "text": "isNaN('hello world');\nNumber.isNaN('hello world');" }, { "code": null, "e": 1776, "s": 1765, "text": "true\nfalse" } ]
\cal - Tex Command
\cal - turns on calligraphic mode; only affects uppercase letters and digits. { \cal ... } \cal command turns on calligraphic mode; only affects uppercase letters and digits. \cal ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ \cal 0123456789 0123456789 \cal abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz {\cal AB}AB ABAB \cal AB \rm AB ABAB \cal{AB}CD ABCD \cal ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ \cal ABCDEFGHIJKLMNOPQRSTUVWXYZ \cal 0123456789 0123456789 \cal 0123456789 \cal abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz \cal abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz {\cal AB}AB ABAB {\cal AB}AB \cal AB \rm AB ABAB \cal AB \rm AB \cal{AB}CD ABCD \cal{AB}CD 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8065, "s": 7986, "text": "\\cal - turns on calligraphic mode; only affects uppercase letters and digits." }, { "code": null, "e": 8078, "s": 8065, "text": "{ \\cal ... }" }, { "code": null, "e": 8162, "s": 8078, "text": "\\cal command turns on calligraphic mode; only affects uppercase letters and digits." }, { "code": null, "e": 8437, "s": 8162, "text": "\n\\cal ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n\n\n\\cal 0123456789\n\n0123456789\n\n\n\\cal abcdefghijklmnopqrstuvwxyz\n\nabcdefghijklmnopqrstuvwxyz\n\n\nabcdefghijklmnopqrstuvwxyz\n\nabcdefghijklmnopqrstuvwxyz\n\n\n{\\cal AB}AB\n\nABAB\n\n\n\\cal AB \\rm AB\n\nABAB\n\n\n\\cal{AB}CD\n\nABCD\n\n\n" }, { "code": null, "e": 8499, "s": 8437, "text": "\\cal ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n\n" }, { "code": null, "e": 8531, "s": 8499, "text": "\\cal ABCDEFGHIJKLMNOPQRSTUVWXYZ" }, { "code": null, "e": 8561, "s": 8531, "text": "\\cal 0123456789\n\n0123456789\n\n" }, { "code": null, "e": 8577, "s": 8561, "text": "\\cal 0123456789" }, { "code": null, "e": 8639, "s": 8577, "text": "\\cal abcdefghijklmnopqrstuvwxyz\n\nabcdefghijklmnopqrstuvwxyz\n\n" }, { "code": null, "e": 8671, "s": 8639, "text": "\\cal abcdefghijklmnopqrstuvwxyz" }, { "code": null, "e": 8728, "s": 8671, "text": "abcdefghijklmnopqrstuvwxyz\n\nabcdefghijklmnopqrstuvwxyz\n\n" }, { "code": null, "e": 8755, "s": 8728, "text": "abcdefghijklmnopqrstuvwxyz" }, { "code": null, "e": 8775, "s": 8755, "text": "{\\cal AB}AB\n\nABAB\n\n" }, { "code": null, "e": 8787, "s": 8775, "text": "{\\cal AB}AB" }, { "code": null, "e": 8810, "s": 8787, "text": "\\cal AB \\rm AB\n\nABAB\n\n" }, { "code": null, "e": 8825, "s": 8810, "text": "\\cal AB \\rm AB" }, { "code": null, "e": 8844, "s": 8825, "text": "\\cal{AB}CD\n\nABCD\n\n" }, { "code": null, "e": 8855, "s": 8844, "text": "\\cal{AB}CD" }, { "code": null, "e": 8887, "s": 8855, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8900, "s": 8887, "text": " Ashraf Said" }, { "code": null, "e": 8933, "s": 8900, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8946, "s": 8933, "text": " Ashraf Said" }, { "code": null, "e": 8978, "s": 8946, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 9014, "s": 8978, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 9049, "s": 9014, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9066, "s": 9049, "text": " Mohammad Nauman" }, { "code": null, "e": 9099, "s": 9066, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9113, "s": 9099, "text": " Daniel Stern" }, { "code": null, "e": 9145, "s": 9113, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 9160, "s": 9145, "text": " Nishant Kumar" }, { "code": null, "e": 9167, "s": 9160, "text": " Print" }, { "code": null, "e": 9178, "s": 9167, "text": " Add Notes" } ]
Minimum rotations to unlock a circular lock
28 Apr, 2021 You are given a lock which is made up of n-different circular rings and each ring has 0-9 digit printed serially on it. Initially all n-rings together show a n-digit integer but there is particular code only which can open the lock. You can rotate each ring any number of time in either direction. You have to find the minimum number of rotation done on rings of lock to open the lock. Examples: Input : Input = 2345, Unlock code = 5432 Output : Rotations required = 8 Explanation : 1st ring is rotated thrice as 2->3->4->5 2nd ring is rotated once as 3->4 3rd ring is rotated once as 4->3 4th ring is rotated thrice as 5->4->3->2 Input : Input = 1919, Unlock code = 0000 Output : Rotations required = 4 Explanation : 1st ring is rotated once as 1->0 2nd ring is rotated once as 9->0 3rd ring is rotated once as 1->0 4th ring is rotated once as 9->0 For a single ring we can rotate it in any of two direction forward or backward as: 0->1->2....->9->0 9->8->....0->9 But we are concerned with minimum number of rotation required so we should choose min (abs(a-b), 10-abs(a-b)) as a-b denotes the number of forward rotation and 10-abs(a-b) denotes the number of backward rotation for a ring to rotate from a to b. Further we have to find minimum number for each ring that is for each digit. So starting from right most digit we can easily the find minimum number of rotation required for each ring and end up at left most digit. C++ Java Python3 C# PHP Javascript // CPP program for min rotation to unlock#include <bits/stdc++.h>using namespace std; // function for min rotationint minRotation(int input, int unlock_code){ int rotation = 0; int input_digit, code_digit; // iterate till input and unlock code become 0 while (input || unlock_code) { // input and unlock last digit as reminder input_digit = input % 10; code_digit = unlock_code % 10; // find min rotation rotation += min(abs(input_digit - code_digit), 10 - abs(input_digit - code_digit)); // update code and input input /= 10; unlock_code /= 10; } return rotation;} // driver codeint main(){ int input = 28756; int unlock_code = 98234; cout << "Minimum Rotation = " << minRotation(input, unlock_code); return 0;} // Java program for min rotation to unlockclass GFG{ // function for min rotation static int minRotation(int input, int unlock_code) { int rotation = 0; int input_digit, code_digit; // iterate till input and unlock code become 0 while (input>0 || unlock_code>0) { // input and unlock last digit as reminder input_digit = input % 10; code_digit = unlock_code % 10; // find min rotation rotation += Math.min(Math.abs(input_digit - code_digit), 10 - Math.abs( input_digit - code_digit)); // update code and input input /= 10; unlock_code /= 10; } return rotation; } // driver code public static void main (String[] args) { int input = 28756; int unlock_code = 98234; System.out.println("Minimum Rotation = "+ minRotation(input, unlock_code)); }} /* This code is contributed by Mr. Somesh Awasthi */ # Python3 program for min rotation to unlock # function for min rotationdef minRotation(input, unlock_code): rotation = 0; # iterate till input and unlock # code become 0 while (input > 0 or unlock_code > 0): # input and unlock last digit # as reminder input_digit = input % 10; code_digit = unlock_code % 10; # find min rotation rotation += min(abs(input_digit - code_digit), 10 - abs(input_digit - code_digit)); # update code and input input = int(input / 10); unlock_code = int(unlock_code / 10); return rotation; # Driver Codeinput = 28756;unlock_code = 98234;print("Minimum Rotation =", minRotation(input, unlock_code)); # This code is contributed by mits // C# program for min rotation to unlockusing System; class GFG { // function for min rotation static int minRotation(int input, int unlock_code) { int rotation = 0; int input_digit, code_digit; // iterate till input and // unlock code become 0 while (input > 0 || unlock_code > 0) { // input and unlock last // digit as reminder input_digit = input % 10; code_digit = unlock_code % 10; // find min rotation rotation += Math.Min(Math.Abs(input_digit - code_digit), 10 - Math.Abs( input_digit - code_digit)); // update code and input input /= 10; unlock_code /= 10; } return rotation; } // Driver Code public static void Main () { int input = 28756; int unlock_code = 98234; Console.Write("Minimum Rotation = "+ minRotation(input, unlock_code)); }} // This code is contributed by Nitin Mittal <?php// PHP program for min// rotation to unlock // function for min rotationfunction minRotation($input, $unlock_code){ $rotation = 0; $input_digit; $code_digit; // iterate till input and // unlock code become 0 while ($input || $unlock_code) { // input and unlock last // digit as reminder $input_digit = $input % 10; $code_digit = $unlock_code % 10; // find min rotation $rotation += min(abs($input_digit - $code_digit), 10 - abs($input_digit - $code_digit)); // update code and input $input /= 10; $unlock_code /= 10; } return $rotation;} // Driver Code $input = 28756; $unlock_code = 98234; echo "Minimum Rotation = " , minRotation($input, $unlock_code); // This code is contributed by vt_m.?> <script>// JavaScript program for min rotation to unlock // function for min rotation function minRotation(input, unlock_code) { let rotation = 0; let input_digit, code_digit; // iterate till input and unlock code become 0 while (input>0 || unlock_code>0) { // input and unlock last digit as reminder input_digit = input % 10; code_digit = unlock_code % 10; // find min rotation rotation += Math.min(Math.abs(input_digit - code_digit), 10 - Math.abs( input_digit - code_digit)); // update code and input input = Math.floor(input / 10); unlock_code = Math.floor(unlock_code / 10); } return rotation; } // Driver Code let input = 28756; let unlock_code = 98234; document.write("Minimum Rotation = "+ minRotation(input, unlock_code)); </script> Output: Minimum Rotation = 12 This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m Mithun Kumar susmitakundugoaldanga Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Apr, 2021" }, { "code": null, "e": 439, "s": 52, "text": "You are given a lock which is made up of n-different circular rings and each ring has 0-9 digit printed serially on it. Initially all n-rings together show a n-digit integer but there is particular code only which can open the lock. You can rotate each ring any number of time in either direction. You have to find the minimum number of rotation done on rings of lock to open the lock. " }, { "code": null, "e": 451, "s": 439, "text": "Examples: " }, { "code": null, "e": 992, "s": 451, "text": "Input : Input = 2345, Unlock code = 5432 \nOutput : Rotations required = 8\nExplanation : 1st ring is rotated thrice as 2->3->4->5\n 2nd ring is rotated once as 3->4\n 3rd ring is rotated once as 4->3\n 4th ring is rotated thrice as 5->4->3->2\n\nInput : Input = 1919, Unlock code = 0000 \nOutput : Rotations required = 4\nExplanation : 1st ring is rotated once as 1->0\n 2nd ring is rotated once as 9->0\n 3rd ring is rotated once as 1->0\n 4th ring is rotated once as 9->0" }, { "code": null, "e": 1079, "s": 994, "text": "For a single ring we can rotate it in any of two direction forward or backward as: " }, { "code": null, "e": 1097, "s": 1079, "text": "0->1->2....->9->0" }, { "code": null, "e": 1112, "s": 1097, "text": "9->8->....0->9" }, { "code": null, "e": 1575, "s": 1112, "text": "But we are concerned with minimum number of rotation required so we should choose min (abs(a-b), 10-abs(a-b)) as a-b denotes the number of forward rotation and 10-abs(a-b) denotes the number of backward rotation for a ring to rotate from a to b. Further we have to find minimum number for each ring that is for each digit. So starting from right most digit we can easily the find minimum number of rotation required for each ring and end up at left most digit. " }, { "code": null, "e": 1579, "s": 1575, "text": "C++" }, { "code": null, "e": 1584, "s": 1579, "text": "Java" }, { "code": null, "e": 1592, "s": 1584, "text": "Python3" }, { "code": null, "e": 1595, "s": 1592, "text": "C#" }, { "code": null, "e": 1599, "s": 1595, "text": "PHP" }, { "code": null, "e": 1610, "s": 1599, "text": "Javascript" }, { "code": "// CPP program for min rotation to unlock#include <bits/stdc++.h>using namespace std; // function for min rotationint minRotation(int input, int unlock_code){ int rotation = 0; int input_digit, code_digit; // iterate till input and unlock code become 0 while (input || unlock_code) { // input and unlock last digit as reminder input_digit = input % 10; code_digit = unlock_code % 10; // find min rotation rotation += min(abs(input_digit - code_digit), 10 - abs(input_digit - code_digit)); // update code and input input /= 10; unlock_code /= 10; } return rotation;} // driver codeint main(){ int input = 28756; int unlock_code = 98234; cout << \"Minimum Rotation = \" << minRotation(input, unlock_code); return 0;}", "e": 2441, "s": 1610, "text": null }, { "code": "// Java program for min rotation to unlockclass GFG{ // function for min rotation static int minRotation(int input, int unlock_code) { int rotation = 0; int input_digit, code_digit; // iterate till input and unlock code become 0 while (input>0 || unlock_code>0) { // input and unlock last digit as reminder input_digit = input % 10; code_digit = unlock_code % 10; // find min rotation rotation += Math.min(Math.abs(input_digit - code_digit), 10 - Math.abs( input_digit - code_digit)); // update code and input input /= 10; unlock_code /= 10; } return rotation; } // driver code public static void main (String[] args) { int input = 28756; int unlock_code = 98234; System.out.println(\"Minimum Rotation = \"+ minRotation(input, unlock_code)); }} /* This code is contributed by Mr. Somesh Awasthi */", "e": 3468, "s": 2441, "text": null }, { "code": "# Python3 program for min rotation to unlock # function for min rotationdef minRotation(input, unlock_code): rotation = 0; # iterate till input and unlock # code become 0 while (input > 0 or unlock_code > 0): # input and unlock last digit # as reminder input_digit = input % 10; code_digit = unlock_code % 10; # find min rotation rotation += min(abs(input_digit - code_digit), 10 - abs(input_digit - code_digit)); # update code and input input = int(input / 10); unlock_code = int(unlock_code / 10); return rotation; # Driver Codeinput = 28756;unlock_code = 98234;print(\"Minimum Rotation =\", minRotation(input, unlock_code)); # This code is contributed by mits", "e": 4242, "s": 3468, "text": null }, { "code": "// C# program for min rotation to unlockusing System; class GFG { // function for min rotation static int minRotation(int input, int unlock_code) { int rotation = 0; int input_digit, code_digit; // iterate till input and // unlock code become 0 while (input > 0 || unlock_code > 0) { // input and unlock last // digit as reminder input_digit = input % 10; code_digit = unlock_code % 10; // find min rotation rotation += Math.Min(Math.Abs(input_digit - code_digit), 10 - Math.Abs( input_digit - code_digit)); // update code and input input /= 10; unlock_code /= 10; } return rotation; } // Driver Code public static void Main () { int input = 28756; int unlock_code = 98234; Console.Write(\"Minimum Rotation = \"+ minRotation(input, unlock_code)); }} // This code is contributed by Nitin Mittal", "e": 5351, "s": 4242, "text": null }, { "code": "<?php// PHP program for min// rotation to unlock // function for min rotationfunction minRotation($input, $unlock_code){ $rotation = 0; $input_digit; $code_digit; // iterate till input and // unlock code become 0 while ($input || $unlock_code) { // input and unlock last // digit as reminder $input_digit = $input % 10; $code_digit = $unlock_code % 10; // find min rotation $rotation += min(abs($input_digit - $code_digit), 10 - abs($input_digit - $code_digit)); // update code and input $input /= 10; $unlock_code /= 10; } return $rotation;} // Driver Code $input = 28756; $unlock_code = 98234; echo \"Minimum Rotation = \" , minRotation($input, $unlock_code); // This code is contributed by vt_m.?>", "e": 6207, "s": 5351, "text": null }, { "code": "<script>// JavaScript program for min rotation to unlock // function for min rotation function minRotation(input, unlock_code) { let rotation = 0; let input_digit, code_digit; // iterate till input and unlock code become 0 while (input>0 || unlock_code>0) { // input and unlock last digit as reminder input_digit = input % 10; code_digit = unlock_code % 10; // find min rotation rotation += Math.min(Math.abs(input_digit - code_digit), 10 - Math.abs( input_digit - code_digit)); // update code and input input = Math.floor(input / 10); unlock_code = Math.floor(unlock_code / 10); } return rotation; } // Driver Code let input = 28756; let unlock_code = 98234; document.write(\"Minimum Rotation = \"+ minRotation(input, unlock_code)); </script>", "e": 7205, "s": 6207, "text": null }, { "code": null, "e": 7215, "s": 7205, "text": "Output: " }, { "code": null, "e": 7237, "s": 7215, "text": "Minimum Rotation = 12" }, { "code": null, "e": 7673, "s": 7237, "text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7686, "s": 7673, "text": "nitin mittal" }, { "code": null, "e": 7691, "s": 7686, "text": "vt_m" }, { "code": null, "e": 7704, "s": 7691, "text": "Mithun Kumar" }, { "code": null, "e": 7726, "s": 7704, "text": "susmitakundugoaldanga" }, { "code": null, "e": 7733, "s": 7726, "text": "Greedy" }, { "code": null, "e": 7746, "s": 7733, "text": "Mathematical" }, { "code": null, "e": 7753, "s": 7746, "text": "Greedy" }, { "code": null, "e": 7766, "s": 7753, "text": "Mathematical" } ]
XOR of all subarray XORs | Set 1
08 Jul, 2022 Given an array of integers, we need to get the total XOR of all subarray XORs where subarray XOR can be obtained by XORing all elements of it. Examples : Input : arr[] = [3, 5, 2, 4, 6] Output : 7 Total XOR of all subarray XORs is, (3) ^ (5) ^ (2) ^ (4) ^ (6) (3^5) ^ (5^2) ^ (2^4) ^ (4^6) (3^5^2) ^ (5^2^4) ^ (2^4^6) (3^5^2^4) ^ (5^2^4^6) ^ (3^5^2^4^6) = 7 Input : arr[] = {1, 2, 3} Output : 2 Input : arr[] = {1, 2, 3, 4} Output : 0 A simple solution is to generate all subarrays and compute XOR of all of them. Below is the implementation of the above idea : Implementation: C++ Java Python 3 C# PHP Javascript // C++ program to get total xor of all subarray xors#include <bits/stdc++.h>using namespace std; // Returns XOR of all subarray xorsint getTotalXorOfSubarrayXors(int arr[], int N){ // initialize result by 0 as (a xor 0 = a) int res = 0; // select the starting element for (int i=0; i<N; i++) // select the eNding element for (int j=i; j<N; j++) // Do XOR of elements in current subarray for (int k=i; k<=j; k++) res = res ^ arr[k]; return res;} // Driver code to test above methodsint main(){ int arr[] = {3, 5, 2, 4, 6}; int N = sizeof(arr) / sizeof(arr[0]); cout << getTotalXorOfSubarrayXors(arr, N); return 0;} // java program to get total XOR// of all subarray xorspublic class GFG { // Returns XOR of all subarray xors static int getTotalXorOfSubarrayXors( int arr[], int N) { // initialize result by // 0 as (a xor 0 = a) int res = 0; // select the starting element for (int i = 0; i < N; i++) // select the eNding element for (int j = i; j < N; j++) // Do XOR of elements // in current subarray for (int k = i; k <= j; k++) res = res ^ arr[k]; return res; } // Driver code public static void main(String args[]) { int arr[] = {3, 5, 2, 4, 6}; int N = arr.length; System.out.println( getTotalXorOfSubarrayXors(arr, N)); }} // This code is contributed by Sam007. # python program to get total xor# of all subarray xors # Returns XOR of all subarray xorsdef getTotalXorOfSubarrayXors(arr, N): # initialize result by 0 as # (a xor 0 = a) res = 0 # select the starting element for i in range(0, N): # select the eNding element for j in range(i, N): # Do XOR of elements in # current subarray for k in range(i, j + 1): res = res ^ arr[k] return res # Driver code to test above methodsarr = [3, 5, 2, 4, 6]N = len(arr) print(getTotalXorOfSubarrayXors(arr, N)) # This code is contributed by Sam007. // C# program to get total XOR// of all subarray xorsusing System; class GFG { // Returns XOR of all subarray xorsstatic int getTotalXorOfSubarrayXors(int []arr, int N){ // initialize result by// 0 as (a xor 0 = a)int res = 0; // select the starting elementfor (int i = 0; i < N; i++) // select the eNding element for (int j = i; j < N; j++) // Do XOR of elements // in current subarray for (int k = i; k <= j; k++) res = res ^ arr[k]; return res;} // Driver Codestatic void Main(){ int []arr = {3, 5, 2, 4, 6}; int N = arr.Length; Console.Write(getTotalXorOfSubarrayXors(arr, N));}} // This code is contributed by Sam007 <?php// PHP program to get total// xor of all subarray xors // Returns XOR of all subarray xorsfunction getTotalXorOfSubarrayXors($arr, $N){ // initialize result by // 0 as (a xor 0 = a) $res = 0; // select the starting element for($i = 0; $i < $N; $i++) // select the eNding element for($j = $i; $j < $N; $j++) // Do XOR of elements in // current subarray for($k = $i; $k <= $j; $k++) $res = $res ^ $arr[$k]; return $res;} // Driver code $arr = array(3, 5, 2, 4, 6); $N = sizeof($arr); echo getTotalXorOfSubarrayXors($arr, $N); // This code is contributed by nitin mittal.?> <script> // JavaScript program for the above approach // Returns XOR of all subarray xors function getTotalXorOfSubarrayXors( arr, N) { // initialize result by // 0 as (a xor 0 = a) let res = 0; // select the starting element for (let i = 0; i < N; i++) // select the eNding element for (let j = i; j < N; j++) // Do XOR of elements // in current subarray for (let k = i; k <= j; k++) res = res ^ arr[k]; return res; } // Driver Code // Both a[] and b[] must be of same size. let arr = [3, 5, 2, 4, 6]; let N = arr.length; document.write(getTotalXorOfSubarrayXors(arr, N)); // This code is contributed by code_hunt.</script> 7 Time Complexity: O(N3) An efficient solution is based on the idea to enumerate all subarrays, we can count the frequency of each element that occurred totally in all subarrays, if the frequency of an element is odd then it will be included in the final result otherwise not. As in above example, 3 occurred 5 times, 5 occurred 8 times, 2 occurred 9 times, 4 occurred 8 times, 6 occurred 5 times So our final result will be xor of all elements which occurred odd number of times i.e. 3^2^6 = 7 From above occurrence pattern we can observe that number at i-th index will have (i + 1) * (N - i) frequency. So we can iterate over all elements once and calculate their frequencies and if it is odd then we can include that in our final result by XORing it with the result. Total time complexity of the solution will be O(N) Implementation: C++ Java Python 3 C# PHP Javascript // C++ program to get total// xor of all subarray xors#include <bits/stdc++.h>using namespace std; // Returns XOR of all subarray xorsint getTotalXorOfSubarrayXors(int arr[], int N){ // initialize result by 0 // as (a XOR 0 = a) int res = 0; // loop over all elements once for (int i = 0; i < N; i++) { // get the frequency of // current element int freq = (i + 1) * (N - i); // Uncomment below line to print // the frequency of arr[i] // cout << arr[i] << " " << freq << endl; // if frequency is odd, then // include it in the result if (freq % 2 == 1) res = res ^ arr[i]; } // return the result return res;} // Driver Codeint main(){ int arr[] = {3, 5, 2, 4, 6}; int N = sizeof(arr) / sizeof(arr[0]); cout << getTotalXorOfSubarrayXors(arr, N); return 0;} // java program to get total xor// of all subarray xorsimport java.io.*; public class GFG { // Returns XOR of all subarray // xors static int getTotalXorOfSubarrayXors( int arr[], int N) { // initialize result by 0 // as (a XOR 0 = a) int res = 0; // loop over all elements once for (int i = 0; i < N; i++) { // get the frequency of // current element int freq = (i + 1) * (N - i); // Uncomment below line to print // the frequency of arr[i] // if frequency is odd, then // include it in the result if (freq % 2 == 1) res = res ^ arr[i]; } // return the result return res; } public static void main(String[] args) { int arr[] = {3, 5, 2, 4, 6}; int N = arr.length; System.out.println( getTotalXorOfSubarrayXors(arr, N)); }} // This code is contributed by Sam007. # Python3 program to get total# xor of all subarray xors # Returns XOR of all# subarray xorsdef getTotalXorOfSubarrayXors(arr, N): # initialize result by 0 # as (a XOR 0 = a) res = 0 # loop over all elements once for i in range(0, N): # get the frequency of # current element freq = (i + 1) * (N - i) # Uncomment below line to print # the frequency of arr[i] # if frequency is odd, then # include it in the result if (freq % 2 == 1): res = res ^ arr[i] # return the result return res # Driver Codearr = [3, 5, 2, 4, 6]N = len(arr)print(getTotalXorOfSubarrayXors(arr, N)) # This code is contributed# by Smitha // C# program to get total xor// of all subarray xorsusing System; class GFG{// Returns XOR of all subarray xorsstatic int getTotalXorOfSubarrayXors(int []arr, int N){ // initialize result by 0 // as (a XOR 0 = a) int res = 0; // loop over all elements once for (int i = 0; i < N; i++) { // get the frequency of // current element int freq = (i + 1) * (N - i); // Uncomment below line to print // the frequency of arr[i] // if frequency is odd, then // include it in the result if (freq % 2 == 1) res = res ^ arr[i]; } // return the result return res;} // Driver Code public static void Main() { int []arr = {3, 5, 2, 4, 6}; int N = arr.Length; Console.Write(getTotalXorOfSubarrayXors(arr, N)); }} // This code is contributed by Sam007 <?php// PHP program to get total// xor of all subarray xors // Returns XOR of all subarray xorsfunction getTotalXorOfSubarrayXors($arr, $N){ // initialize result by 0 // as (a XOR 0 = a) $res = 0; // loop over all elements once for ($i = 0; $i < $N; $i++) { // get the frequency of // current element $freq = ($i + 1) * ($N - $i); // if frequency is odd, then // include it in the result if ($freq % 2 == 1) $res = $res ^ $arr[$i]; } // return the result return $res;} // Driver Code $arr = array(3, 5, 2, 4, 6); $N = count($arr); echo getTotalXorOfSubarrayXors($arr, $N); // This code is contributed by anuj_67.?> <script> // Javascript program to get total// xor of all subarray xors // Returns XOR of all subarray xorsfunction getTotalXorOfSubarrayXors(arr, N){ // initialize result by 0 // as (a XOR 0 = a) let res = 0; // loop over all elements once for (let i = 0; i < N; i++) { // get the frequency of // current element let freq = (i + 1) * (N - i); // Uncomment below line to print // the frequency of arr[i] // cout << arr[i] << " " << freq << endl; // if frequency is odd, then // include it in the result if (freq % 2 == 1) res = res ^ arr[i]; } // return the result return res;} // Driver Code let arr = [3, 5, 2, 4, 6]; let N = arr.length; document.write(getTotalXorOfSubarrayXors(arr, N)); </script> 7 Time Complexity : O(N) This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Sam007 vt_m nitin mittal Smitha Dinesh Semwal nidhi_biet code_hunt rishavmahato348 hardikkoriintern Amazon Bitwise-XOR subarray Arrays Mathematical Amazon Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 197, "s": 54, "text": "Given an array of integers, we need to get the total XOR of all subarray XORs where subarray XOR can be obtained by XORing all elements of it." }, { "code": null, "e": 209, "s": 197, "text": "Examples : " }, { "code": null, "e": 497, "s": 209, "text": "Input : arr[] = [3, 5, 2, 4, 6]\nOutput : 7\nTotal XOR of all subarray XORs is,\n(3) ^ (5) ^ (2) ^ (4) ^ (6)\n(3^5) ^ (5^2) ^ (2^4) ^ (4^6)\n(3^5^2) ^ (5^2^4) ^ (2^4^6)\n(3^5^2^4) ^ (5^2^4^6) ^\n(3^5^2^4^6) = 7 \n\nInput : arr[] = {1, 2, 3}\nOutput : 2\n\nInput : arr[] = {1, 2, 3, 4}\nOutput : 0" }, { "code": null, "e": 625, "s": 497, "text": "A simple solution is to generate all subarrays and compute XOR of all of them. Below is the implementation of the above idea : " }, { "code": null, "e": 641, "s": 625, "text": "Implementation:" }, { "code": null, "e": 645, "s": 641, "text": "C++" }, { "code": null, "e": 650, "s": 645, "text": "Java" }, { "code": null, "e": 659, "s": 650, "text": "Python 3" }, { "code": null, "e": 662, "s": 659, "text": "C#" }, { "code": null, "e": 666, "s": 662, "text": "PHP" }, { "code": null, "e": 677, "s": 666, "text": "Javascript" }, { "code": "// C++ program to get total xor of all subarray xors#include <bits/stdc++.h>using namespace std; // Returns XOR of all subarray xorsint getTotalXorOfSubarrayXors(int arr[], int N){ // initialize result by 0 as (a xor 0 = a) int res = 0; // select the starting element for (int i=0; i<N; i++) // select the eNding element for (int j=i; j<N; j++) // Do XOR of elements in current subarray for (int k=i; k<=j; k++) res = res ^ arr[k]; return res;} // Driver code to test above methodsint main(){ int arr[] = {3, 5, 2, 4, 6}; int N = sizeof(arr) / sizeof(arr[0]); cout << getTotalXorOfSubarrayXors(arr, N); return 0;}", "e": 1375, "s": 677, "text": null }, { "code": "// java program to get total XOR// of all subarray xorspublic class GFG { // Returns XOR of all subarray xors static int getTotalXorOfSubarrayXors( int arr[], int N) { // initialize result by // 0 as (a xor 0 = a) int res = 0; // select the starting element for (int i = 0; i < N; i++) // select the eNding element for (int j = i; j < N; j++) // Do XOR of elements // in current subarray for (int k = i; k <= j; k++) res = res ^ arr[k]; return res; } // Driver code public static void main(String args[]) { int arr[] = {3, 5, 2, 4, 6}; int N = arr.length; System.out.println( getTotalXorOfSubarrayXors(arr, N)); }} // This code is contributed by Sam007.", "e": 2286, "s": 1375, "text": null }, { "code": "# python program to get total xor# of all subarray xors # Returns XOR of all subarray xorsdef getTotalXorOfSubarrayXors(arr, N): # initialize result by 0 as # (a xor 0 = a) res = 0 # select the starting element for i in range(0, N): # select the eNding element for j in range(i, N): # Do XOR of elements in # current subarray for k in range(i, j + 1): res = res ^ arr[k] return res # Driver code to test above methodsarr = [3, 5, 2, 4, 6]N = len(arr) print(getTotalXorOfSubarrayXors(arr, N)) # This code is contributed by Sam007.", "e": 2937, "s": 2286, "text": null }, { "code": "// C# program to get total XOR// of all subarray xorsusing System; class GFG { // Returns XOR of all subarray xorsstatic int getTotalXorOfSubarrayXors(int []arr, int N){ // initialize result by// 0 as (a xor 0 = a)int res = 0; // select the starting elementfor (int i = 0; i < N; i++) // select the eNding element for (int j = i; j < N; j++) // Do XOR of elements // in current subarray for (int k = i; k <= j; k++) res = res ^ arr[k]; return res;} // Driver Codestatic void Main(){ int []arr = {3, 5, 2, 4, 6}; int N = arr.Length; Console.Write(getTotalXorOfSubarrayXors(arr, N));}} // This code is contributed by Sam007", "e": 3648, "s": 2937, "text": null }, { "code": "<?php// PHP program to get total// xor of all subarray xors // Returns XOR of all subarray xorsfunction getTotalXorOfSubarrayXors($arr, $N){ // initialize result by // 0 as (a xor 0 = a) $res = 0; // select the starting element for($i = 0; $i < $N; $i++) // select the eNding element for($j = $i; $j < $N; $j++) // Do XOR of elements in // current subarray for($k = $i; $k <= $j; $k++) $res = $res ^ $arr[$k]; return $res;} // Driver code $arr = array(3, 5, 2, 4, 6); $N = sizeof($arr); echo getTotalXorOfSubarrayXors($arr, $N); // This code is contributed by nitin mittal.?>", "e": 4326, "s": 3648, "text": null }, { "code": "<script> // JavaScript program for the above approach // Returns XOR of all subarray xors function getTotalXorOfSubarrayXors( arr, N) { // initialize result by // 0 as (a xor 0 = a) let res = 0; // select the starting element for (let i = 0; i < N; i++) // select the eNding element for (let j = i; j < N; j++) // Do XOR of elements // in current subarray for (let k = i; k <= j; k++) res = res ^ arr[k]; return res; } // Driver Code // Both a[] and b[] must be of same size. let arr = [3, 5, 2, 4, 6]; let N = arr.length; document.write(getTotalXorOfSubarrayXors(arr, N)); // This code is contributed by code_hunt.</script>", "e": 5168, "s": 4326, "text": null }, { "code": null, "e": 5170, "s": 5168, "text": "7" }, { "code": null, "e": 5193, "s": 5170, "text": "Time Complexity: O(N3)" }, { "code": null, "e": 5446, "s": 5193, "text": "An efficient solution is based on the idea to enumerate all subarrays, we can count the frequency of each element that occurred totally in all subarrays, if the frequency of an element is odd then it will be included in the final result otherwise not. " }, { "code": null, "e": 5778, "s": 5446, "text": "As in above example, \n3 occurred 5 times,\n5 occurred 8 times,\n2 occurred 9 times,\n4 occurred 8 times,\n6 occurred 5 times\nSo our final result will be xor of all elements which occurred odd number of times\ni.e. 3^2^6 = 7\n\nFrom above occurrence pattern we can observe that number at i-th index will have \n(i + 1) * (N - i) frequency. " }, { "code": null, "e": 5995, "s": 5778, "text": "So we can iterate over all elements once and calculate their frequencies and if it is odd then we can include that in our final result by XORing it with the result. Total time complexity of the solution will be O(N) " }, { "code": null, "e": 6011, "s": 5995, "text": "Implementation:" }, { "code": null, "e": 6015, "s": 6011, "text": "C++" }, { "code": null, "e": 6020, "s": 6015, "text": "Java" }, { "code": null, "e": 6029, "s": 6020, "text": "Python 3" }, { "code": null, "e": 6032, "s": 6029, "text": "C#" }, { "code": null, "e": 6036, "s": 6032, "text": "PHP" }, { "code": null, "e": 6047, "s": 6036, "text": "Javascript" }, { "code": "// C++ program to get total// xor of all subarray xors#include <bits/stdc++.h>using namespace std; // Returns XOR of all subarray xorsint getTotalXorOfSubarrayXors(int arr[], int N){ // initialize result by 0 // as (a XOR 0 = a) int res = 0; // loop over all elements once for (int i = 0; i < N; i++) { // get the frequency of // current element int freq = (i + 1) * (N - i); // Uncomment below line to print // the frequency of arr[i] // cout << arr[i] << \" \" << freq << endl; // if frequency is odd, then // include it in the result if (freq % 2 == 1) res = res ^ arr[i]; } // return the result return res;} // Driver Codeint main(){ int arr[] = {3, 5, 2, 4, 6}; int N = sizeof(arr) / sizeof(arr[0]); cout << getTotalXorOfSubarrayXors(arr, N); return 0;}", "e": 6951, "s": 6047, "text": null }, { "code": "// java program to get total xor// of all subarray xorsimport java.io.*; public class GFG { // Returns XOR of all subarray // xors static int getTotalXorOfSubarrayXors( int arr[], int N) { // initialize result by 0 // as (a XOR 0 = a) int res = 0; // loop over all elements once for (int i = 0; i < N; i++) { // get the frequency of // current element int freq = (i + 1) * (N - i); // Uncomment below line to print // the frequency of arr[i] // if frequency is odd, then // include it in the result if (freq % 2 == 1) res = res ^ arr[i]; } // return the result return res; } public static void main(String[] args) { int arr[] = {3, 5, 2, 4, 6}; int N = arr.length; System.out.println( getTotalXorOfSubarrayXors(arr, N)); }} // This code is contributed by Sam007.", "e": 8009, "s": 6951, "text": null }, { "code": "# Python3 program to get total# xor of all subarray xors # Returns XOR of all# subarray xorsdef getTotalXorOfSubarrayXors(arr, N): # initialize result by 0 # as (a XOR 0 = a) res = 0 # loop over all elements once for i in range(0, N): # get the frequency of # current element freq = (i + 1) * (N - i) # Uncomment below line to print # the frequency of arr[i] # if frequency is odd, then # include it in the result if (freq % 2 == 1): res = res ^ arr[i] # return the result return res # Driver Codearr = [3, 5, 2, 4, 6]N = len(arr)print(getTotalXorOfSubarrayXors(arr, N)) # This code is contributed# by Smitha", "e": 8724, "s": 8009, "text": null }, { "code": "// C# program to get total xor// of all subarray xorsusing System; class GFG{// Returns XOR of all subarray xorsstatic int getTotalXorOfSubarrayXors(int []arr, int N){ // initialize result by 0 // as (a XOR 0 = a) int res = 0; // loop over all elements once for (int i = 0; i < N; i++) { // get the frequency of // current element int freq = (i + 1) * (N - i); // Uncomment below line to print // the frequency of arr[i] // if frequency is odd, then // include it in the result if (freq % 2 == 1) res = res ^ arr[i]; } // return the result return res;} // Driver Code public static void Main() { int []arr = {3, 5, 2, 4, 6}; int N = arr.Length; Console.Write(getTotalXorOfSubarrayXors(arr, N)); }} // This code is contributed by Sam007", "e": 9634, "s": 8724, "text": null }, { "code": "<?php// PHP program to get total// xor of all subarray xors // Returns XOR of all subarray xorsfunction getTotalXorOfSubarrayXors($arr, $N){ // initialize result by 0 // as (a XOR 0 = a) $res = 0; // loop over all elements once for ($i = 0; $i < $N; $i++) { // get the frequency of // current element $freq = ($i + 1) * ($N - $i); // if frequency is odd, then // include it in the result if ($freq % 2 == 1) $res = $res ^ $arr[$i]; } // return the result return $res;} // Driver Code $arr = array(3, 5, 2, 4, 6); $N = count($arr); echo getTotalXorOfSubarrayXors($arr, $N); // This code is contributed by anuj_67.?>", "e": 10394, "s": 9634, "text": null }, { "code": "<script> // Javascript program to get total// xor of all subarray xors // Returns XOR of all subarray xorsfunction getTotalXorOfSubarrayXors(arr, N){ // initialize result by 0 // as (a XOR 0 = a) let res = 0; // loop over all elements once for (let i = 0; i < N; i++) { // get the frequency of // current element let freq = (i + 1) * (N - i); // Uncomment below line to print // the frequency of arr[i] // cout << arr[i] << \" \" << freq << endl; // if frequency is odd, then // include it in the result if (freq % 2 == 1) res = res ^ arr[i]; } // return the result return res;} // Driver Code let arr = [3, 5, 2, 4, 6]; let N = arr.length; document.write(getTotalXorOfSubarrayXors(arr, N)); </script>", "e": 11209, "s": 10394, "text": null }, { "code": null, "e": 11211, "s": 11209, "text": "7" }, { "code": null, "e": 11234, "s": 11211, "text": "Time Complexity : O(N)" }, { "code": null, "e": 11534, "s": 11234, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 11541, "s": 11534, "text": "Sam007" }, { "code": null, "e": 11546, "s": 11541, "text": "vt_m" }, { "code": null, "e": 11559, "s": 11546, "text": "nitin mittal" }, { "code": null, "e": 11580, "s": 11559, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 11591, "s": 11580, "text": "nidhi_biet" }, { "code": null, "e": 11601, "s": 11591, "text": "code_hunt" }, { "code": null, "e": 11617, "s": 11601, "text": "rishavmahato348" }, { "code": null, "e": 11634, "s": 11617, "text": "hardikkoriintern" }, { "code": null, "e": 11641, "s": 11634, "text": "Amazon" }, { "code": null, "e": 11653, "s": 11641, "text": "Bitwise-XOR" }, { "code": null, "e": 11662, "s": 11653, "text": "subarray" }, { "code": null, "e": 11669, "s": 11662, "text": "Arrays" }, { "code": null, "e": 11682, "s": 11669, "text": "Mathematical" }, { "code": null, "e": 11689, "s": 11682, "text": "Amazon" }, { "code": null, "e": 11696, "s": 11689, "text": "Arrays" }, { "code": null, "e": 11709, "s": 11696, "text": "Mathematical" } ]
Creating an Alpine Docker Container
31 Oct, 2020 Alpine is a Linux Distribution. Docker provides you with the low sized (only 5 MB) Alpine Linux Image. The Alpine Linux Docker Image has advantages over the Ubuntu Image because of its relatively lower size and it provides almost all the functionalities that an Ubuntu Image can. In this article, we will see how to build an Alpine Linux Image. We will try to install MySQL client, Python 3, and Firefox inside the Alpine Linux Docker Container as well. To create the Alpine Docker Container follow the below steps: To run the Alpine Image Docker Container, you can use the Docker run command. sudo docker run -it alpine:3 Running the Alpine Container Once the Image is loaded, it opens up the shell for you automatically. To install python 3 inside the Alpine Container, you can use the apk add command inside the shell. apk add python3 Installing Python 3 You can install the My-SQL client using the following command. apk add mysql-client My-SQL Client To install Firefox inside the Container, you can use the following command. apk add firefox Installing Firefox Step 5: Commit the changes in the Image You need the Container Id to commit the changes in the Image. To find the Container ID, use this command. sudo docker ps -a Copy the Container ID and paste it in this command. sudo docker commit eacdf78d1bde my-alpine “my-alpine” is the new image name. You can verify by listing the images. sudo docker images Docker commit Docker Container linux Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2020" }, { "code": null, "e": 482, "s": 28, "text": "Alpine is a Linux Distribution. Docker provides you with the low sized (only 5 MB) Alpine Linux Image. The Alpine Linux Docker Image has advantages over the Ubuntu Image because of its relatively lower size and it provides almost all the functionalities that an Ubuntu Image can. In this article, we will see how to build an Alpine Linux Image. We will try to install MySQL client, Python 3, and Firefox inside the Alpine Linux Docker Container as well." }, { "code": null, "e": 544, "s": 482, "text": "To create the Alpine Docker Container follow the below steps:" }, { "code": null, "e": 622, "s": 544, "text": "To run the Alpine Image Docker Container, you can use the Docker run command." }, { "code": null, "e": 653, "s": 622, "text": "sudo docker run -it alpine:3\n\n" }, { "code": null, "e": 682, "s": 653, "text": "Running the Alpine Container" }, { "code": null, "e": 753, "s": 682, "text": "Once the Image is loaded, it opens up the shell for you automatically." }, { "code": null, "e": 852, "s": 753, "text": "To install python 3 inside the Alpine Container, you can use the apk add command inside the shell." }, { "code": null, "e": 871, "s": 852, "text": "apk add python3 \n\n" }, { "code": null, "e": 891, "s": 871, "text": "Installing Python 3" }, { "code": null, "e": 954, "s": 891, "text": "You can install the My-SQL client using the following command." }, { "code": null, "e": 977, "s": 954, "text": "apk add mysql-client\n\n" }, { "code": null, "e": 991, "s": 977, "text": "My-SQL Client" }, { "code": null, "e": 1067, "s": 991, "text": "To install Firefox inside the Container, you can use the following command." }, { "code": null, "e": 1085, "s": 1067, "text": "apk add firefox\n\n" }, { "code": null, "e": 1104, "s": 1085, "text": "Installing Firefox" }, { "code": null, "e": 1144, "s": 1104, "text": "Step 5: Commit the changes in the Image" }, { "code": null, "e": 1206, "s": 1144, "text": "You need the Container Id to commit the changes in the Image." }, { "code": null, "e": 1250, "s": 1206, "text": "To find the Container ID, use this command." }, { "code": null, "e": 1270, "s": 1250, "text": "sudo docker ps -a\n\n" }, { "code": null, "e": 1322, "s": 1270, "text": "Copy the Container ID and paste it in this command." }, { "code": null, "e": 1366, "s": 1322, "text": "sudo docker commit eacdf78d1bde my-alpine\n\n" }, { "code": null, "e": 1401, "s": 1366, "text": "“my-alpine” is the new image name." }, { "code": null, "e": 1439, "s": 1401, "text": "You can verify by listing the images." }, { "code": null, "e": 1461, "s": 1439, "text": "sudo docker images \n\n" }, { "code": null, "e": 1475, "s": 1461, "text": "Docker commit" }, { "code": null, "e": 1492, "s": 1475, "text": "Docker Container" }, { "code": null, "e": 1498, "s": 1492, "text": "linux" }, { "code": null, "e": 1524, "s": 1498, "text": "Advanced Computer Subject" } ]
JavaScript unescape() Function
22 Nov, 2021 Prerequisite: JavaScript escape() Function Below is the example of the unescape() function. Example:<script> // Special character encoded with // escape function document.write(unescape("Geeks%20for%20Geeks%21%21%21")); document.write("<br>"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(unescape("To%20contribute%20articles%20contact"+ "%20us%[email protected]"));</script> <script> // Special character encoded with // escape function document.write(unescape("Geeks%20for%20Geeks%21%21%21")); document.write("<br>"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(unescape("To%20contribute%20articles%20contact"+ "%20us%[email protected]"));</script> Output:Geeks for Geeks!!! To contribute articles contact us at [email protected] Geeks for Geeks!!! To contribute articles contact us at [email protected] The unescape() function in JavaScript takes a string as a parameter and uses to decode that string encoded by the escape() function. The hexadecimal sequence in the string is replaced by the characters they represent when decoded via unescape(). Syntax: unescape(string) Parameters: This function accepts a single parameter as mentioned above and described below: string: This parameters holds the string that will be decoded.Return value: This function returns a decoded string.Note: This function only decodes the special characters, this function is depricated.Exceptions: @ – + . / * _More example codes for the above function are as follows:Program 1:<script> // Special character encoded with // escape function var str = escape("Geeks for Geeks!!!"); document.write("Encoded : " + str); // New Line document.write("<br>"); // unescape() function document.write("Decoded : " + unescape(str)) // New Line document.write("<br><br>"); // The exception // @ and . not encoded. str = escape("To contribute articles contact us" + "at [email protected]") document.write("Encoded : " + str); // New Line document.write("<br>"); // unescape() function document.write("Decoded : " + unescape(str)) </script>Output:Encoded : Geeks%20for%20Geeks%21%21%21 Decoded : Geeks for Geeks!!! Encoded : To%20contribute%20articles%20contact%20us%20at%[email protected] Decoded : To contribute articles contact us at [email protected] Supported Browsers:Google Chrome 1 and aboveEdge 12 and aboveInternet Explorer 3 and aboveMozilla Firefox 1 and aboveSafari 1 and aboveOpera 3 and above Return value: This function returns a decoded string. Note: This function only decodes the special characters, this function is depricated.Exceptions: @ – + . / * _ More example codes for the above function are as follows:Program 1: <script> // Special character encoded with // escape function var str = escape("Geeks for Geeks!!!"); document.write("Encoded : " + str); // New Line document.write("<br>"); // unescape() function document.write("Decoded : " + unescape(str)) // New Line document.write("<br><br>"); // The exception // @ and . not encoded. str = escape("To contribute articles contact us" + "at [email protected]") document.write("Encoded : " + str); // New Line document.write("<br>"); // unescape() function document.write("Decoded : " + unescape(str)) </script> Output: Encoded : Geeks%20for%20Geeks%21%21%21 Decoded : Geeks for Geeks!!! Encoded : To%20contribute%20articles%20contact%20us%20at%[email protected] Decoded : To contribute articles contact us at [email protected] Supported Browsers: Google Chrome 1 and above Edge 12 and above Internet Explorer 3 and above Mozilla Firefox 1 and above Safari 1 and above Opera 3 and above ysachin2314 javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 71, "s": 28, "text": "Prerequisite: JavaScript escape() Function" }, { "code": null, "e": 120, "s": 71, "text": "Below is the example of the unescape() function." }, { "code": null, "e": 534, "s": 120, "text": "Example:<script> // Special character encoded with // escape function document.write(unescape(\"Geeks%20for%20Geeks%21%21%21\")); document.write(\"<br>\"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(unescape(\"To%20contribute%20articles%20contact\"+ \"%20us%[email protected]\"));</script> " }, { "code": "<script> // Special character encoded with // escape function document.write(unescape(\"Geeks%20for%20Geeks%21%21%21\")); document.write(\"<br>\"); // Print encoded string using escape() function // Also include exceptions i.e. @ and . document.write(unescape(\"To%20contribute%20articles%20contact\"+ \"%20us%[email protected]\"));</script> ", "e": 940, "s": 534, "text": null }, { "code": null, "e": 1034, "s": 940, "text": "Output:Geeks for Geeks!!!\nTo contribute articles contact us at \[email protected]" }, { "code": null, "e": 1121, "s": 1034, "text": "Geeks for Geeks!!!\nTo contribute articles contact us at \[email protected]" }, { "code": null, "e": 1367, "s": 1121, "text": "The unescape() function in JavaScript takes a string as a parameter and uses to decode that string encoded by the escape() function. The hexadecimal sequence in the string is replaced by the characters they represent when decoded via unescape()." }, { "code": null, "e": 1375, "s": 1367, "text": "Syntax:" }, { "code": null, "e": 1392, "s": 1375, "text": "unescape(string)" }, { "code": null, "e": 1485, "s": 1392, "text": "Parameters: This function accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 2796, "s": 1485, "text": "string: This parameters holds the string that will be decoded.Return value: This function returns a decoded string.Note: This function only decodes the special characters, this function is depricated.Exceptions: @ – + . / * _More example codes for the above function are as follows:Program 1:<script> // Special character encoded with // escape function var str = escape(\"Geeks for Geeks!!!\"); document.write(\"Encoded : \" + str); // New Line document.write(\"<br>\"); // unescape() function document.write(\"Decoded : \" + unescape(str)) // New Line document.write(\"<br><br>\"); // The exception // @ and . not encoded. str = escape(\"To contribute articles contact us\" + \"at [email protected]\") document.write(\"Encoded : \" + str); // New Line document.write(\"<br>\"); // unescape() function document.write(\"Decoded : \" + unescape(str)) </script>Output:Encoded : Geeks%20for%20Geeks%21%21%21\nDecoded : Geeks for Geeks!!!\n\nEncoded : To%20contribute%20articles%20contact%20us%20at%[email protected]\nDecoded : To contribute articles contact us at [email protected]\nSupported Browsers:Google Chrome 1 and aboveEdge 12 and aboveInternet Explorer 3 and aboveMozilla Firefox 1 and aboveSafari 1 and aboveOpera 3 and above" }, { "code": null, "e": 2850, "s": 2796, "text": "Return value: This function returns a decoded string." }, { "code": null, "e": 2961, "s": 2850, "text": "Note: This function only decodes the special characters, this function is depricated.Exceptions: @ – + . / * _" }, { "code": null, "e": 3029, "s": 2961, "text": "More example codes for the above function are as follows:Program 1:" }, { "code": "<script> // Special character encoded with // escape function var str = escape(\"Geeks for Geeks!!!\"); document.write(\"Encoded : \" + str); // New Line document.write(\"<br>\"); // unescape() function document.write(\"Decoded : \" + unescape(str)) // New Line document.write(\"<br><br>\"); // The exception // @ and . not encoded. str = escape(\"To contribute articles contact us\" + \"at [email protected]\") document.write(\"Encoded : \" + str); // New Line document.write(\"<br>\"); // unescape() function document.write(\"Decoded : \" + unescape(str)) </script>", "e": 3654, "s": 3029, "text": null }, { "code": null, "e": 3662, "s": 3654, "text": "Output:" }, { "code": null, "e": 3898, "s": 3662, "text": "Encoded : Geeks%20for%20Geeks%21%21%21\nDecoded : Geeks for Geeks!!!\n\nEncoded : To%20contribute%20articles%20contact%20us%20at%[email protected]\nDecoded : To contribute articles contact us at [email protected]\n" }, { "code": null, "e": 3918, "s": 3898, "text": "Supported Browsers:" }, { "code": null, "e": 3944, "s": 3918, "text": "Google Chrome 1 and above" }, { "code": null, "e": 3962, "s": 3944, "text": "Edge 12 and above" }, { "code": null, "e": 3992, "s": 3962, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 4020, "s": 3992, "text": "Mozilla Firefox 1 and above" }, { "code": null, "e": 4039, "s": 4020, "text": "Safari 1 and above" }, { "code": null, "e": 4057, "s": 4039, "text": "Opera 3 and above" }, { "code": null, "e": 4069, "s": 4057, "text": "ysachin2314" }, { "code": null, "e": 4090, "s": 4069, "text": "javascript-functions" }, { "code": null, "e": 4101, "s": 4090, "text": "JavaScript" }, { "code": null, "e": 4118, "s": 4101, "text": "Web Technologies" } ]
Python | Pandas Dataframe.rank()
17 Sep, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Dataframe.rank() method returns a rank of every respective index of a series passed. The rank is returned on the basis of position after sorting. Syntax:DataFrame.rank(axis=0, method=’average’, numeric_only=None, na_option=’keep’, ascending=True, pct=False) Parameters:axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column.method: Takes a string input(‘average’, ‘min’, ‘max’, ‘first’, ‘dense’) which tells pandas what to do with same values. Default is average which means assign average of ranks to the similar values.numeric_only: Takes a boolean value and the rank function works on non-numeric value only if it’s False.na_option: Takes 3 string input(‘keep’, ‘top’, ‘bottom’) to set position of Null values if any in the passed Series.ascending: Boolean value which ranks in ascending order if True.pct: Boolean value which ranks percentage wise if True. Return type: Series with Rank of every index of caller series. For link to CSV file Used in Code, click here. Example #1: Ranking Column with Unique values In the following example, a new rank column is created which ranks the Name of every Player. All the values in Name column are unique and hence there is no need to describe a method. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # creating a rank column and passing the returned rank seriesdata["Rank"] = data["Name"].rank() # displaydata # sorting w.r.t name columndata.sort_values("Name", inplace = True) # display after sorting w.r.t Name columndata Output:As shown in the image, a column rank was created with rank of every Name. After the sort_value function sorted the data frame with respect to name, it can be seen that the rank was also sorted since those were ranking of Names only. Before Sorting – After Sorting – Example #2: Sorting Column with some similar values In the following example, data frame is first sorted with respect to team name and first the method is default (i.e. average) and hence the rank of same Team players is average. After that min method is also used to see the output. # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # sorting w.r.t team namedata.sort_values("Team", inplace = True) # creating a rank column and passing the returned rank series# change method to 'min' to rank by minimumdata["Rank"] = data["Team"].rank(method ='average') # displaydata Output: With method=’average’ With method=’min’ Python pandas-dataFrame Python pandas-dataFrame-methods 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": "\n17 Sep, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 395, "s": 242, "text": "Pandas Dataframe.rank() method returns a rank of every respective index of a series passed. The rank is returned on the basis of position after sorting." }, { "code": null, "e": 507, "s": 395, "text": "Syntax:DataFrame.rank(axis=0, method=’average’, numeric_only=None, na_option=’keep’, ascending=True, pct=False)" }, { "code": null, "e": 1113, "s": 507, "text": "Parameters:axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column.method: Takes a string input(‘average’, ‘min’, ‘max’, ‘first’, ‘dense’) which tells pandas what to do with same values. Default is average which means assign average of ranks to the similar values.numeric_only: Takes a boolean value and the rank function works on non-numeric value only if it’s False.na_option: Takes 3 string input(‘keep’, ‘top’, ‘bottom’) to set position of Null values if any in the passed Series.ascending: Boolean value which ranks in ascending order if True.pct: Boolean value which ranks percentage wise if True." }, { "code": null, "e": 1176, "s": 1113, "text": "Return type: Series with Rank of every index of caller series." }, { "code": null, "e": 1223, "s": 1176, "text": "For link to CSV file Used in Code, click here." }, { "code": null, "e": 1269, "s": 1223, "text": "Example #1: Ranking Column with Unique values" }, { "code": null, "e": 1452, "s": 1269, "text": "In the following example, a new rank column is created which ranks the Name of every Player. All the values in Name column are unique and hence there is no need to describe a method." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # creating a rank column and passing the returned rank seriesdata[\"Rank\"] = data[\"Name\"].rank() # displaydata # sorting w.r.t name columndata.sort_values(\"Name\", inplace = True) # display after sorting w.r.t Name columndata", "e": 1790, "s": 1452, "text": null }, { "code": null, "e": 2030, "s": 1790, "text": "Output:As shown in the image, a column rank was created with rank of every Name. After the sort_value function sorted the data frame with respect to name, it can be seen that the rank was also sorted since those were ranking of Names only." }, { "code": null, "e": 2115, "s": 2030, "text": "Before Sorting – After Sorting – Example #2: Sorting Column with some similar values" }, { "code": null, "e": 2347, "s": 2115, "text": "In the following example, data frame is first sorted with respect to team name and first the method is default (i.e. average) and hence the rank of same Team players is average. After that min method is also used to see the output." }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # sorting w.r.t team namedata.sort_values(\"Team\", inplace = True) # creating a rank column and passing the returned rank series# change method to 'min' to rank by minimumdata[\"Rank\"] = data[\"Team\"].rank(method ='average') # displaydata", "e": 2696, "s": 2347, "text": null }, { "code": null, "e": 2704, "s": 2696, "text": "Output:" }, { "code": null, "e": 2726, "s": 2704, "text": "With method=’average’" }, { "code": null, "e": 2746, "s": 2728, "text": "With method=’min’" }, { "code": null, "e": 2770, "s": 2746, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2802, "s": 2770, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2816, "s": 2802, "text": "Python-pandas" }, { "code": null, "e": 2823, "s": 2816, "text": "Python" } ]
turtle.setundobuffer() function in Python
17 May, 2021 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This function is used to set or disable undobuffer. It takes the size parameter. If the size is an integer an empty undobuffer of a given size is installed. Size gives the maximum number of turtle-actions that can be undone by the undo() function. If the size is None, no undobuffer is present. Syntax : turtle.setundobuffer(size) Below is the implementation of the above method with some examples : Example 1 : Python3 # importing packageimport turtle # check default value of undobufferprint(turtle.undobufferentries()) # set undo buffer by 10 as valueturtle.setundobuffer(10) # loop executes 50 times with# turtle.forward(1) statement# i.e; undobufferentries gives 50for i in range(50): turtle.forward(1) # but gives 10 as it is set alreadyprint(turtle.undobufferentries()) Output : 0 10 Example 2 : Python3 # importing packageimport turtle # print default valueprint(turtle.undobufferentries()) # loop for motionfor i in range(50): # one statement increase the # undobuffer entries turtle.fd(1) # print undobuffer entries ie; 50# due to above loop with one statementprint(turtle.undobufferentries()) # set undobuffer to Noneturtle.setundobuffer(None) # print undobuffer entries# i.e; value set by set undobufferprint(turtle.undobufferentries()) Output : 0 50 0 akshaysingh98088 Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 May, 2021" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 540, "s": 245, "text": "This function is used to set or disable undobuffer. It takes the size parameter. If the size is an integer an empty undobuffer of a given size is installed. Size gives the maximum number of turtle-actions that can be undone by the undo() function. If the size is None, no undobuffer is present." }, { "code": null, "e": 549, "s": 540, "text": "Syntax :" }, { "code": null, "e": 576, "s": 549, "text": "turtle.setundobuffer(size)" }, { "code": null, "e": 645, "s": 576, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 657, "s": 645, "text": "Example 1 :" }, { "code": null, "e": 665, "s": 657, "text": "Python3" }, { "code": "# importing packageimport turtle # check default value of undobufferprint(turtle.undobufferentries()) # set undo buffer by 10 as valueturtle.setundobuffer(10) # loop executes 50 times with# turtle.forward(1) statement# i.e; undobufferentries gives 50for i in range(50): turtle.forward(1) # but gives 10 as it is set alreadyprint(turtle.undobufferentries())", "e": 1031, "s": 665, "text": null }, { "code": null, "e": 1043, "s": 1034, "text": "Output :" }, { "code": null, "e": 1050, "s": 1045, "text": "0\n10" }, { "code": null, "e": 1064, "s": 1052, "text": "Example 2 :" }, { "code": null, "e": 1074, "s": 1066, "text": "Python3" }, { "code": "# importing packageimport turtle # print default valueprint(turtle.undobufferentries()) # loop for motionfor i in range(50): # one statement increase the # undobuffer entries turtle.fd(1) # print undobuffer entries ie; 50# due to above loop with one statementprint(turtle.undobufferentries()) # set undobuffer to Noneturtle.setundobuffer(None) # print undobuffer entries# i.e; value set by set undobufferprint(turtle.undobufferentries())", "e": 1528, "s": 1074, "text": null }, { "code": null, "e": 1540, "s": 1531, "text": "Output :" }, { "code": null, "e": 1549, "s": 1542, "text": "0\n50\n0" }, { "code": null, "e": 1568, "s": 1551, "text": "akshaysingh98088" }, { "code": null, "e": 1582, "s": 1568, "text": "Python-turtle" }, { "code": null, "e": 1589, "s": 1582, "text": "Python" } ]
How to display multiple horizontal images in Bootstrap card ?
12 Jul, 2019 Pre-requisite: Bootstrap Cards Bootstrap cards provide a flexible and extensible content container with multiple variants and options such as styling the Tables, stacking multiple images horizontally/vertically, making the stacked contents responsive, etc. Cards include so many options for customizing their backgrounds, borders, Header, footer, color, etc. To show multiple horizontal images in Bootstrap card you need to clear the basics of Bootstrap Card, there is an easy way to do that task. Also, there is some pre-defined bootstrap code which will give a similar output after that you can easily modify that little bit with the help of CSS, those are grid markup Card groups Card decks Card columns Example: This example inserts multiple images in Bootstrap card horizontally. <!DOCTYPE html> <html lang="en"> <head> <title> How to show multiple horizontal images in Bootstrap card ? </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> img { max-width: 100%; max-height: 50%; padding-top:10px; } h1 { color: green; } </style></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card-group"> <!--bootstrap card with 3 horizontal images--> <div class="row"> <div class="card col-md-4"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"> <div class="card-body"> <h3 class="card-title">Compare</h3> <p class="card-text">JavaScript | Python</p> </div> </div> <div class="card col-md-4"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190705124953/Left-SP2019.png"> <div class="card-body"> <h3 class="card-title text-primary">Placement</h3> <p class="card-text">Sudo Placement Course</p> </div> </div> <div class="card col-md-4"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190623192118/Left-Bar-DSA-Self.png"> <div class="card-body"> <h3 class="card-title">DSA</h3> <p class="card-text">DS & Algo Course</p> </div> </div> </div> </div> </div></body></html> Output: Bootstrap-4 Picked Bootstrap Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jul, 2019" }, { "code": null, "e": 59, "s": 28, "text": "Pre-requisite: Bootstrap Cards" }, { "code": null, "e": 387, "s": 59, "text": "Bootstrap cards provide a flexible and extensible content container with multiple variants and options such as styling the Tables, stacking multiple images horizontally/vertically, making the stacked contents responsive, etc. Cards include so many options for customizing their backgrounds, borders, Header, footer, color, etc." }, { "code": null, "e": 687, "s": 387, "text": "To show multiple horizontal images in Bootstrap card you need to clear the basics of Bootstrap Card, there is an easy way to do that task. Also, there is some pre-defined bootstrap code which will give a similar output after that you can easily modify that little bit with the help of CSS, those are" }, { "code": null, "e": 699, "s": 687, "text": "grid markup" }, { "code": null, "e": 711, "s": 699, "text": "Card groups" }, { "code": null, "e": 722, "s": 711, "text": "Card decks" }, { "code": null, "e": 735, "s": 722, "text": "Card columns" }, { "code": null, "e": 813, "s": 735, "text": "Example: This example inserts multiple images in Bootstrap card horizontally." }, { "code": "<!DOCTYPE html> <html lang=\"en\"> <head> <title> How to show multiple horizontal images in Bootstrap card ? </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> img { max-width: 100%; max-height: 50%; padding-top:10px; } h1 { color: green; } </style></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card-group\"> <!--bootstrap card with 3 horizontal images--> <div class=\"row\"> <div class=\"card col-md-4\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\"> <div class=\"card-body\"> <h3 class=\"card-title\">Compare</h3> <p class=\"card-text\">JavaScript | Python</p> </div> </div> <div class=\"card col-md-4\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190705124953/Left-SP2019.png\"> <div class=\"card-body\"> <h3 class=\"card-title text-primary\">Placement</h3> <p class=\"card-text\">Sudo Placement Course</p> </div> </div> <div class=\"card col-md-4\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190623192118/Left-Bar-DSA-Self.png\"> <div class=\"card-body\"> <h3 class=\"card-title\">DSA</h3> <p class=\"card-text\">DS & Algo Course</p> </div> </div> </div> </div> </div></body></html> ", "e": 3274, "s": 813, "text": null }, { "code": null, "e": 3282, "s": 3274, "text": "Output:" }, { "code": null, "e": 3294, "s": 3282, "text": "Bootstrap-4" }, { "code": null, "e": 3301, "s": 3294, "text": "Picked" }, { "code": null, "e": 3311, "s": 3301, "text": "Bootstrap" }, { "code": null, "e": 3328, "s": 3311, "text": "Web Technologies" }, { "code": null, "e": 3355, "s": 3328, "text": "Web technologies Questions" } ]
How to implement Google Login in your Web app with Firebase ?
12 Jun, 2020 Firebase offers a great number of options to implement Login in your app. Some of which are: Using Email. Using Phone number. Using Google. Using Facebook etc. The best part is you don’t have to worry about handling the login flow, Firebase takes care of it. Approach: First of all, create a Firebase project by following these steps: Go to https://console.firebase.google.com/ and login with your google account. Create a project on Firebase. Add Firebase SDKs to your app. <!– Insert these scripts inside your body tag –> <body> <!–This is the most important script that has to be added –> <script src=”/__/firebase/7.14.4/firebase-app.js”></script> <!– In order to use Google login add this script –> <script src=”/__/firebase/7.14.4/firebase-auth.js”></script></body> Now that we have added these scripts in our app, we will now initialize the Firebase in our app. In the Firebase console go to the app settings, from there copy App config object and paste it in your code. App config object looks like this. var firebaseConfig = { apiKey: "your-api-key", authDomain: "your-project-id.firebaseapp.com", databaseURL: "https://your-project-id.firebaseio.com", projectId: "your-project-id", storageBucket: "your-project-id.appspot.com", messagingSenderId: "the-sender-id", appId: "the-app-id", measurementId: "G-measurement-id", }; If you followed these steps correctly your app will be registered with Firebase. Now, we will enable google login in our app by following these steps: Go to the Firebase console and open Auth section Enable google sign on the sign in method tab and save the settings. In your app create a google provider object to handle login flow. const GoogleAuth = new firebase.auth.GoogleAuthProvider(); Authenticate user by using the instance of object that you created with the Firebase. You can either redirect the user to sign in page or open a pop-up window. //To sign in with pop-up. firebase.auth().signInWithPopup(googleAuth); //To sign in with redirect. firebase.auth().signInWithRedirect(googleAuth); Google Login method is implemented in your app, now you are good to go. Example: We will create a simple react based web app with just the login button. Code for the button component: Javascript import React, { Component } from "react";import firebase from 'firebase'; class tutorial extends Component{render(){return(<div> <button onClick={() => { // Google provider object is created here. const googleAuth = new firebase.auth.GoogleAuthProvider(); // using the object we will authenticate the user. firebase.auth().signInWithPopup(googleAuth); }} > Sign in with Google </button> </div> ); } } export default tutorial; Code for your Firebase.ts file: Javascript import * as firebase from 'firebase';const firebaseConfig = { apiKey: "****", authDomain: "****.firebaseapp.com", databaseURL: "https://*****.firebaseio.com", projectId: "****", storageBucket: "****.appspot.com", messagingSenderId: "****", appId: "****", measurementId: "****"};class Firebase { constructor() { firebase.initializeApp(firebaseConfig); }} export default Firebase; Output: 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": "\n12 Jun, 2020" }, { "code": null, "e": 145, "s": 52, "text": "Firebase offers a great number of options to implement Login in your app. Some of which are:" }, { "code": null, "e": 158, "s": 145, "text": "Using Email." }, { "code": null, "e": 178, "s": 158, "text": "Using Phone number." }, { "code": null, "e": 192, "s": 178, "text": "Using Google." }, { "code": null, "e": 212, "s": 192, "text": "Using Facebook etc." }, { "code": null, "e": 311, "s": 212, "text": "The best part is you don’t have to worry about handling the login flow, Firebase takes care of it." }, { "code": null, "e": 321, "s": 311, "text": "Approach:" }, { "code": null, "e": 387, "s": 321, "text": "First of all, create a Firebase project by following these steps:" }, { "code": null, "e": 466, "s": 387, "text": "Go to https://console.firebase.google.com/ and login with your google account." }, { "code": null, "e": 496, "s": 466, "text": "Create a project on Firebase." }, { "code": null, "e": 527, "s": 496, "text": "Add Firebase SDKs to your app." }, { "code": null, "e": 576, "s": 527, "text": "<!– Insert these scripts inside your body tag –>" }, { "code": null, "e": 583, "s": 576, "text": "<body>" }, { "code": null, "e": 644, "s": 583, "text": "<!–This is the most important script that has to be added –>" }, { "code": null, "e": 704, "s": 644, "text": "<script src=”/__/firebase/7.14.4/firebase-app.js”></script>" }, { "code": null, "e": 756, "s": 704, "text": "<!– In order to use Google login add this script –>" }, { "code": null, "e": 824, "s": 756, "text": "<script src=”/__/firebase/7.14.4/firebase-auth.js”></script></body>" }, { "code": null, "e": 921, "s": 824, "text": "Now that we have added these scripts in our app, we will now initialize the Firebase in our app." }, { "code": null, "e": 1030, "s": 921, "text": "In the Firebase console go to the app settings, from there copy App config object and paste it in your code." }, { "code": null, "e": 1065, "s": 1030, "text": "App config object looks like this." }, { "code": null, "e": 1403, "s": 1065, "text": "var firebaseConfig = {\n apiKey: \"your-api-key\",\n authDomain: \"your-project-id.firebaseapp.com\",\n databaseURL: \"https://your-project-id.firebaseio.com\",\n projectId: \"your-project-id\",\n storageBucket: \"your-project-id.appspot.com\",\n messagingSenderId: \"the-sender-id\",\n appId: \"the-app-id\",\n measurementId: \"G-measurement-id\",\n};\n\n" }, { "code": null, "e": 1484, "s": 1403, "text": "If you followed these steps correctly your app will be registered with Firebase." }, { "code": null, "e": 1554, "s": 1484, "text": "Now, we will enable google login in our app by following these steps:" }, { "code": null, "e": 1603, "s": 1554, "text": "Go to the Firebase console and open Auth section" }, { "code": null, "e": 1671, "s": 1603, "text": "Enable google sign on the sign in method tab and save the settings." }, { "code": null, "e": 1737, "s": 1671, "text": "In your app create a google provider object to handle login flow." }, { "code": null, "e": 1796, "s": 1737, "text": "const GoogleAuth = new firebase.auth.GoogleAuthProvider();" }, { "code": null, "e": 1882, "s": 1796, "text": "Authenticate user by using the instance of object that you created with the Firebase." }, { "code": null, "e": 1956, "s": 1882, "text": "You can either redirect the user to sign in page or open a pop-up window." }, { "code": null, "e": 2107, "s": 1956, "text": "//To sign in with pop-up.\nfirebase.auth().signInWithPopup(googleAuth);\n\n//To sign in with redirect. \nfirebase.auth().signInWithRedirect(googleAuth);\n\n" }, { "code": null, "e": 2179, "s": 2107, "text": "Google Login method is implemented in your app, now you are good to go." }, { "code": null, "e": 2188, "s": 2179, "text": "Example:" }, { "code": null, "e": 2260, "s": 2188, "text": "We will create a simple react based web app with just the login button." }, { "code": null, "e": 2291, "s": 2260, "text": "Code for the button component:" }, { "code": null, "e": 2302, "s": 2291, "text": "Javascript" }, { "code": "import React, { Component } from \"react\";import firebase from 'firebase'; class tutorial extends Component{render(){return(<div> <button onClick={() => { // Google provider object is created here. const googleAuth = new firebase.auth.GoogleAuthProvider(); // using the object we will authenticate the user. firebase.auth().signInWithPopup(googleAuth); }} > Sign in with Google </button> </div> ); } } export default tutorial;", "e": 2822, "s": 2302, "text": null }, { "code": null, "e": 2854, "s": 2822, "text": "Code for your Firebase.ts file:" }, { "code": null, "e": 2865, "s": 2854, "text": "Javascript" }, { "code": "import * as firebase from 'firebase';const firebaseConfig = { apiKey: \"****\", authDomain: \"****.firebaseapp.com\", databaseURL: \"https://*****.firebaseio.com\", projectId: \"****\", storageBucket: \"****.appspot.com\", messagingSenderId: \"****\", appId: \"****\", measurementId: \"****\"};class Firebase { constructor() { firebase.initializeApp(firebaseConfig); }} export default Firebase;", "e": 3272, "s": 2865, "text": null }, { "code": null, "e": 3280, "s": 3272, "text": "Output:" }, { "code": null, "e": 3297, "s": 3280, "text": "Web Technologies" }, { "code": null, "e": 3324, "s": 3297, "text": "Web technologies Questions" } ]
Python | os.path.islink() method
12 Jun, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation. os.path.islink() method in Python is used to check whether the given path represents an existing directory entry that is a symbolic link or not. Note: If symbolic links are not supported by the Python runtime then os.path.islink() method always returns False. Syntax: os.path.islink(path) Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path. Return Type: This method returns a Boolean value of class bool. This method returns True if the given path is a directory entry that is a symbolic link, otherwise returns False. Create a soft link or symbolic linkIn Unix or Linux, soft link or symbolic link can be created using ln command. Below is the syntax to create a symbolic link at the shell prompt: $ ln -s {source-filename} {symbolic-filename} Example: In above output, file(shortcut).txt is a symbolic link which also shows the file name to which it is linked. Code: Use of os.path.islink() method to check if the given path is a symbolic link # Python program to explain os.path.islink() method # importing os.path module import os.path # Path path = "/home/ihritik/Documents/file(original).txt" # Check whether the # given path is a# symbolic linkisLink = os.path.islink(path)print(isLink) # Pathpath = "/home/ihritik/Desktop/file(shortcut).txt" # Check whether the # given path is a# symbolic linkisLink = os.path.islink(path)print(isFile) False True Reference: https://docs.python.org/3/library/os.path.html Python OS-path-module python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2019" }, { "code": null, "e": 339, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation." }, { "code": null, "e": 484, "s": 339, "text": "os.path.islink() method in Python is used to check whether the given path represents an existing directory entry that is a symbolic link or not." }, { "code": null, "e": 599, "s": 484, "text": "Note: If symbolic links are not supported by the Python runtime then os.path.islink() method always returns False." }, { "code": null, "e": 628, "s": 599, "text": "Syntax: os.path.islink(path)" }, { "code": null, "e": 771, "s": 628, "text": "Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path." }, { "code": null, "e": 949, "s": 771, "text": "Return Type: This method returns a Boolean value of class bool. This method returns True if the given path is a directory entry that is a symbolic link, otherwise returns False." }, { "code": null, "e": 1129, "s": 949, "text": "Create a soft link or symbolic linkIn Unix or Linux, soft link or symbolic link can be created using ln command. Below is the syntax to create a symbolic link at the shell prompt:" }, { "code": null, "e": 1176, "s": 1129, "text": "$ ln -s {source-filename} {symbolic-filename}\n" }, { "code": null, "e": 1185, "s": 1176, "text": "Example:" }, { "code": null, "e": 1294, "s": 1185, "text": "In above output, file(shortcut).txt is a symbolic link which also shows the file name to which it is linked." }, { "code": null, "e": 1377, "s": 1294, "text": "Code: Use of os.path.islink() method to check if the given path is a symbolic link" }, { "code": "# Python program to explain os.path.islink() method # importing os.path module import os.path # Path path = \"/home/ihritik/Documents/file(original).txt\" # Check whether the # given path is a# symbolic linkisLink = os.path.islink(path)print(isLink) # Pathpath = \"/home/ihritik/Desktop/file(shortcut).txt\" # Check whether the # given path is a# symbolic linkisLink = os.path.islink(path)print(isFile)", "e": 1788, "s": 1377, "text": null }, { "code": null, "e": 1800, "s": 1788, "text": "False\nTrue\n" }, { "code": null, "e": 1858, "s": 1800, "text": "Reference: https://docs.python.org/3/library/os.path.html" }, { "code": null, "e": 1880, "s": 1858, "text": "Python OS-path-module" }, { "code": null, "e": 1897, "s": 1880, "text": "python-os-module" }, { "code": null, "e": 1904, "s": 1897, "text": "Python" } ]
How to Setup Sublime Text 3 for Python in Windows?
01 Jun, 2020 Written by a Google engineer sublime text is a cross-platform IDE developed in C++ and Python. It has basic built-in support for Python. Sublime text is fast and you can customize this editor as per your need to create a full-fledged Python development environment. You can install packages such as debugging, auto-completion, code linting, etc. There are also various packages for scientific development, Django, Flask, and so on. Sublime Text 3 can be downloaded from its official site sublimetext.com. To install sublime text 3 on Windows, go through How to install Sublime Text 3 in Windows? Step 1: Click the Advanced system settings link. Step 2: Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New. Step 3: In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK. Step 1: Create a new file and save it with extension .py for example save it as checkversion.py. Now, Go to Tools -> Build System -> Python then type on your checkversion.pyThis is showing the version of python. This means python is successfully installed and added in Environment Variable. Step 2: Add new build system on your Sublime Tools -> Build System -> New Build System and make sure that the new build system has this following command { "cmd":["C:/Users/<user>/AppData/Local/Programs/Python/Python37-32/python.exe", "-u", "$file"], "file_regex": "^[ ]File \"(...?)\", line ([0-9]*)", "selector": "source.python"} Select your new system build newPython3 and re-run the checkversion.py and now it should be using Python 3 ALL Done...Now create any file and save it with .py extension Now you can run your Python code by using CTRL+SHIFT+B and choose from the 2 options. How To Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jun, 2020" }, { "code": null, "e": 486, "s": 54, "text": "Written by a Google engineer sublime text is a cross-platform IDE developed in C++ and Python. It has basic built-in support for Python. Sublime text is fast and you can customize this editor as per your need to create a full-fledged Python development environment. You can install packages such as debugging, auto-completion, code linting, etc. There are also various packages for scientific development, Django, Flask, and so on." }, { "code": null, "e": 650, "s": 486, "text": "Sublime Text 3 can be downloaded from its official site sublimetext.com. To install sublime text 3 on Windows, go through How to install Sublime Text 3 in Windows?" }, { "code": null, "e": 699, "s": 650, "text": "Step 1: Click the Advanced system settings link." }, { "code": null, "e": 891, "s": 699, "text": "Step 2: Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New." }, { "code": null, "e": 1066, "s": 891, "text": "Step 3: In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK." }, { "code": null, "e": 1357, "s": 1066, "text": "Step 1: Create a new file and save it with extension .py for example save it as checkversion.py. Now, Go to Tools -> Build System -> Python then type on your checkversion.pyThis is showing the version of python. This means python is successfully installed and added in Environment Variable." }, { "code": null, "e": 1511, "s": 1357, "text": "Step 2: Add new build system on your Sublime Tools -> Build System -> New Build System and make sure that the new build system has this following command" }, { "code": "{ \"cmd\":[\"C:/Users/<user>/AppData/Local/Programs/Python/Python37-32/python.exe\", \"-u\", \"$file\"], \"file_regex\": \"^[ ]File \\\"(...?)\\\", line ([0-9]*)\", \"selector\": \"source.python\"}", "e": 1689, "s": 1511, "text": null }, { "code": null, "e": 1796, "s": 1689, "text": "Select your new system build newPython3 and re-run the checkversion.py and now it should be using Python 3" }, { "code": null, "e": 1858, "s": 1796, "text": "ALL Done...Now create any file and save it with .py extension" }, { "code": null, "e": 1944, "s": 1858, "text": "Now you can run your Python code by using CTRL+SHIFT+B and choose from the 2 options." }, { "code": null, "e": 1951, "s": 1944, "text": "How To" }, { "code": null, "e": 1958, "s": 1951, "text": "Python" }, { "code": null, "e": 1975, "s": 1958, "text": "Web Technologies" } ]
Oracle DataBase – Grant Privileges to a User in SQL Command Line
12 Jan, 2022 As we create a new user in the Oracle database, we first need to grant it the required privileges. After that only we can use that user to perform any task, provided that task comes under the role of privileges provided to it. This is illustrated below. For this article, we will be using the SQL Command-Line. Step 1: Open the SQL Command Line by typing run in the Search toolbar and selecting the option of Run as administrator. The SQL Command Line opens. Step 2: The following screen appears after clicking “Yes” on the dialog box which appears after step 1. Output: Step 3: Connect to the oracle database using CONNECT command. Query: CONNECT Hit ENTER after typing the command. Output: Step 4: Login using the default user i.e. the SYSTEM user. So type in the user-name as SYSTEM and then type in the correct password and hit Enter. Note: The password for the SYSTEM user is set during Oracle installation. Output: Step 5: Now, we create a new user named GFG. Syntax: CREATE USER NEW_USER_NAME INENTIFIED BY PASSWORD; Query: CREATE USER NEWUSERGFG INENTIFIED BY GFGQWERTY; Note: Here, we set the password as GFGQWERTY. Output: Step 6: Now, we close this session and reopen the SQL Command Line using Steps 1 and 2. We try to CONNECT to the session using NEWUSERGFG user-name. An error is thrown as the user NEWUSERGFG doesn’t have the privilege to start a session. Query: CONNECT Output: Step 7: Again connect using SYSTEM user-name. Now we shall enable all the privileges to NEWUSERGFG users. Syntax: GRANT ALL PRIVILEGES TO NEW_USER_NAME; Query: GRANT ALL PRIVILEGES TO NEWUSERGFG; Step 8: We test the last step by re-attempting to connect using NEWUSERGFG user-name. Query: CONNECT Note: The connection is successfully established this time and Connected is displayed. Step 9: Create a table named NEWSAMPLETABLE containing 2 columns i.e. ID and NAME. This further establishes a successful connection. Query: CREATE TABLE NEWSAMPLETABLE( ID INT, NAME VARCHAR2(10) ); Oracle Picked SQL-Query SQL-Server SQL Oracle SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jan, 2022" }, { "code": null, "e": 339, "s": 28, "text": "As we create a new user in the Oracle database, we first need to grant it the required privileges. After that only we can use that user to perform any task, provided that task comes under the role of privileges provided to it. This is illustrated below. For this article, we will be using the SQL Command-Line." }, { "code": null, "e": 487, "s": 339, "text": "Step 1: Open the SQL Command Line by typing run in the Search toolbar and selecting the option of Run as administrator. The SQL Command Line opens." }, { "code": null, "e": 591, "s": 487, "text": "Step 2: The following screen appears after clicking “Yes” on the dialog box which appears after step 1." }, { "code": null, "e": 599, "s": 591, "text": "Output:" }, { "code": null, "e": 661, "s": 599, "text": "Step 3: Connect to the oracle database using CONNECT command." }, { "code": null, "e": 668, "s": 661, "text": "Query:" }, { "code": null, "e": 676, "s": 668, "text": "CONNECT" }, { "code": null, "e": 712, "s": 676, "text": "Hit ENTER after typing the command." }, { "code": null, "e": 720, "s": 712, "text": "Output:" }, { "code": null, "e": 868, "s": 720, "text": "Step 4: Login using the default user i.e. the SYSTEM user. So type in the user-name as SYSTEM and then type in the correct password and hit Enter. " }, { "code": null, "e": 942, "s": 868, "text": "Note: The password for the SYSTEM user is set during Oracle installation." }, { "code": null, "e": 950, "s": 942, "text": "Output:" }, { "code": null, "e": 995, "s": 950, "text": "Step 5: Now, we create a new user named GFG." }, { "code": null, "e": 1003, "s": 995, "text": "Syntax:" }, { "code": null, "e": 1053, "s": 1003, "text": "CREATE USER NEW_USER_NAME INENTIFIED BY PASSWORD;" }, { "code": null, "e": 1060, "s": 1053, "text": "Query:" }, { "code": null, "e": 1108, "s": 1060, "text": "CREATE USER NEWUSERGFG INENTIFIED BY GFGQWERTY;" }, { "code": null, "e": 1154, "s": 1108, "text": "Note: Here, we set the password as GFGQWERTY." }, { "code": null, "e": 1162, "s": 1154, "text": "Output:" }, { "code": null, "e": 1400, "s": 1162, "text": "Step 6: Now, we close this session and reopen the SQL Command Line using Steps 1 and 2. We try to CONNECT to the session using NEWUSERGFG user-name. An error is thrown as the user NEWUSERGFG doesn’t have the privilege to start a session." }, { "code": null, "e": 1407, "s": 1400, "text": "Query:" }, { "code": null, "e": 1415, "s": 1407, "text": "CONNECT" }, { "code": null, "e": 1423, "s": 1415, "text": "Output:" }, { "code": null, "e": 1529, "s": 1423, "text": "Step 7: Again connect using SYSTEM user-name. Now we shall enable all the privileges to NEWUSERGFG users." }, { "code": null, "e": 1537, "s": 1529, "text": "Syntax:" }, { "code": null, "e": 1576, "s": 1537, "text": "GRANT ALL PRIVILEGES TO NEW_USER_NAME;" }, { "code": null, "e": 1583, "s": 1576, "text": "Query:" }, { "code": null, "e": 1619, "s": 1583, "text": "GRANT ALL PRIVILEGES TO NEWUSERGFG;" }, { "code": null, "e": 1705, "s": 1619, "text": "Step 8: We test the last step by re-attempting to connect using NEWUSERGFG user-name." }, { "code": null, "e": 1712, "s": 1705, "text": "Query:" }, { "code": null, "e": 1720, "s": 1712, "text": "CONNECT" }, { "code": null, "e": 1807, "s": 1720, "text": "Note: The connection is successfully established this time and Connected is displayed." }, { "code": null, "e": 1940, "s": 1807, "text": "Step 9: Create a table named NEWSAMPLETABLE containing 2 columns i.e. ID and NAME. This further establishes a successful connection." }, { "code": null, "e": 1947, "s": 1940, "text": "Query:" }, { "code": null, "e": 2005, "s": 1947, "text": "CREATE TABLE NEWSAMPLETABLE(\nID INT,\nNAME VARCHAR2(10)\n);" }, { "code": null, "e": 2012, "s": 2005, "text": "Oracle" }, { "code": null, "e": 2019, "s": 2012, "text": "Picked" }, { "code": null, "e": 2029, "s": 2019, "text": "SQL-Query" }, { "code": null, "e": 2040, "s": 2029, "text": "SQL-Server" }, { "code": null, "e": 2044, "s": 2040, "text": "SQL" }, { "code": null, "e": 2051, "s": 2044, "text": "Oracle" }, { "code": null, "e": 2055, "s": 2051, "text": "SQL" } ]
How to Calculate IP Subnet Address with ipcalc Tool ?
30 May, 2021 Subnetting is something you’ll have to deal with if you’re doing any kind of moderate to advanced networking. While some people can do the binary math in their heads to figure out the correct subnet-mask, others may find it difficult to calculate. For those people, Ipcalc is a Linux utility that may assist them to compute the number of subnets, the subnetting mask, and other IP addressing-related information. Ipcalc determines the broadcast, network, Cisco wildcard mask, and host range from an IP address and netmask. You can create subnets and supernets by specifying a second netmask. It’s also meant to be a teaching tool. Therefore, the subnetting results are presented as simple binary values. Formats for multiple addresses and netmask output (dotted quad, hex, number of bits). Broadcast address, network class, Cisco wildcard, hosts/range, and network range are all output. Bitmaps of various types are output. A user-defined number of extra networks are output. Multiple networks can be accessed using the command line. Hostname DNS resolutions. To install Ipcalc in Ubuntu/Debian-based Linux, open terminal and run the following command: $ sudo apt-get install ipcalc Use ipcalc to find out everything you need to know about your IP address: $ ipcalc 192.168.1.27 To calculate subnet for 192.168.1.0/24 use the following command: $ ipcalc 192.168.1.0/24 To calculate a single subnet, use the following command: $ ipcalc 192.168.1.0 -s 5 Assume you want to split 192.168.1.0 into three subnets, with a total of 50 hosts. In each segment, specify your network mask and the number of hosts. $ ipcalc 192.168.1.0 -s 10 20 20 Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2021" }, { "code": null, "e": 441, "s": 28, "text": "Subnetting is something you’ll have to deal with if you’re doing any kind of moderate to advanced networking. While some people can do the binary math in their heads to figure out the correct subnet-mask, others may find it difficult to calculate. For those people, Ipcalc is a Linux utility that may assist them to compute the number of subnets, the subnetting mask, and other IP addressing-related information." }, { "code": null, "e": 732, "s": 441, "text": "Ipcalc determines the broadcast, network, Cisco wildcard mask, and host range from an IP address and netmask. You can create subnets and supernets by specifying a second netmask. It’s also meant to be a teaching tool. Therefore, the subnetting results are presented as simple binary values." }, { "code": null, "e": 818, "s": 732, "text": "Formats for multiple addresses and netmask output (dotted quad, hex, number of bits)." }, { "code": null, "e": 915, "s": 818, "text": "Broadcast address, network class, Cisco wildcard, hosts/range, and network range are all output." }, { "code": null, "e": 952, "s": 915, "text": "Bitmaps of various types are output." }, { "code": null, "e": 1004, "s": 952, "text": "A user-defined number of extra networks are output." }, { "code": null, "e": 1062, "s": 1004, "text": "Multiple networks can be accessed using the command line." }, { "code": null, "e": 1088, "s": 1062, "text": "Hostname DNS resolutions." }, { "code": null, "e": 1181, "s": 1088, "text": "To install Ipcalc in Ubuntu/Debian-based Linux, open terminal and run the following command:" }, { "code": null, "e": 1211, "s": 1181, "text": "$ sudo apt-get install ipcalc" }, { "code": null, "e": 1285, "s": 1211, "text": "Use ipcalc to find out everything you need to know about your IP address:" }, { "code": null, "e": 1307, "s": 1285, "text": "$ ipcalc 192.168.1.27" }, { "code": null, "e": 1374, "s": 1307, "text": "To calculate subnet for 192.168.1.0/24 use the following command: " }, { "code": null, "e": 1398, "s": 1374, "text": "$ ipcalc 192.168.1.0/24" }, { "code": null, "e": 1456, "s": 1398, "text": "To calculate a single subnet, use the following command: " }, { "code": null, "e": 1483, "s": 1456, "text": "$ ipcalc 192.168.1.0 -s 5" }, { "code": null, "e": 1634, "s": 1483, "text": "Assume you want to split 192.168.1.0 into three subnets, with a total of 50 hosts. In each segment, specify your network mask and the number of hosts." }, { "code": null, "e": 1667, "s": 1634, "text": "$ ipcalc 192.168.1.0 -s 10 20 20" }, { "code": null, "e": 1679, "s": 1667, "text": "Linux-Tools" }, { "code": null, "e": 1690, "s": 1679, "text": "Linux-Unix" } ]
How to check if string contains only digits in Java
05 Jul, 2022 Given string str, the task is to write a Java program to check whether a string contains only digits or not. If so, then print true, otherwise false. Examples: Input: str = “1234” Output: true Explanation: The given string contains only digits so that output is true. Input: str = “GeeksforGeeks2020” Output: false Explanation: The given string contains alphabet character and digits so that output is false. The idea is to traverse each character in the string and check if the character of the string contains only digits from 0 to 9. If all the character of the string contains only digits then return true, otherwise, return false. Below is the implementation of the above approach: Java // Java program for the above approach// contains only digitsclass GFG { // Function to check if a string // contains only digits public static boolean onlyDigits(String str, int n) { // Traverse the string from // start to end for (int i = 0; i < n; i++) { // Check if character is // not a digit between 0-9 // then return false if (str.charAt(i) < '0' || str.charAt(i) > '9') { return false; } } // If we reach here, that means // all characters were digits. return true; } // Driver Code public static void main(String args[]) { // Given string str String str = "1a234"; int len = str.length(); // Function Call System.out.println(onlyDigits(str, len)); }} false Time Complexity: O(N), where N is the length of the given string. Auxiliary Space: O(1) The idea is to iterate over each character of the string and check whether the specified character is a digit or not using Character.isDigit(char ch). If the character is a digit then return true, else return false. Below is the implementation of the above approach: Java // Java program to check if a string// contains only digitsclass GFG { // Function to check if a string // contains only digits public static boolean onlyDigits(String str, int n) { // Traverse the string from // start to end for (int i = 0; i < n; i++) { // Check if the sepecified // character is a not digit // then return false, // else return false if (!Character.isDigit(str.charAt(i))) { return false; } } // If we reach here that means all // the characters were digits, // so we return true return true; } // Driver Code public static void main(String args[]) { // Given string str String str = "1234"; int len = str.length(); // Function Call System.out.println(onlyDigits(str, len)); }} true Time Complexity: O(N), where N is the length of the given string. Auxiliary Space: O(1) Get the String. Create a Regular Expression to check string contains only digits as mentioned below: regex = "[0-9]+"; Match the given string with Regular Expression. In Java, this can be done by using Pattern.matcher(). Return true if the string matches with the given regular expression, else return false. Below is the implementation of the above approach: Java // Java program to check if a string// contains only digitsimport java.util.regex.*;class GFG { // Function to validate URL // using regular expression public static boolean onlyDigits(String str) { // Regex to check string // contains only digits String regex = "[0-9]+"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code public static void main(String args[]) { // Given string str String str = "1234"; // Function Call System.out.println(onlyDigits(str)); }} true Time Complexity: O(N), where N is the length of the given string. Auxiliary Space: O(1) sinanitw Nikhil Arya 1 simmytarika5 Java-Character java-regular-expression Java-String-Programs number-digits regular-expression Java Programs Pattern Searching School Programming Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2022" }, { "code": null, "e": 203, "s": 52, "text": "Given string str, the task is to write a Java program to check whether a string contains only digits or not. If so, then print true, otherwise false. " }, { "code": null, "e": 214, "s": 203, "text": "Examples: " }, { "code": null, "e": 322, "s": 214, "text": "Input: str = “1234” Output: true Explanation: The given string contains only digits so that output is true." }, { "code": null, "e": 465, "s": 322, "text": "Input: str = “GeeksforGeeks2020” Output: false Explanation: The given string contains alphabet character and digits so that output is false. " }, { "code": null, "e": 744, "s": 465, "text": "The idea is to traverse each character in the string and check if the character of the string contains only digits from 0 to 9. If all the character of the string contains only digits then return true, otherwise, return false. Below is the implementation of the above approach: " }, { "code": null, "e": 749, "s": 744, "text": "Java" }, { "code": "// Java program for the above approach// contains only digitsclass GFG { // Function to check if a string // contains only digits public static boolean onlyDigits(String str, int n) { // Traverse the string from // start to end for (int i = 0; i < n; i++) { // Check if character is // not a digit between 0-9 // then return false if (str.charAt(i) < '0' || str.charAt(i) > '9') { return false; } } // If we reach here, that means // all characters were digits. return true; } // Driver Code public static void main(String args[]) { // Given string str String str = \"1a234\"; int len = str.length(); // Function Call System.out.println(onlyDigits(str, len)); }}", "e": 1617, "s": 749, "text": null }, { "code": null, "e": 1623, "s": 1617, "text": "false" }, { "code": null, "e": 1690, "s": 1623, "text": "Time Complexity: O(N), where N is the length of the given string. " }, { "code": null, "e": 1714, "s": 1690, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 1983, "s": 1714, "text": "The idea is to iterate over each character of the string and check whether the specified character is a digit or not using Character.isDigit(char ch). If the character is a digit then return true, else return false. Below is the implementation of the above approach: " }, { "code": null, "e": 1988, "s": 1983, "text": "Java" }, { "code": "// Java program to check if a string// contains only digitsclass GFG { // Function to check if a string // contains only digits public static boolean onlyDigits(String str, int n) { // Traverse the string from // start to end for (int i = 0; i < n; i++) { // Check if the sepecified // character is a not digit // then return false, // else return false if (!Character.isDigit(str.charAt(i))) { return false; } } // If we reach here that means all // the characters were digits, // so we return true return true; } // Driver Code public static void main(String args[]) { // Given string str String str = \"1234\"; int len = str.length(); // Function Call System.out.println(onlyDigits(str, len)); }}", "e": 2896, "s": 1988, "text": null }, { "code": null, "e": 2901, "s": 2896, "text": "true" }, { "code": null, "e": 2968, "s": 2901, "text": "Time Complexity: O(N), where N is the length of the given string. " }, { "code": null, "e": 2991, "s": 2968, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 3008, "s": 2991, "text": "Get the String. " }, { "code": null, "e": 3095, "s": 3008, "text": "Create a Regular Expression to check string contains only digits as mentioned below: " }, { "code": null, "e": 3113, "s": 3095, "text": "regex = \"[0-9]+\";" }, { "code": null, "e": 3215, "s": 3113, "text": "Match the given string with Regular Expression. In Java, this can be done by using Pattern.matcher()." }, { "code": null, "e": 3303, "s": 3215, "text": "Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 3354, "s": 3303, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3359, "s": 3354, "text": "Java" }, { "code": "// Java program to check if a string// contains only digitsimport java.util.regex.*;class GFG { // Function to validate URL // using regular expression public static boolean onlyDigits(String str) { // Regex to check string // contains only digits String regex = \"[0-9]+\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code public static void main(String args[]) { // Given string str String str = \"1234\"; // Function Call System.out.println(onlyDigits(str)); }}", "e": 4291, "s": 3359, "text": null }, { "code": null, "e": 4296, "s": 4291, "text": "true" }, { "code": null, "e": 4363, "s": 4296, "text": "Time Complexity: O(N), where N is the length of the given string. " }, { "code": null, "e": 4387, "s": 4363, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 4396, "s": 4387, "text": "sinanitw" }, { "code": null, "e": 4410, "s": 4396, "text": "Nikhil Arya 1" }, { "code": null, "e": 4423, "s": 4410, "text": "simmytarika5" }, { "code": null, "e": 4438, "s": 4423, "text": "Java-Character" }, { "code": null, "e": 4462, "s": 4438, "text": "java-regular-expression" }, { "code": null, "e": 4483, "s": 4462, "text": "Java-String-Programs" }, { "code": null, "e": 4497, "s": 4483, "text": "number-digits" }, { "code": null, "e": 4516, "s": 4497, "text": "regular-expression" }, { "code": null, "e": 4530, "s": 4516, "text": "Java Programs" }, { "code": null, "e": 4548, "s": 4530, "text": "Pattern Searching" }, { "code": null, "e": 4567, "s": 4548, "text": "School Programming" }, { "code": null, "e": 4575, "s": 4567, "text": "Strings" }, { "code": null, "e": 4583, "s": 4575, "text": "Strings" }, { "code": null, "e": 4601, "s": 4583, "text": "Pattern Searching" } ]
JavaTuples setValue() method
27 Aug, 2018 The setValue() method in org.javatuples is used to set the value in the LabelValueClassObject or KeyValueClassObject. This method can be used with only LabelValue class or KeyValue class of javatuples library. It returns another ClassObject with the value as the element passed as the parameter, and the key or label from the previous ClassObject. Method Declaration: public <X> LabelValue<A, X> setValue(X value) Syntax: LabelValue<A, B> LabelValueClassObject = LabelValue.setValue(X value) Return Value: This method returns another LabelValueClassObject with the value as the element passed as the parameter, and the label from the previous LabelValueClassObject. Below is the program that will illustrate the various ways to use setValue() method in LabelValue Class: Example: // Below is a Java program to set// Value in a LabelValue pair import java.util.*;import org.javatuples.LabelValue; class GfG { public static void main(String[] args) { // Creating a LabelValue object LabelValue<Integer, String> lv = LabelValue.with(Integer.valueOf(1), "A computer science portal"); // Using setValue() method LabelValue<Integer, Integer> lv1 = lv.setValue(Integer.valueOf(2)); // Printing the returned LabelValue System.out.println(lv1); }} Output: [1, 2] Method Declaration: public <X> KeyValue<A, X> setValue(X value) Syntax: KeyValue<A, B> KeyValueClassObject = KeyValue.setValue(X value) Return Value: This method returns another KeyValueClassObject with the value as the element passed as the parameter, and the key from the previous KeyValueClassObject. Below is the program that will illustrate the various ways to use setValue() method in KeyValue Class: Example: // Below is a Java program to set// Value in a KeyValue pair import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { // Creating a KeyValue object KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), "A computer science portal"); // Using setValue() method KeyValue<Integer, String> kv1 = kv.setValue("GeeksforGeeks"); // Printing the returned KeyValue System.out.println(kv1); }} Output: [1, GeeksforGeeks] Java-Functions JavaTuples Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Aug, 2018" }, { "code": null, "e": 376, "s": 28, "text": "The setValue() method in org.javatuples is used to set the value in the LabelValueClassObject or KeyValueClassObject. This method can be used with only LabelValue class or KeyValue class of javatuples library. It returns another ClassObject with the value as the element passed as the parameter, and the key or label from the previous ClassObject." }, { "code": null, "e": 396, "s": 376, "text": "Method Declaration:" }, { "code": null, "e": 442, "s": 396, "text": "public <X> LabelValue<A, X> setValue(X value)" }, { "code": null, "e": 450, "s": 442, "text": "Syntax:" }, { "code": null, "e": 520, "s": 450, "text": "LabelValue<A, B> LabelValueClassObject = LabelValue.setValue(X value)" }, { "code": null, "e": 694, "s": 520, "text": "Return Value: This method returns another LabelValueClassObject with the value as the element passed as the parameter, and the label from the previous LabelValueClassObject." }, { "code": null, "e": 799, "s": 694, "text": "Below is the program that will illustrate the various ways to use setValue() method in LabelValue Class:" }, { "code": null, "e": 808, "s": 799, "text": "Example:" }, { "code": "// Below is a Java program to set// Value in a LabelValue pair import java.util.*;import org.javatuples.LabelValue; class GfG { public static void main(String[] args) { // Creating a LabelValue object LabelValue<Integer, String> lv = LabelValue.with(Integer.valueOf(1), \"A computer science portal\"); // Using setValue() method LabelValue<Integer, Integer> lv1 = lv.setValue(Integer.valueOf(2)); // Printing the returned LabelValue System.out.println(lv1); }}", "e": 1364, "s": 808, "text": null }, { "code": null, "e": 1372, "s": 1364, "text": "Output:" }, { "code": null, "e": 1380, "s": 1372, "text": "[1, 2]\n" }, { "code": null, "e": 1400, "s": 1380, "text": "Method Declaration:" }, { "code": null, "e": 1444, "s": 1400, "text": "public <X> KeyValue<A, X> setValue(X value)" }, { "code": null, "e": 1452, "s": 1444, "text": "Syntax:" }, { "code": null, "e": 1516, "s": 1452, "text": "KeyValue<A, B> KeyValueClassObject = KeyValue.setValue(X value)" }, { "code": null, "e": 1684, "s": 1516, "text": "Return Value: This method returns another KeyValueClassObject with the value as the element passed as the parameter, and the key from the previous KeyValueClassObject." }, { "code": null, "e": 1787, "s": 1684, "text": "Below is the program that will illustrate the various ways to use setValue() method in KeyValue Class:" }, { "code": null, "e": 1796, "s": 1787, "text": "Example:" }, { "code": "// Below is a Java program to set// Value in a KeyValue pair import java.util.*;import org.javatuples.KeyValue; class GfG { public static void main(String[] args) { // Creating a KeyValue object KeyValue<Integer, String> kv = KeyValue.with(Integer.valueOf(1), \"A computer science portal\"); // Using setValue() method KeyValue<Integer, String> kv1 = kv.setValue(\"GeeksforGeeks\"); // Printing the returned KeyValue System.out.println(kv1); }}", "e": 2332, "s": 1796, "text": null }, { "code": null, "e": 2340, "s": 2332, "text": "Output:" }, { "code": null, "e": 2360, "s": 2340, "text": "[1, GeeksforGeeks]\n" }, { "code": null, "e": 2375, "s": 2360, "text": "Java-Functions" }, { "code": null, "e": 2386, "s": 2375, "text": "JavaTuples" }, { "code": null, "e": 2391, "s": 2386, "text": "Java" }, { "code": null, "e": 2396, "s": 2391, "text": "Java" } ]
Program to Subtract two 8 Bit numbers in 8051 Microprocessor
Now, in this section we will see how to subtract two 8-bit numbers using 8051 microcontroller. The register A (Accumulator) is used as one operand in the operations. There are seven registers R0 – R7 in different register banks. We can use any of them as second operand. We are taking two number 73H and BDH at location 20H and 21H, After subtracting the result will be stored at location 30H and 31H. MOV R0, #20H ; set source address 20H to R0 MOV R1, #30H ; set destination address 30H to R1 MOV A, @R0 ; take the value from source to register A MOV R5, A ; Move the value from A to R5 MOV R4, #00H ; Clear register R4 to store borrow INC R0 ; Point to the next location MOV A, @R0 ; take the value from source to register A MOV R3, A ; store second byte MOV A, R5 ;get back the first operand SUBB A, R3 ; Subtract R3 from A JNC SAVE INC R4 ; Increment R4 to get borrow MOV B, R4 ; Get borrow to register B MOV @R1, B ; Store the borrow first INC R1 ; Increase R1 to point to the next address SAVE: MOV @R1, A ; Store the result HALT: SJMP HALT ; Stop the program So by subtracting 73H – BDH, the result will be B6H. At location 30H, we will get 01H. This indicates that the result is negative. The get the actual value from result B6H, we have to perform 2’s complement operation. After performing 2’s Complement, the result will be -4AH.
[ { "code": null, "e": 1333, "s": 1062, "text": "Now, in this section we will see how to subtract two 8-bit numbers using 8051 microcontroller. The register A (Accumulator) is used as one operand in the operations. There are seven registers R0 – R7 in different register banks. We can use any of them as second operand." }, { "code": null, "e": 1464, "s": 1333, "text": "We are taking two number 73H and BDH at location 20H and 21H, After subtracting the result will be stored at location 30H and 31H." }, { "code": null, "e": 2219, "s": 1464, "text": " MOV R0, #20H ; set source address 20H to R0\n MOV R1, #30H ; set destination address 30H to R1\n MOV A, @R0 ; take the value from source to register A\n MOV R5, A ; Move the value from A to R5\n MOV R4, #00H ; Clear register R4 to store borrow\n INC R0 ; Point to the next location\n MOV A, @R0 ; take the value from source to register A\n MOV R3, A ; store second byte\n MOV A, R5 ;get back the first operand\n SUBB A, R3 ; Subtract R3 from A\n JNC SAVE\n INC R4 ; Increment R4 to get borrow\n MOV B, R4 ; Get borrow to register B\n MOV @R1, B ; Store the borrow first\n INC R1 ; Increase R1 to point to the next address\nSAVE: MOV @R1, A ; Store the result\nHALT: SJMP HALT ; Stop the program" }, { "code": null, "e": 2495, "s": 2219, "text": "So by subtracting 73H – BDH, the result will be B6H. At location 30H, we will get 01H. This indicates that the result is negative. The get the actual value from result B6H, we have to perform 2’s complement operation. After performing 2’s Complement, the result will be -4AH." } ]
Python program maximum of three.
Given three number a b and c, our task is that we have to find the maximum element in among in given number. Input: a = 2, b = 4, c = 3 Output: 4 Step 1: input three user input number. Step2: Add three numbers to list. Step 3: Using max() function to find the greatest number max(lst). Step 4: And finally we will print maximum number. def maximum(a, b, c): list = [a, b, c] return max(list) # Driven code x = int(input("Enter First number")) y = int(input("Enter Second number")) z = int(input("Enter Third number")) print("Maximum Number is ::>",maximum(x, y, z)) Enter First number 56 Enter Second number 90 Enter Third number 67 Maximum Number Is ::> 90
[ { "code": null, "e": 1171, "s": 1062, "text": "Given three number a b and c, our task is that we have to find the maximum element in among in given number." }, { "code": null, "e": 1210, "s": 1171, "text": "Input: a = 2, b = 4, c = 3\nOutput: 4 \n" }, { "code": null, "e": 1402, "s": 1210, "text": "Step 1: input three user input number.\nStep2: Add three numbers to list.\nStep 3: Using max() function to find the greatest number max(lst).\nStep 4: And finally we will print maximum number.\n" }, { "code": null, "e": 1644, "s": 1402, "text": "def maximum(a, b, c): \n list = [a, b, c] \n return max(list) \n# Driven code \nx = int(input(\"Enter First number\"))\ny = int(input(\"Enter Second number\"))\nz = int(input(\"Enter Third number\"))\nprint(\"Maximum Number is ::>\",maximum(x, y, z)) " }, { "code": null, "e": 1737, "s": 1644, "text": "Enter First number 56\nEnter Second number 90\nEnter Third number 67\nMaximum Number Is ::> 90\n" } ]