title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Forward Iterators in C++
25 Apr, 2019 After going through the template definition of various STL algorithms like std::search, std::search_n, std::lower_bound, you must have found their template definition consisting of objects of type Forward Iterator. So what are they and why are they used ? Forward iterators are one of the five main types of iterators present in C++ Standard Library, others being Input iterators, Output iterator, Bidirectional iterator and Random – access iterators. Forward iterators are considered to be the combination of input as well as output iterators. It provides support to the functionality of both of them. It permits values to be both accessed and modified. One important thing to be kept in mind is that bidirectional and random-access iterators are also valid forward iterators, as shown in the iterator hierarchy above. Salient Features Usability: Performing operations on a forward iterator that is dereferenceable never makes its iterator value non-dereferenceable, as a result this enables algorithms that use this category of iterators to use multiple copies of an iterator to pass more than once by the same iterator values. So, it can be used in multi-pass algorithms.Equality / Inequality Comparison: A forward iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are forward iterators:A == B // Checking for equality A != B // Checking for inequality Dereferencing: Because an input iterator can be dereferenced, using the operator * and -> as an rvalue and an output iterator can be dereferenced as an lvalue, so forward iterators can be used for both the purposes.// C++ program to demonstrate forward iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << " "; } return 0;}Output:1 1 1 1 1 So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is at least a forward iterator( it can be higher in hierarchy also).Incrementable: A forward iterator can be incremented, so that it refers to the next element in sequence, using operator ++().Note: The fact that we can use forward iterators with increment operator doesn’t mean that operator – -() can also be used with them. Remember, that forward iterators are unidirectional and can only move in the forward direction.So, the following two expressions are valid if A is a forward iterator:A++ // Using post increment operator ++A // Using pre increment operator Swappable: The value pointed to by these iterators can be exchanged or swapped. Usability: Performing operations on a forward iterator that is dereferenceable never makes its iterator value non-dereferenceable, as a result this enables algorithms that use this category of iterators to use multiple copies of an iterator to pass more than once by the same iterator values. So, it can be used in multi-pass algorithms. Equality / Inequality Comparison: A forward iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are forward iterators:A == B // Checking for equality A != B // Checking for inequality So, the following two expressions are valid if A and B are forward iterators: A == B // Checking for equality A != B // Checking for inequality Dereferencing: Because an input iterator can be dereferenced, using the operator * and -> as an rvalue and an output iterator can be dereferenced as an lvalue, so forward iterators can be used for both the purposes.// C++ program to demonstrate forward iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << " "; } return 0;}Output:1 1 1 1 1 So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is at least a forward iterator( it can be higher in hierarchy also). // C++ program to demonstrate forward iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << " "; } return 0;} Output: 1 1 1 1 1 So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is at least a forward iterator( it can be higher in hierarchy also). Incrementable: A forward iterator can be incremented, so that it refers to the next element in sequence, using operator ++().Note: The fact that we can use forward iterators with increment operator doesn’t mean that operator – -() can also be used with them. Remember, that forward iterators are unidirectional and can only move in the forward direction.So, the following two expressions are valid if A is a forward iterator:A++ // Using post increment operator ++A // Using pre increment operator Note: The fact that we can use forward iterators with increment operator doesn’t mean that operator – -() can also be used with them. Remember, that forward iterators are unidirectional and can only move in the forward direction. So, the following two expressions are valid if A is a forward iterator: A++ // Using post increment operator ++A // Using pre increment operator Swappable: The value pointed to by these iterators can be exchanged or swapped. Practical implementation After understanding its features, it is very important to learn about its practical implementation as well. As told earlier, forward iterators can be used both when we want to access elements and also when we have to assign elements to them, as it is the combination of both input and output iterator. The following two STL algorithms can show this fact: std::replace: As we know this algorithm is used to replace all the elements in the range which are equal to a particular value by a new value. So, let us look at its internal working (Don’t go into detail just look where forward iterators can be used and where they cannot be):// Definition of std::replace()template void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value){ while (first != last) { if (*first == old_value) // L1 *first = new_value; // L2 ++first; }}Here, we can see that we have made use of forward iterators, as we need to make use of the feature of both input as well as output iterators. In L1, we are required to dereference the iterator first as a rvalue (input iterator) and in L2, we are required to dereference first as a lvalue (output iterator), so to accomplish both the tasks, we have made use of forward iterators. // Definition of std::replace()template void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value){ while (first != last) { if (*first == old_value) // L1 *first = new_value; // L2 ++first; }} Here, we can see that we have made use of forward iterators, as we need to make use of the feature of both input as well as output iterators. In L1, we are required to dereference the iterator first as a rvalue (input iterator) and in L2, we are required to dereference first as a lvalue (output iterator), so to accomplish both the tasks, we have made use of forward iterators. std::reverse_copy: As the name suggests, this algorithm is used to copy a range into another range, but in reverse order. Now, as far as accessing elements and assigning elements are concerned, forward iterators are fine, but as soon as we have to decrement the iterator, then we cannot use these forward iterators for this purpose.// Definition of std::reverse_copy()template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result){ while (first != last) *result++ = *--last; return result;}Here, we can see that we have declared last as a bidirectional iterator, and not a forward iterator since we cannot decrement a forward iterator as done in case of last, so we cannot use it in this scenario. // Definition of std::reverse_copy()template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result){ while (first != last) *result++ = *--last; return result;} Here, we can see that we have declared last as a bidirectional iterator, and not a forward iterator since we cannot decrement a forward iterator as done in case of last, so we cannot use it in this scenario. Note: As we know that forward iterators are the combination of both input and output iterators, so if any algorithm involves the use of any of these two iterators, then we can use forward iterators in their place as well, without affecting the program. So, the two above examples very well show when, where, why and how forward iterators are used practically. Limitations After studying the salient features, one must also know its deficiencies as well although there are not as many as there are in input or output iterators as it is higher in the hierarchy. Can not be decremented: Just like we can use operator ++() with forward iterators for incrementing them, we cannot decrement them. Although it is higher in the hierarchy than input and output iterators, still it can’t overcome this deficiency.That is why, its name is forward, which shows that it can move only in forward direction.If A is a forward iterator, then A-- // Not allowed with forward iterators Relational Operators: Although, forward iterators can be used with equality operator (==), it can not be used with other relational operators like =.If A and B are forward iterators, then A == B // Allowed A <= B // Not Allowed Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that forward operators can only move in one direction that too forward and that too sequentially.If A and B are forward iterators, then A + 1 // Not allowed B - 2 // Not allowed Use of offset dereference operator ([ ]): Forward iterators do not support offset dereference operator ([ ]), which is used for random-access.If A is a forward iterator, then A[3] // Not allowed Can not be decremented: Just like we can use operator ++() with forward iterators for incrementing them, we cannot decrement them. Although it is higher in the hierarchy than input and output iterators, still it can’t overcome this deficiency.That is why, its name is forward, which shows that it can move only in forward direction.If A is a forward iterator, then A-- // Not allowed with forward iterators That is why, its name is forward, which shows that it can move only in forward direction. If A is a forward iterator, then A-- // Not allowed with forward iterators Relational Operators: Although, forward iterators can be used with equality operator (==), it can not be used with other relational operators like =.If A and B are forward iterators, then A == B // Allowed A <= B // Not Allowed If A and B are forward iterators, then A == B // Allowed A <= B // Not Allowed Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that forward operators can only move in one direction that too forward and that too sequentially.If A and B are forward iterators, then A + 1 // Not allowed B - 2 // Not allowed If A and B are forward iterators, then A + 1 // Not allowed B - 2 // Not allowed Use of offset dereference operator ([ ]): Forward iterators do not support offset dereference operator ([ ]), which is used for random-access.If A is a forward iterator, then A[3] // Not allowed If A is a forward iterator, then A[3] // Not allowed This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai cpp-iterator STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Apr, 2019" }, { "code": null, "e": 310, "s": 54, "text": "After going through the template definition of various STL algorithms like std::search, std::search_n, std::lower_bound, you must have found their template definition consisting of objects of type Forward Iterator. So what are they and why are they used ?" }, { "code": null, "e": 506, "s": 310, "text": "Forward iterators are one of the five main types of iterators present in C++ Standard Library, others being Input iterators, Output iterator, Bidirectional iterator and Random – access iterators." }, { "code": null, "e": 709, "s": 506, "text": "Forward iterators are considered to be the combination of input as well as output iterators. It provides support to the functionality of both of them. It permits values to be both accessed and modified." }, { "code": null, "e": 874, "s": 709, "text": "One important thing to be kept in mind is that bidirectional and random-access iterators are also valid forward iterators, as shown in the iterator hierarchy above." }, { "code": null, "e": 891, "s": 874, "text": "Salient Features" }, { "code": null, "e": 3103, "s": 891, "text": "Usability: Performing operations on a forward iterator that is dereferenceable never makes its iterator value non-dereferenceable, as a result this enables algorithms that use this category of iterators to use multiple copies of an iterator to pass more than once by the same iterator values. So, it can be used in multi-pass algorithms.Equality / Inequality Comparison: A forward iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are forward iterators:A == B // Checking for equality\nA != B // Checking for inequality\nDereferencing: Because an input iterator can be dereferenced, using the operator * and -> as an rvalue and an output iterator can be dereferenced as an lvalue, so forward iterators can be used for both the purposes.// C++ program to demonstrate forward iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << \" \"; } return 0;}Output:1 1 1 1 1\nSo, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is at least a forward iterator( it can be higher in hierarchy also).Incrementable: A forward iterator can be incremented, so that it refers to the next element in sequence, using operator ++().Note: The fact that we can use forward iterators with increment operator doesn’t mean that operator – -() can also be used with them. Remember, that forward iterators are unidirectional and can only move in the forward direction.So, the following two expressions are valid if A is a forward iterator:A++ // Using post increment operator\n++A // Using pre increment operator\nSwappable: The value pointed to by these iterators can be exchanged or swapped." }, { "code": null, "e": 3441, "s": 3103, "text": "Usability: Performing operations on a forward iterator that is dereferenceable never makes its iterator value non-dereferenceable, as a result this enables algorithms that use this category of iterators to use multiple copies of an iterator to pass more than once by the same iterator values. So, it can be used in multi-pass algorithms." }, { "code": null, "e": 3825, "s": 3441, "text": "Equality / Inequality Comparison: A forward iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are forward iterators:A == B // Checking for equality\nA != B // Checking for inequality\n" }, { "code": null, "e": 3903, "s": 3825, "text": "So, the following two expressions are valid if A and B are forward iterators:" }, { "code": null, "e": 3972, "s": 3903, "text": "A == B // Checking for equality\nA != B // Checking for inequality\n" }, { "code": null, "e": 4883, "s": 3972, "text": "Dereferencing: Because an input iterator can be dereferenced, using the operator * and -> as an rvalue and an output iterator can be dereferenced as an lvalue, so forward iterators can be used for both the purposes.// C++ program to demonstrate forward iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << \" \"; } return 0;}Output:1 1 1 1 1\nSo, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is at least a forward iterator( it can be higher in hierarchy also)." }, { "code": "// C++ program to demonstrate forward iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << \" \"; } return 0;}", "e": 5388, "s": 4883, "text": null }, { "code": null, "e": 5396, "s": 5388, "text": "Output:" }, { "code": null, "e": 5407, "s": 5396, "text": "1 1 1 1 1\n" }, { "code": null, "e": 5582, "s": 5407, "text": "So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is at least a forward iterator( it can be higher in hierarchy also)." }, { "code": null, "e": 6085, "s": 5582, "text": "Incrementable: A forward iterator can be incremented, so that it refers to the next element in sequence, using operator ++().Note: The fact that we can use forward iterators with increment operator doesn’t mean that operator – -() can also be used with them. Remember, that forward iterators are unidirectional and can only move in the forward direction.So, the following two expressions are valid if A is a forward iterator:A++ // Using post increment operator\n++A // Using pre increment operator\n" }, { "code": null, "e": 6315, "s": 6085, "text": "Note: The fact that we can use forward iterators with increment operator doesn’t mean that operator – -() can also be used with them. Remember, that forward iterators are unidirectional and can only move in the forward direction." }, { "code": null, "e": 6387, "s": 6315, "text": "So, the following two expressions are valid if A is a forward iterator:" }, { "code": null, "e": 6465, "s": 6387, "text": "A++ // Using post increment operator\n++A // Using pre increment operator\n" }, { "code": null, "e": 6545, "s": 6465, "text": "Swappable: The value pointed to by these iterators can be exchanged or swapped." }, { "code": null, "e": 6570, "s": 6545, "text": "Practical implementation" }, { "code": null, "e": 6925, "s": 6570, "text": "After understanding its features, it is very important to learn about its practical implementation as well. As told earlier, forward iterators can be used both when we want to access elements and also when we have to assign elements to them, as it is the combination of both input and output iterator. The following two STL algorithms can show this fact:" }, { "code": null, "e": 7864, "s": 6925, "text": "std::replace: As we know this algorithm is used to replace all the elements in the range which are equal to a particular value by a new value. So, let us look at its internal working (Don’t go into detail just look where forward iterators can be used and where they cannot be):// Definition of std::replace()template void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value){ while (first != last) { if (*first == old_value) // L1 *first = new_value; // L2 ++first; }}Here, we can see that we have made use of forward iterators, as we need to make use of the feature of both input as well as output iterators. In L1, we are required to dereference the iterator first as a rvalue (input iterator) and in L2, we are required to dereference first as a lvalue (output iterator), so to accomplish both the tasks, we have made use of forward iterators." }, { "code": "// Definition of std::replace()template void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value){ while (first != last) { if (*first == old_value) // L1 *first = new_value; // L2 ++first; }}", "e": 8148, "s": 7864, "text": null }, { "code": null, "e": 8527, "s": 8148, "text": "Here, we can see that we have made use of forward iterators, as we need to make use of the feature of both input as well as output iterators. In L1, we are required to dereference the iterator first as a rvalue (input iterator) and in L2, we are required to dereference first as a lvalue (output iterator), so to accomplish both the tasks, we have made use of forward iterators." }, { "code": null, "e": 9364, "s": 8527, "text": "std::reverse_copy: As the name suggests, this algorithm is used to copy a range into another range, but in reverse order. Now, as far as accessing elements and assigning elements are concerned, forward iterators are fine, but as soon as we have to decrement the iterator, then we cannot use these forward iterators for this purpose.// Definition of std::reverse_copy()template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result){ while (first != last) *result++ = *--last; return result;}Here, we can see that we have declared last as a bidirectional iterator, and not a forward iterator since we cannot decrement a forward iterator as done in case of last, so we cannot use it in this scenario." }, { "code": "// Definition of std::reverse_copy()template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result){ while (first != last) *result++ = *--last; return result;}", "e": 9662, "s": 9364, "text": null }, { "code": null, "e": 9870, "s": 9662, "text": "Here, we can see that we have declared last as a bidirectional iterator, and not a forward iterator since we cannot decrement a forward iterator as done in case of last, so we cannot use it in this scenario." }, { "code": null, "e": 10123, "s": 9870, "text": "Note: As we know that forward iterators are the combination of both input and output iterators, so if any algorithm involves the use of any of these two iterators, then we can use forward iterators in their place as well, without affecting the program." }, { "code": null, "e": 10230, "s": 10123, "text": "So, the two above examples very well show when, where, why and how forward iterators are used practically." }, { "code": null, "e": 10242, "s": 10230, "text": "Limitations" }, { "code": null, "e": 10430, "s": 10242, "text": "After studying the salient features, one must also know its deficiencies as well although there are not as many as there are in input or output iterators as it is higher in the hierarchy." }, { "code": null, "e": 11602, "s": 10430, "text": "Can not be decremented: Just like we can use operator ++() with forward iterators for incrementing them, we cannot decrement them. Although it is higher in the hierarchy than input and output iterators, still it can’t overcome this deficiency.That is why, its name is forward, which shows that it can move only in forward direction.If A is a forward iterator, then\n\nA-- // Not allowed with forward iterators\nRelational Operators: Although, forward iterators can be used with equality operator (==), it can not be used with other relational operators like =.If A and B are forward iterators, then\n\nA == B // Allowed\nA <= B // Not Allowed\nArithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that forward operators can only move in one direction that too forward and that too sequentially.If A and B are forward iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\nUse of offset dereference operator ([ ]): Forward iterators do not support offset dereference operator ([ ]), which is used for random-access.If A is a forward iterator, then\nA[3] // Not allowed \n" }, { "code": null, "e": 12014, "s": 11602, "text": "Can not be decremented: Just like we can use operator ++() with forward iterators for incrementing them, we cannot decrement them. Although it is higher in the hierarchy than input and output iterators, still it can’t overcome this deficiency.That is why, its name is forward, which shows that it can move only in forward direction.If A is a forward iterator, then\n\nA-- // Not allowed with forward iterators\n" }, { "code": null, "e": 12104, "s": 12014, "text": "That is why, its name is forward, which shows that it can move only in forward direction." }, { "code": null, "e": 12184, "s": 12104, "text": "If A is a forward iterator, then\n\nA-- // Not allowed with forward iterators\n" }, { "code": null, "e": 12422, "s": 12184, "text": "Relational Operators: Although, forward iterators can be used with equality operator (==), it can not be used with other relational operators like =.If A and B are forward iterators, then\n\nA == B // Allowed\nA <= B // Not Allowed\n" }, { "code": null, "e": 12511, "s": 12422, "text": "If A and B are forward iterators, then\n\nA == B // Allowed\nA <= B // Not Allowed\n" }, { "code": null, "e": 12836, "s": 12511, "text": "Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that forward operators can only move in one direction that too forward and that too sequentially.If A and B are forward iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\n" }, { "code": null, "e": 12927, "s": 12836, "text": "If A and B are forward iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\n" }, { "code": null, "e": 13127, "s": 12927, "text": "Use of offset dereference operator ([ ]): Forward iterators do not support offset dereference operator ([ ]), which is used for random-access.If A is a forward iterator, then\nA[3] // Not allowed \n" }, { "code": null, "e": 13185, "s": 13127, "text": "If A is a forward iterator, then\nA[3] // Not allowed \n" }, { "code": null, "e": 13488, "s": 13185, "text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 13613, "s": 13488, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 13626, "s": 13613, "text": "Akanksha_Rai" }, { "code": null, "e": 13639, "s": 13626, "text": "cpp-iterator" }, { "code": null, "e": 13643, "s": 13639, "text": "STL" }, { "code": null, "e": 13647, "s": 13643, "text": "C++" }, { "code": null, "e": 13651, "s": 13647, "text": "STL" }, { "code": null, "e": 13655, "s": 13651, "text": "CPP" } ]
How to update NPM ?
31 May, 2020 NPM (Node Package Manager) is the default package manager for Node.js and is written entirely in JavaScript. It manages all the packages and modules for Node.js and consists of command-line client npm. It gets installed into the system with the installation of Node.js. The required packages and modules in the Node project are installed using NPM. The update of the NPM means the update node package manager to the latest version. The update of NPM updates the Node.js and modules to the latest version. Syntax: npm update [-g] [<pkg>...] Here, -g refers to global and pkg refers to package. Method 1: Using npm update command to update the node package manager. npm update -g Method 2: Using npm@latest command to update the node package manager. npm install npm@latest -g Method 3: Using PPA repository (only for Linux). sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs npm Method 4: Using cache cleaning & stable installing (only for Linux). sudo npm cache clean -f sudo npm install -g n sudo n stable Method 5: Using npm@next to update the node package manager. npm install -g npm@next Node.js-Misc Picked Node.js 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": "\n31 May, 2020" }, { "code": null, "e": 403, "s": 54, "text": "NPM (Node Package Manager) is the default package manager for Node.js and is written entirely in JavaScript. It manages all the packages and modules for Node.js and consists of command-line client npm. It gets installed into the system with the installation of Node.js. The required packages and modules in the Node project are installed using NPM." }, { "code": null, "e": 559, "s": 403, "text": "The update of the NPM means the update node package manager to the latest version. The update of NPM updates the Node.js and modules to the latest version." }, { "code": null, "e": 567, "s": 559, "text": "Syntax:" }, { "code": null, "e": 594, "s": 567, "text": "npm update [-g] [<pkg>...]" }, { "code": null, "e": 647, "s": 594, "text": "Here, -g refers to global and pkg refers to package." }, { "code": null, "e": 718, "s": 647, "text": "Method 1: Using npm update command to update the node package manager." }, { "code": null, "e": 732, "s": 718, "text": "npm update -g" }, { "code": null, "e": 803, "s": 732, "text": "Method 2: Using npm@latest command to update the node package manager." }, { "code": null, "e": 829, "s": 803, "text": "npm install npm@latest -g" }, { "code": null, "e": 878, "s": 829, "text": "Method 3: Using PPA repository (only for Linux)." }, { "code": null, "e": 976, "s": 878, "text": "sudo add-apt-repository ppa:chris-lea/node.js\nsudo apt-get update\nsudo apt-get install nodejs npm" }, { "code": null, "e": 1045, "s": 976, "text": "Method 4: Using cache cleaning & stable installing (only for Linux)." }, { "code": null, "e": 1105, "s": 1045, "text": "sudo npm cache clean -f\nsudo npm install -g n\nsudo n stable" }, { "code": null, "e": 1166, "s": 1105, "text": "Method 5: Using npm@next to update the node package manager." }, { "code": null, "e": 1190, "s": 1166, "text": "npm install -g npm@next" }, { "code": null, "e": 1203, "s": 1190, "text": "Node.js-Misc" }, { "code": null, "e": 1210, "s": 1203, "text": "Picked" }, { "code": null, "e": 1218, "s": 1210, "text": "Node.js" }, { "code": null, "e": 1235, "s": 1218, "text": "Web Technologies" } ]
C# | Encapsulation
23 Jan, 2019 Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield. Technically in encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of own class in which they are declared. As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding. Encapsulation can be achieved by: Declaring all the variables in the class as private and using C# Properties in the class to set and get the values of variables. Example: // C# program to illustrate encapsulationusing System; public class DemoEncap { // private variables declared // these can only be accessed by // public methods of class private String studentName; private int studentAge; // using accessors to get and // set the value of studentName public String Name { get { return studentName; } set { studentName = value; } } // using accessors to get and // set the value of studentAge public int Age { get { return studentAge; } set { studentAge = value; } } } // Driver Classclass GFG { // Main Method static public void Main() { // creating object DemoEncap obj = new DemoEncap(); // calls set accessor of the property Name, // and pass "Ankita" as value of the // standard field 'value' obj.Name = "Ankita"; // calls set accessor of the property Age, // and pass "21" as value of the // standard field 'value' obj.Age = 21; // Displaying values of the variables Console.WriteLine("Name: " + obj.Name); Console.WriteLine("Age: " + obj.Age); }} Output: Name: Ankita Age: 21 Explanation: In the above program the class DemoEncap is encapsulated as the variables are declared as private. To access these private variables we are using the Name and Age accessors which contains the get and set method to retrieve and set the values of private fields. Accessors are defined as public so that they can access in other class. Advantages of Encapsulation: Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is stored values in the variables. He only knows that we are passing the values to accessors and variables are getting initialized to that value. Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to only use Get Accessor in the code. If we wish to make the variables as write-only then we have to only use Set Accessor. Reusability: Encapsulation also improves the re-usability and easy to change with new requirements. Testing code is easy: Encapsulated code is easy to test for unit testing. CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jan, 2019" }, { "code": null, "e": 332, "s": 52, "text": "Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield." }, { "code": null, "e": 521, "s": 332, "text": "Technically in encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of own class in which they are declared." }, { "code": null, "e": 628, "s": 521, "text": "As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding." }, { "code": null, "e": 791, "s": 628, "text": "Encapsulation can be achieved by: Declaring all the variables in the class as private and using C# Properties in the class to set and get the values of variables." }, { "code": null, "e": 800, "s": 791, "text": "Example:" }, { "code": "// C# program to illustrate encapsulationusing System; public class DemoEncap { // private variables declared // these can only be accessed by // public methods of class private String studentName; private int studentAge; // using accessors to get and // set the value of studentName public String Name { get { return studentName; } set { studentName = value; } } // using accessors to get and // set the value of studentAge public int Age { get { return studentAge; } set { studentAge = value; } } } // Driver Classclass GFG { // Main Method static public void Main() { // creating object DemoEncap obj = new DemoEncap(); // calls set accessor of the property Name, // and pass \"Ankita\" as value of the // standard field 'value' obj.Name = \"Ankita\"; // calls set accessor of the property Age, // and pass \"21\" as value of the // standard field 'value' obj.Age = 21; // Displaying values of the variables Console.WriteLine(\"Name: \" + obj.Name); Console.WriteLine(\"Age: \" + obj.Age); }}", "e": 2196, "s": 800, "text": null }, { "code": null, "e": 2204, "s": 2196, "text": "Output:" }, { "code": null, "e": 2226, "s": 2204, "text": "Name: Ankita\nAge: 21\n" }, { "code": null, "e": 2572, "s": 2226, "text": "Explanation: In the above program the class DemoEncap is encapsulated as the variables are declared as private. To access these private variables we are using the Name and Age accessors which contains the get and set method to retrieve and set the values of private fields. Accessors are defined as public so that they can access in other class." }, { "code": null, "e": 2601, "s": 2572, "text": "Advantages of Encapsulation:" }, { "code": null, "e": 2886, "s": 2601, "text": "Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is stored values in the variables. He only knows that we are passing the values to accessors and variables are getting initialized to that value." }, { "code": null, "e": 3188, "s": 2886, "text": "Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to only use Get Accessor in the code. If we wish to make the variables as write-only then we have to only use Set Accessor." }, { "code": null, "e": 3288, "s": 3188, "text": "Reusability: Encapsulation also improves the re-usability and easy to change with new requirements." }, { "code": null, "e": 3362, "s": 3288, "text": "Testing code is easy: Encapsulated code is easy to test for unit testing." }, { "code": null, "e": 3373, "s": 3362, "text": "CSharp-OOP" }, { "code": null, "e": 3376, "s": 3373, "text": "C#" } ]
Python PIL | Image.show() method
04 Mar, 2022 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.Image.show() Displays this image. This method is mainly intended for debugging purposes. On Unix platforms, this method saves the image to a temporary PPM file, and calls the xv utility. On Windows, it saves the image to a temporary BMP file, and uses the standard BMP display utility to show it (usually Paint). Syntax: Image.show(title=None, command=None) Parameters: title – Optional title to use for the image window, where possible.command – command used to show the image Return Type = The assigned path image will open. Image Used: Python3 # importing Image class from PIL packagefrom PIL import Image # creating a objectim = Image.open(r"C:\Users\System-Pc\Desktop\home.png") im.show() Output: Another example: opening image with show()using .jpg extension . Image Used: Python3 # importing Image class from PIL packagefrom PIL import Image # creating a objectim = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg") im.show() Output: surinderdawra388 spi3lot Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Mar, 2022" }, { "code": null, "e": 668, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.Image.show() Displays this image. This method is mainly intended for debugging purposes. On Unix platforms, this method saves the image to a temporary PPM file, and calls the xv utility. On Windows, it saves the image to a temporary BMP file, and uses the standard BMP display utility to show it (usually Paint). " }, { "code": null, "e": 884, "s": 668, "text": "Syntax: Image.show(title=None, command=None) Parameters: title – Optional title to use for the image window, where possible.command – command used to show the image Return Type = The assigned path image will open. " }, { "code": null, "e": 898, "s": 884, "text": "Image Used: " }, { "code": null, "e": 908, "s": 900, "text": "Python3" }, { "code": "# importing Image class from PIL packagefrom PIL import Image # creating a objectim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\home.png\") im.show()", "e": 1055, "s": 908, "text": null }, { "code": null, "e": 1065, "s": 1055, "text": "Output: " }, { "code": null, "e": 1144, "s": 1065, "text": "Another example: opening image with show()using .jpg extension . Image Used: " }, { "code": null, "e": 1154, "s": 1146, "text": "Python3" }, { "code": "# importing Image class from PIL packagefrom PIL import Image # creating a objectim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\tree.jpg\") im.show()", "e": 1301, "s": 1154, "text": null }, { "code": null, "e": 1311, "s": 1301, "text": "Output: " }, { "code": null, "e": 1330, "s": 1313, "text": "surinderdawra388" }, { "code": null, "e": 1338, "s": 1330, "text": "spi3lot" }, { "code": null, "e": 1349, "s": 1338, "text": "Python-pil" }, { "code": null, "e": 1356, "s": 1349, "text": "Python" } ]
Python – Kolmogorov-Smirnov Distribution in Statistics
10 Jan, 2020 scipy.stats.kstwobign() is Kolmogorov-Smirnov two-sided test for large N test that is defined with a standard format and some shape parameters to complete its specification. It is a statistical test that measures the maximum absolute distance of the theoretical CDF from the empirical CDF. Parameters : q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates. Results : kstwobign continuous random variable Code #1 : Creating kstwobign continuous random variable # importing library from scipy.stats import kstwobign numargs = kstwobign.numargs a, b = 4.32, 3.18rv = kstwobign(a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D54959C8 Code #2 : kstwobign continuous variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = kstwobign.rvs(a, b, scale = 2, size = 10) print ("Random Variates : \n", R) Output : Random Variates : [3.88510141 3.48394857 3.66124797 3.88484201 3.86533511 3.21176073 4.10238585 3.42397866 3.85111721 4.36433596] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) Output : Distribution : [0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633 1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714 2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102 2.93877551 3. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = kstwobign .pdf(x, 1, 3) y2 = kstwobign .pdf(x, 1, 4) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2020" }, { "code": null, "e": 318, "s": 28, "text": "scipy.stats.kstwobign() is Kolmogorov-Smirnov two-sided test for large N test that is defined with a standard format and some shape parameters to complete its specification. It is a statistical test that measures the maximum absolute distance of the theoretical CDF from the empirical CDF." }, { "code": null, "e": 331, "s": 318, "text": "Parameters :" }, { "code": null, "e": 532, "s": 331, "text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates." }, { "code": null, "e": 579, "s": 532, "text": "Results : kstwobign continuous random variable" }, { "code": null, "e": 635, "s": 579, "text": "Code #1 : Creating kstwobign continuous random variable" }, { "code": "# importing library from scipy.stats import kstwobign numargs = kstwobign.numargs a, b = 4.32, 3.18rv = kstwobign(a, b) print (\"RV : \\n\", rv) ", "e": 791, "s": 635, "text": null }, { "code": null, "e": 800, "s": 791, "text": "Output :" }, { "code": null, "e": 881, "s": 800, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D54959C8\n" }, { "code": null, "e": 950, "s": 881, "text": "Code #2 : kstwobign continuous variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = kstwobign.rvs(a, b, scale = 2, size = 10) print (\"Random Variates : \\n\", R) ", "e": 1106, "s": 950, "text": null }, { "code": null, "e": 1115, "s": 1106, "text": "Output :" }, { "code": null, "e": 1249, "s": 1115, "text": "Random Variates : \n [3.88510141 3.48394857 3.66124797 3.88484201 3.86533511 3.21176073\n 4.10238585 3.42397866 3.85111721 4.36433596]\n" }, { "code": null, "e": 1285, "s": 1249, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) ", "e": 1496, "s": 1285, "text": null }, { "code": null, "e": 1505, "s": 1496, "text": "Output :" }, { "code": null, "e": 2083, "s": 1505, "text": "Distribution : \n [0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245\n 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939\n 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633\n 1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327\n 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102\n 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714\n 2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408\n 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102\n 2.93877551 3. ]\n " }, { "code": null, "e": 2122, "s": 2083, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = kstwobign .pdf(x, 1, 3) y2 = kstwobign .pdf(x, 1, 4) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 2335, "s": 2122, "text": null }, { "code": null, "e": 2344, "s": 2335, "text": "Output :" }, { "code": null, "e": 2373, "s": 2344, "text": "Python scipy-stats-functions" }, { "code": null, "e": 2380, "s": 2373, "text": "Python" }, { "code": null, "e": 2478, "s": 2380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2496, "s": 2478, "text": "Python Dictionary" }, { "code": null, "e": 2538, "s": 2496, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2560, "s": 2538, "text": "Enumerate() in Python" }, { "code": null, "e": 2586, "s": 2560, "text": "Python String | replace()" }, { "code": null, "e": 2618, "s": 2586, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2647, "s": 2618, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2674, "s": 2647, "text": "Python Classes and Objects" }, { "code": null, "e": 2704, "s": 2674, "text": "Iterate over a list in Python" }, { "code": null, "e": 2740, "s": 2704, "text": "Convert integer to string in Python" } ]
fprintf() in C
28 Oct, 2020 fprintf is used to print content in file instead of stdout console. int fprintf(FILE *fptr, const char *str, ...); Example: C // C Program for the above approach #include<stdio.h>int main(){ int i, n=2; char str[50]; //open file sample.txt in write mode FILE *fptr = fopen("sample.txt", "w"); if (fptr == NULL) { printf("Could not open file"); return 0; } for (i = 0; i < n; i++) { puts("Enter a name"); scanf("%[^\n]%*c", str); fprintf(fptr,"%d.%s\n", i, str); } fclose(fptr); return 0;} Input: GeeksforGeeks GeeksQuiz Output: sample.txt file now having output as 0. GeeksforGeeks 1. GeeksQuiz Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. subhankarh701 cpp-input-output CPP-Library C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Oct, 2020" }, { "code": null, "e": 120, "s": 52, "text": "fprintf is used to print content in file instead of stdout console." }, { "code": null, "e": 168, "s": 120, "text": "int fprintf(FILE *fptr, const char *str, ...);\n" }, { "code": null, "e": 178, "s": 168, "text": "Example: " }, { "code": null, "e": 180, "s": 178, "text": "C" }, { "code": "// C Program for the above approach #include<stdio.h>int main(){ int i, n=2; char str[50]; //open file sample.txt in write mode FILE *fptr = fopen(\"sample.txt\", \"w\"); if (fptr == NULL) { printf(\"Could not open file\"); return 0; } for (i = 0; i < n; i++) { puts(\"Enter a name\"); scanf(\"%[^\\n]%*c\", str); fprintf(fptr,\"%d.%s\\n\", i, str); } fclose(fptr); return 0;}", "e": 624, "s": 180, "text": null }, { "code": null, "e": 740, "s": 624, "text": "Input: GeeksforGeeks\n GeeksQuiz\nOutput: sample.txt file now having output as \n0. GeeksforGeeks\n1. GeeksQuiz\n" }, { "code": null, "e": 865, "s": 740, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 879, "s": 865, "text": "subhankarh701" }, { "code": null, "e": 896, "s": 879, "text": "cpp-input-output" }, { "code": null, "e": 908, "s": 896, "text": "CPP-Library" }, { "code": null, "e": 919, "s": 908, "text": "C Language" } ]
Python program to implement Rock Paper Scissor game
08 Jun, 2022 Python is a multipurpose language and one can do anything with it. Python can also be used for game development. Let’s create a simple command-line Rock-Paper-Scissor game without using any external game libraries like PyGame. In this game, the user gets the first chance to pick the option between Rock, paper, and scissors. After the computer select from the remaining two choices(randomly), the winner is decided as per the rules. Winning Rules as follows : Rock vs paper-> paper wins Rock vs scissor-> Rock wins paper vs scissor-> scissor wins. In this game, randint() inbuilt function is used for generating random integer values within the given range. Below is the implementation: Python3 # import random moduleimport random # Print multiline instruction# performstring concatenation of stringprint("Winning Rules of the Rock paper scissor game as follows: \n" +"Rock vs paper->paper wins \n" + "Rock vs scissor->Rock wins \n" +"paper vs scissor->scissor wins \n") while True: print("Enter choice \n 1 for Rock, \n 2 for paper, and \n 3 for scissor \n") # take the input from user choice = int(input("User turn: ")) # OR is the short-circuit operator # if any one of the condition is true # then it return True value # looping until user enter invalid input while choice > 3 or choice < 1: choice = int(input("enter valid input: ")) # initialize value of choice_name variable # corresponding to the choice value if choice == 1: choice_name = 'Rock' elif choice == 2: choice_name = 'paper' else: choice_name = 'scissor' # print user choice print("user choice is: " + choice_name) print("\nNow its computer turn.......") # Computer chooses randomly any number # among 1 , 2 and 3. Using randint method # of random module comp_choice = random.randint(1, 3) # looping until comp_choice value # is equal to the choice value while comp_choice == choice: comp_choice = random.randint(1, 3) # initialize value of comp_choice_name # variable corresponding to the choice value if comp_choice == 1: comp_choice_name = 'Rock' elif comp_choice == 2: comp_choice_name = 'paper' else: comp_choice_name = 'scissor' print("Computer choice is: " + comp_choice_name) print(choice_name + " V/s " + comp_choice_name) #we need to check of a draw if choice == comp_choice: print("Draw=> ", end = "") result = Draw # condition for winning if((choice == 1 and comp_choice == 2) or (choice == 2 and comp_choice ==1 )): print("paper wins => ", end = "") result = "paper" elif((choice == 1 and comp_choice == 3) or (choice == 3 and comp_choice == 1)): print("Rock wins =>", end = "") result = "Rock" else: print("scissor wins =>", end = "") result = "scissor" # Printing either user or computer wins or draw if result == Draw: print("<== Its a tie ==>") if result == choice_name: print("<== User wins ==>") else: print("<== Computer wins ==>") print("Do you want to play again? (Y/N)") ans = input().lower # if user input n or N then condition is True if ans == 'n': break # after coming out of the while loop# we print thanks for playingprint("\nThanks for playing") Output: winning Rules of the Rock paper and scissor game as follows: rock vs paper->paper wins rock vs scissors->rock wins paper vs scissors->scissors wins Enter choice 1. Rock 2. paper 3. scissor User turn: 1 User choice is: Rock Now its computer turn....... computer choice is: paper Rock V/s paper paper wins =>computer wins do you want to play again? N ishanrastogi26 yotamadk8xh Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jun, 2022" }, { "code": null, "e": 486, "s": 52, "text": "Python is a multipurpose language and one can do anything with it. Python can also be used for game development. Let’s create a simple command-line Rock-Paper-Scissor game without using any external game libraries like PyGame. In this game, the user gets the first chance to pick the option between Rock, paper, and scissors. After the computer select from the remaining two choices(randomly), the winner is decided as per the rules." }, { "code": null, "e": 602, "s": 486, "text": "Winning Rules as follows :\n\nRock vs paper-> paper wins\nRock vs scissor-> Rock wins\npaper vs scissor-> scissor wins." }, { "code": null, "e": 712, "s": 602, "text": "In this game, randint() inbuilt function is used for generating random integer values within the given range." }, { "code": null, "e": 742, "s": 712, "text": "Below is the implementation: " }, { "code": null, "e": 750, "s": 742, "text": "Python3" }, { "code": "# import random moduleimport random # Print multiline instruction# performstring concatenation of stringprint(\"Winning Rules of the Rock paper scissor game as follows: \\n\" +\"Rock vs paper->paper wins \\n\" + \"Rock vs scissor->Rock wins \\n\" +\"paper vs scissor->scissor wins \\n\") while True: print(\"Enter choice \\n 1 for Rock, \\n 2 for paper, and \\n 3 for scissor \\n\") # take the input from user choice = int(input(\"User turn: \")) # OR is the short-circuit operator # if any one of the condition is true # then it return True value # looping until user enter invalid input while choice > 3 or choice < 1: choice = int(input(\"enter valid input: \")) # initialize value of choice_name variable # corresponding to the choice value if choice == 1: choice_name = 'Rock' elif choice == 2: choice_name = 'paper' else: choice_name = 'scissor' # print user choice print(\"user choice is: \" + choice_name) print(\"\\nNow its computer turn.......\") # Computer chooses randomly any number # among 1 , 2 and 3. Using randint method # of random module comp_choice = random.randint(1, 3) # looping until comp_choice value # is equal to the choice value while comp_choice == choice: comp_choice = random.randint(1, 3) # initialize value of comp_choice_name # variable corresponding to the choice value if comp_choice == 1: comp_choice_name = 'Rock' elif comp_choice == 2: comp_choice_name = 'paper' else: comp_choice_name = 'scissor' print(\"Computer choice is: \" + comp_choice_name) print(choice_name + \" V/s \" + comp_choice_name) #we need to check of a draw if choice == comp_choice: print(\"Draw=> \", end = \"\") result = Draw # condition for winning if((choice == 1 and comp_choice == 2) or (choice == 2 and comp_choice ==1 )): print(\"paper wins => \", end = \"\") result = \"paper\" elif((choice == 1 and comp_choice == 3) or (choice == 3 and comp_choice == 1)): print(\"Rock wins =>\", end = \"\") result = \"Rock\" else: print(\"scissor wins =>\", end = \"\") result = \"scissor\" # Printing either user or computer wins or draw if result == Draw: print(\"<== Its a tie ==>\") if result == choice_name: print(\"<== User wins ==>\") else: print(\"<== Computer wins ==>\") print(\"Do you want to play again? (Y/N)\") ans = input().lower # if user input n or N then condition is True if ans == 'n': break # after coming out of the while loop# we print thanks for playingprint(\"\\nThanks for playing\")", "e": 3593, "s": 750, "text": null }, { "code": null, "e": 3602, "s": 3593, "text": "Output: " }, { "code": null, "e": 3965, "s": 3602, "text": "winning Rules of the Rock paper and scissor game as follows:\nrock vs paper->paper wins \nrock vs scissors->rock wins \npaper vs scissors->scissors wins \n\nEnter choice \n 1. Rock \n 2. paper \n 3. scissor \n\nUser turn: 1\nUser choice is: Rock\n\nNow its computer turn.......\n\ncomputer choice is: paper\nRock V/s paper\npaper wins =>computer wins\ndo you want to play again?\nN" }, { "code": null, "e": 3980, "s": 3965, "text": "ishanrastogi26" }, { "code": null, "e": 3992, "s": 3980, "text": "yotamadk8xh" }, { "code": null, "e": 3999, "s": 3992, "text": "Python" }, { "code": null, "e": 4015, "s": 3999, "text": "Python Programs" } ]
Python String format() Method
08 Jul, 2022 Python format() function has been introduced for handling complex string formatting more efficiently. Python3 txt = "I have {an:.2f} Ruppes!"print(txt.format(an = 4)) Output: I have 4.00 Ruppes! This method of the built-in string class provides functionality for complex variable substitutions and value formatting. This new formatting technique is regarded as more elegant. The general syntax of format() method is string.format(var1, var2,...). Here we will try to understand how to Format A String That Contains Curly Braces In Python. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function. Syntax: { }.format(value) Parameters: value : Can be an integer, floating point numeric constant, string, characters or even variables. Returntype: Returns a formatted string with the value passed as parameter in the placeholder position. In this example, we will use the string bracket notation program to demonstrate the str.format() method. Python3 # using format option in a simple stringprint("{}, A computer science portal for geeks." .format("GeeksforGeeks")) # using format option for a# value stored in a variablestr = "This article is written in {}"print(str.format("Python")) # formatting a string using a numeric constantprint("Hello, I am {} years old !".format(18)) Output : GeeksforGeeks, A computer science portal for geeks. This article is written in Python Hello, I am 18 years old! Multiple pairs of curly braces can be used while formatting the string in Python. Let’s say another variable substitution is needed in the sentence, which can be done by adding a second pair of curly braces and passing a second value into the method. Python will replace the placeholders with values in order. Syntax : { } { } .format(value1, value2) Parameters : (value1, value2) : Can be integers, floating point numeric constants, strings, characters and even variables. Only difference is, the number of values passed as parameters in format() method must be equal to the number of placeholders created in the string. Errors and Exceptions : IndexError : Occurs when string has an extra placeholder, and we didn’t pass any value for it in the format() method. Python usually assigns the placeholders with default index in order like 0, 1, 2, 3.... to access the values passed as parameters. So when it encounters a placeholder whose index doesn’t have any value passed inside as parameter, it throws IndexError. Python program using multiple placeholders to demonstrate str.format() method. Python3 # Multiple placeholders in format() functionmy_string = "{}, is a {} science portal for {}"print(my_string.format("GeeksforGeeks", "computer", "geeks")) # different datatypes can be used in formattingprint("Hi ! My name is {} and I am {} years old" .format("User", 19)) # The values passed as parameters# are replaced in order of their entryprint("This is {} {} {} {}" .format("one", "two", "three", "four")) Output : GeeksforGeeks, is a computer science portal for geeks Hi! My name is User and I am 19 years old This is one two three four Python program demonstrating Index error number of placeholders is four but there are only three values passed. Python3 # parameters in format function.my_string = "{}, is a {} {} science portal for {}" print(my_string.format("GeeksforGeeks", "computer", "geeks")) Output : IndexError: tuple index out of range You can use two or more specially designated characters within a string to format a string or perform a command. These characters are called escape sequences. An Escape sequence in Python starts with a backslash (\). For example, \n is an escape sequence in which the common meaning of the letter n is literally escaped and given an alternative meaning – a new line. When placeholders { } are empty, Python will replace the values passed through str.format() in order. The values that exist within the str.format() method are essentially tuple data types and each individual value contained in the tuple can be called by its index number, which starts with the index number 0. These index numbers can be passed into the curly braces that serve as the placeholders in the original string. Syntax : {0} {1}.format(positional_argument, keyword_argument) Parameters : (positional_argument, keyword_argument) Positional_argument can be integers, floating point numeric constants, strings, characters and even variables. Keyword_argument is essentially a variable storing some value, which is passed as parameter. Example: To demonstrate the use of formatters with positional key arguments. Python3 # Positional arguments# are placed in orderprint("{0} love {1}!!".format("GeeksforGeeks", "Geeks")) # Reverse the index numbers with the# parameters of the placeholdersprint("{1} love {0}!!".format("GeeksforGeeks", "Geeks")) print("Every {} should know the use of {} {} programming and {}" .format("programmer", "Open", "Source", "Operating Systems")) # Use the index numbers of the# values to change the order that# they appear in the stringprint("Every {3} should know the use of {2} {1} programming and {0}" .format("programmer", "Open", "Source", "Operating Systems")) # Keyword arguments are called# by their keyword nameprint("{gfg} is a {0} science portal for {1}" .format("computer", "geeks", gfg="GeeksforGeeks")) Output : GeeksforGeeks love Geeks!! Geeks love GeeksforGeeks!! Every programmer should know the use of Open Source programming and Operating Systems Every Operating Systems should know the use of Source Open programming and programmer GeeksforGeeks is a computer science portal for geeks More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name: conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type. Python3 print("%20s" % ('geeksforgeeks', ))print("%-20s" % ('Interngeeks', ))print("%.5s" % ('Interngeeks', )) Output: geeksforgeeks Interngeeks Inter Python3 type = 'bug' result = 'troubling' print('I wondered why the program was %s me. Then\it dawned on me it was a %s .' % (result, type)) Output: I wondered why the program was me troubling me. Then it dawned on me it was a bug. Python3 match = 12000 site = 'amazon' print("%s is so useful. I tried to look\up mobile and they had a nice one that cost %d rupees." % (site, match)) Output: amazon is so useful. I tried to look up mobiles and they had a nice one that cost 12000 rupees %u unsigned decimal integer %o octal integer f – floating-point display b – binary number o – octal number %x – hexadecimal with lowercase letters after 9 %X– hexadecimal with uppercase letters after 9 e – exponent notation You can also specify formatting symbols. The only change is using a colon (:) instead of %. For example, instead of %s use {:s} and instead of %d use (:d} Syntax : String {field_name:conversion} Example.format(value)Errors and Exceptions : ValueError : Error occurs during type conversion in this method. Python3 print("This site is {0:f}% securely {1}!!". format(100, "encrypted")) # To limit the precisionprint("My average of this {0} was {1:.2f}%" .format("semester", 78.234876)) # For no decimal placesprint("My average of this {0} was {1:.0f}%" .format("semester", 78.234876)) # Convert an integer to its binary or# with other different converted bases.print("The {0} of 100 is {1:b}" .format("binary", 100)) print("The {0} of 100 is {1:o}" .format("octal", 100)) Output : This site is 100.000000% securely encrypted!! My average of this semester was 78.23% My average of this semester was 78% The binary of 100 is 1100100 The octal of 100 is 144 Demonstrate ValueError while doing forced type-conversions Python3 # When explicitly converted floating-point# values to decimal with base-10 by 'd'# type conversion we encounter Value-Error.print("The temperature today is {0:d} degrees outside !" .format(35.567)) # Instead write this to avoid value-errors''' print("The temperature today is {0:.0f} degrees outside !" .format(35.567))''' Output : ValueError: Unknown format code 'd' for object of type 'float' By default, strings are left-justified within the field, and numbers are right-justified. We can modify this by placing an alignment code just following the colon. < : left-align text in the field ^ : center text in the field > : right-align text in the field Python3 # To demonstrate spacing when# strings are passed as parametersprint("{0:4}, is the computer science portal for {1:8}!" .format("GeeksforGeeks", "geeks")) # To demonstrate spacing when numeric# constants are passed as parameters.print("It is {0:5} degrees outside !" .format(40)) # To demonstrate both string and numeric# constants passed as parametersprint("{0:4} was founded in {1:16}!" .format("GeeksforGeeks", 2009)) # To demonstrate aligning of spacesprint("{0:^16} was founded in {1:<4}!" .format("GeeksforGeeks", 2009)) print("{:*^20s}".format("Geeks")) Output : GeeksforGeeks, is the computer science portal for geeks ! It is 40 degrees outside! GeeksforGeeks was founded in 2009! GeeksforGeeks was founded in 2009 ! *******Geeks******** Formatters are generally used to Organize Data. Formatters can be seen in their best light when they are being used to organize a lot of data in a visual way. If we are showing databases to users, using formatters to increase field size and modify alignment can make the output more readable. Python3 # which prints out i, i ^ 2, i ^ 3,# i ^ 4 in the given range # Function prints out values# in an unorganized mannerdef unorganized(a, b): for i in range(a, b): print(i, i**2, i**3, i**4) # Function prints the organized set of valuesdef organized(a, b): for i in range(a, b): # Using formatters to give 6 # spaces to each set of values print("{:6d} {:6d} {:6d} {:6d}" .format(i, i ** 2, i ** 3, i ** 4)) # Driver Coden1 = int(input("Enter lower range :-\n"))n2 = int(input("Enter upper range :-\n")) print("------Before Using Formatters-------") # Calling function without formattersunorganized(n1, n2) print()print("-------After Using Formatters---------")print() # Calling function that contains# formatters to organize the dataorganized(n1, n2) Output : Enter lower range :- 3 Enter upper range :- 10 ------Before Using Formatters------- 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561 -------After Using Formatters--------- 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561 Using a dictionary to unpack values into the placeholders in the string that needs to be formatted. We basically use ** to unpack the values. This method can be useful in string substitution while preparing an SQL query. Python3 introduction = 'My name is {first_name} {middle_name} {last_name} AKA the {aka}.'full_name = { 'first_name': 'Tony', 'middle_name': 'Howard', 'last_name': 'Stark', 'aka': 'Iron Man',} # Notice the use of "**" operator to unpack the values.print(introduction.format(**full_name)) Output: My name is Tony Howard Stark AKA the Iron Man. Given a list of float values, the task is to truncate all float values to 2-decimal digits. Let’s see the different methods to do the task. Python3 # Python code to truncate float# values to 2 decimal digits. # List initializationInput = [100.7689454, 17.232999, 60.98867, 300.83748789] # Using formatOutput = ['{:.2f}'.format(elem) for elem in Input] # Print outputprint(Output) Output: ['100.77', '17.23', '60.99', '300.84'] harshsinha03 abhaystoic anikaseth98 kumar_satyam surinderdawra388 surajkumarguptaintern Python-Built-in-functions python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 155, "s": 52, "text": "Python format() function has been introduced for handling complex string formatting more efficiently. " }, { "code": null, "e": 163, "s": 155, "text": "Python3" }, { "code": "txt = \"I have {an:.2f} Ruppes!\"print(txt.format(an = 4))", "e": 220, "s": 163, "text": null }, { "code": null, "e": 228, "s": 220, "text": "Output:" }, { "code": null, "e": 248, "s": 228, "text": "I have 4.00 Ruppes!" }, { "code": null, "e": 593, "s": 248, "text": "This method of the built-in string class provides functionality for complex variable substitutions and value formatting. This new formatting technique is regarded as more elegant. The general syntax of format() method is string.format(var1, var2,...). Here we will try to understand how to Format A String That Contains Curly Braces In Python. " }, { "code": null, "e": 879, "s": 593, "text": "Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function." }, { "code": null, "e": 905, "s": 879, "text": "Syntax: { }.format(value)" }, { "code": null, "e": 918, "s": 905, "text": "Parameters: " }, { "code": null, "e": 1016, "s": 918, "text": "value : Can be an integer, floating point numeric constant, string, characters or even variables." }, { "code": null, "e": 1120, "s": 1016, "text": "Returntype: Returns a formatted string with the value passed as parameter in the placeholder position. " }, { "code": null, "e": 1225, "s": 1120, "text": "In this example, we will use the string bracket notation program to demonstrate the str.format() method." }, { "code": null, "e": 1233, "s": 1225, "text": "Python3" }, { "code": "# using format option in a simple stringprint(\"{}, A computer science portal for geeks.\" .format(\"GeeksforGeeks\")) # using format option for a# value stored in a variablestr = \"This article is written in {}\"print(str.format(\"Python\")) # formatting a string using a numeric constantprint(\"Hello, I am {} years old !\".format(18))", "e": 1566, "s": 1233, "text": null }, { "code": null, "e": 1575, "s": 1566, "text": "Output :" }, { "code": null, "e": 1688, "s": 1575, "text": "GeeksforGeeks, A computer science portal for geeks.\nThis article is written in Python\nHello, I am 18 years old!" }, { "code": null, "e": 1999, "s": 1688, "text": "Multiple pairs of curly braces can be used while formatting the string in Python. Let’s say another variable substitution is needed in the sentence, which can be done by adding a second pair of curly braces and passing a second value into the method. Python will replace the placeholders with values in order. " }, { "code": null, "e": 2040, "s": 1999, "text": "Syntax : { } { } .format(value1, value2)" }, { "code": null, "e": 2312, "s": 2040, "text": "Parameters : (value1, value2) : Can be integers, floating point numeric constants, strings, characters and even variables. Only difference is, the number of values passed as parameters in format() method must be equal to the number of placeholders created in the string." }, { "code": null, "e": 2337, "s": 2312, "text": "Errors and Exceptions : " }, { "code": null, "e": 2708, "s": 2337, "text": "IndexError : Occurs when string has an extra placeholder, and we didn’t pass any value for it in the format() method. Python usually assigns the placeholders with default index in order like 0, 1, 2, 3.... to access the values passed as parameters. So when it encounters a placeholder whose index doesn’t have any value passed inside as parameter, it throws IndexError. " }, { "code": null, "e": 2787, "s": 2708, "text": "Python program using multiple placeholders to demonstrate str.format() method." }, { "code": null, "e": 2795, "s": 2787, "text": "Python3" }, { "code": "# Multiple placeholders in format() functionmy_string = \"{}, is a {} science portal for {}\"print(my_string.format(\"GeeksforGeeks\", \"computer\", \"geeks\")) # different datatypes can be used in formattingprint(\"Hi ! My name is {} and I am {} years old\" .format(\"User\", 19)) # The values passed as parameters# are replaced in order of their entryprint(\"This is {} {} {} {}\" .format(\"one\", \"two\", \"three\", \"four\"))", "e": 3214, "s": 2795, "text": null }, { "code": null, "e": 3224, "s": 3214, "text": "Output : " }, { "code": null, "e": 3347, "s": 3224, "text": "GeeksforGeeks, is a computer science portal for geeks\nHi! My name is User and I am 19 years old\nThis is one two three four" }, { "code": null, "e": 3459, "s": 3347, "text": "Python program demonstrating Index error number of placeholders is four but there are only three values passed." }, { "code": null, "e": 3467, "s": 3459, "text": "Python3" }, { "code": "# parameters in format function.my_string = \"{}, is a {} {} science portal for {}\" print(my_string.format(\"GeeksforGeeks\", \"computer\", \"geeks\"))", "e": 3612, "s": 3467, "text": null }, { "code": null, "e": 3622, "s": 3612, "text": "Output : " }, { "code": null, "e": 3659, "s": 3622, "text": "IndexError: tuple index out of range" }, { "code": null, "e": 4026, "s": 3659, "text": "You can use two or more specially designated characters within a string to format a string or perform a command. These characters are called escape sequences. An Escape sequence in Python starts with a backslash (\\). For example, \\n is an escape sequence in which the common meaning of the letter n is literally escaped and given an alternative meaning – a new line." }, { "code": null, "e": 4447, "s": 4026, "text": "When placeholders { } are empty, Python will replace the values passed through str.format() in order. The values that exist within the str.format() method are essentially tuple data types and each individual value contained in the tuple can be called by its index number, which starts with the index number 0. These index numbers can be passed into the curly braces that serve as the placeholders in the original string." }, { "code": null, "e": 4510, "s": 4447, "text": "Syntax : {0} {1}.format(positional_argument, keyword_argument)" }, { "code": null, "e": 4563, "s": 4510, "text": "Parameters : (positional_argument, keyword_argument)" }, { "code": null, "e": 4675, "s": 4563, "text": "Positional_argument can be integers, floating point numeric constants, strings, characters and even variables. " }, { "code": null, "e": 4768, "s": 4675, "text": "Keyword_argument is essentially a variable storing some value, which is passed as parameter." }, { "code": null, "e": 4777, "s": 4768, "text": "Example:" }, { "code": null, "e": 4845, "s": 4777, "text": "To demonstrate the use of formatters with positional key arguments." }, { "code": null, "e": 4853, "s": 4845, "text": "Python3" }, { "code": "# Positional arguments# are placed in orderprint(\"{0} love {1}!!\".format(\"GeeksforGeeks\", \"Geeks\")) # Reverse the index numbers with the# parameters of the placeholdersprint(\"{1} love {0}!!\".format(\"GeeksforGeeks\", \"Geeks\")) print(\"Every {} should know the use of {} {} programming and {}\" .format(\"programmer\", \"Open\", \"Source\", \"Operating Systems\")) # Use the index numbers of the# values to change the order that# they appear in the stringprint(\"Every {3} should know the use of {2} {1} programming and {0}\" .format(\"programmer\", \"Open\", \"Source\", \"Operating Systems\")) # Keyword arguments are called# by their keyword nameprint(\"{gfg} is a {0} science portal for {1}\" .format(\"computer\", \"geeks\", gfg=\"GeeksforGeeks\"))", "e": 5665, "s": 4853, "text": null }, { "code": null, "e": 5675, "s": 5665, "text": "Output : " }, { "code": null, "e": 5702, "s": 5675, "text": "GeeksforGeeks love Geeks!!" }, { "code": null, "e": 5729, "s": 5702, "text": "Geeks love GeeksforGeeks!!" }, { "code": null, "e": 5815, "s": 5729, "text": "Every programmer should know the use of Open Source programming and Operating Systems" }, { "code": null, "e": 5901, "s": 5815, "text": "Every Operating Systems should know the use of Source Open programming and programmer" }, { "code": null, "e": 5954, "s": 5901, "text": "GeeksforGeeks is a computer science portal for geeks" }, { "code": null, "e": 6229, "s": 5954, "text": "More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name: conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type." }, { "code": null, "e": 6237, "s": 6229, "text": "Python3" }, { "code": "print(\"%20s\" % ('geeksforgeeks', ))print(\"%-20s\" % ('Interngeeks', ))print(\"%.5s\" % ('Interngeeks', ))", "e": 6340, "s": 6237, "text": null }, { "code": null, "e": 6348, "s": 6340, "text": "Output:" }, { "code": null, "e": 6389, "s": 6348, "text": "geeksforgeeks\nInterngeeks \nInter" }, { "code": null, "e": 6397, "s": 6389, "text": "Python3" }, { "code": "type = 'bug' result = 'troubling' print('I wondered why the program was %s me. Then\\it dawned on me it was a %s .' % (result, type))", "e": 6535, "s": 6397, "text": null }, { "code": null, "e": 6543, "s": 6535, "text": "Output:" }, { "code": null, "e": 6626, "s": 6543, "text": "I wondered why the program was me troubling me. Then it dawned on me it was a bug." }, { "code": null, "e": 6634, "s": 6626, "text": "Python3" }, { "code": "match = 12000 site = 'amazon' print(\"%s is so useful. I tried to look\\up mobile and they had a nice one that cost %d rupees.\" % (site, match))", "e": 6777, "s": 6634, "text": null }, { "code": null, "e": 6785, "s": 6777, "text": "Output:" }, { "code": null, "e": 6880, "s": 6785, "text": "amazon is so useful. I tried to look up mobiles and they had a nice one that cost 12000 rupees" }, { "code": null, "e": 6908, "s": 6880, "text": "%u unsigned decimal integer" }, { "code": null, "e": 6925, "s": 6908, "text": "%o octal integer" }, { "code": null, "e": 6952, "s": 6925, "text": "f – floating-point display" }, { "code": null, "e": 6970, "s": 6952, "text": "b – binary number" }, { "code": null, "e": 6987, "s": 6970, "text": "o – octal number" }, { "code": null, "e": 7035, "s": 6987, "text": "%x – hexadecimal with lowercase letters after 9" }, { "code": null, "e": 7082, "s": 7035, "text": "%X– hexadecimal with uppercase letters after 9" }, { "code": null, "e": 7104, "s": 7082, "text": "e – exponent notation" }, { "code": null, "e": 7259, "s": 7104, "text": "You can also specify formatting symbols. The only change is using a colon (:) instead of %. For example, instead of %s use {:s} and instead of %d use (:d}" }, { "code": null, "e": 7410, "s": 7259, "text": "Syntax : String {field_name:conversion} Example.format(value)Errors and Exceptions : ValueError : Error occurs during type conversion in this method. " }, { "code": null, "e": 7418, "s": 7410, "text": "Python3" }, { "code": "print(\"This site is {0:f}% securely {1}!!\". format(100, \"encrypted\")) # To limit the precisionprint(\"My average of this {0} was {1:.2f}%\" .format(\"semester\", 78.234876)) # For no decimal placesprint(\"My average of this {0} was {1:.0f}%\" .format(\"semester\", 78.234876)) # Convert an integer to its binary or# with other different converted bases.print(\"The {0} of 100 is {1:b}\" .format(\"binary\", 100)) print(\"The {0} of 100 is {1:o}\" .format(\"octal\", 100))", "e": 7899, "s": 7418, "text": null }, { "code": null, "e": 7909, "s": 7899, "text": "Output : " }, { "code": null, "e": 8083, "s": 7909, "text": "This site is 100.000000% securely encrypted!!\nMy average of this semester was 78.23%\nMy average of this semester was 78%\nThe binary of 100 is 1100100\nThe octal of 100 is 144" }, { "code": null, "e": 8142, "s": 8083, "text": "Demonstrate ValueError while doing forced type-conversions" }, { "code": null, "e": 8150, "s": 8142, "text": "Python3" }, { "code": "# When explicitly converted floating-point# values to decimal with base-10 by 'd'# type conversion we encounter Value-Error.print(\"The temperature today is {0:d} degrees outside !\" .format(35.567)) # Instead write this to avoid value-errors''' print(\"The temperature today is {0:.0f} degrees outside !\" .format(35.567))'''", "e": 8521, "s": 8150, "text": null }, { "code": null, "e": 8531, "s": 8521, "text": "Output : " }, { "code": null, "e": 8594, "s": 8531, "text": "ValueError: Unknown format code 'd' for object of type 'float'" }, { "code": null, "e": 8758, "s": 8594, "text": "By default, strings are left-justified within the field, and numbers are right-justified. We can modify this by placing an alignment code just following the colon." }, { "code": null, "e": 8863, "s": 8758, "text": "< : left-align text in the field\n^ : center text in the field\n> : right-align text in the field" }, { "code": null, "e": 8871, "s": 8863, "text": "Python3" }, { "code": "# To demonstrate spacing when# strings are passed as parametersprint(\"{0:4}, is the computer science portal for {1:8}!\" .format(\"GeeksforGeeks\", \"geeks\")) # To demonstrate spacing when numeric# constants are passed as parameters.print(\"It is {0:5} degrees outside !\" .format(40)) # To demonstrate both string and numeric# constants passed as parametersprint(\"{0:4} was founded in {1:16}!\" .format(\"GeeksforGeeks\", 2009)) # To demonstrate aligning of spacesprint(\"{0:^16} was founded in {1:<4}!\" .format(\"GeeksforGeeks\", 2009)) print(\"{:*^20s}\".format(\"Geeks\"))", "e": 9453, "s": 8871, "text": null }, { "code": null, "e": 9463, "s": 9453, "text": "Output : " }, { "code": null, "e": 9659, "s": 9463, "text": "GeeksforGeeks, is the computer science portal for geeks !\nIt is 40 degrees outside!\nGeeksforGeeks was founded in 2009!\n GeeksforGeeks was founded in 2009 !\n*******Geeks********" }, { "code": null, "e": 9952, "s": 9659, "text": "Formatters are generally used to Organize Data. Formatters can be seen in their best light when they are being used to organize a lot of data in a visual way. If we are showing databases to users, using formatters to increase field size and modify alignment can make the output more readable." }, { "code": null, "e": 9960, "s": 9952, "text": "Python3" }, { "code": "# which prints out i, i ^ 2, i ^ 3,# i ^ 4 in the given range # Function prints out values# in an unorganized mannerdef unorganized(a, b): for i in range(a, b): print(i, i**2, i**3, i**4) # Function prints the organized set of valuesdef organized(a, b): for i in range(a, b): # Using formatters to give 6 # spaces to each set of values print(\"{:6d} {:6d} {:6d} {:6d}\" .format(i, i ** 2, i ** 3, i ** 4)) # Driver Coden1 = int(input(\"Enter lower range :-\\n\"))n2 = int(input(\"Enter upper range :-\\n\")) print(\"------Before Using Formatters-------\") # Calling function without formattersunorganized(n1, n2) print()print(\"-------After Using Formatters---------\")print() # Calling function that contains# formatters to organize the dataorganized(n1, n2)", "e": 10757, "s": 9960, "text": null }, { "code": null, "e": 10767, "s": 10757, "text": "Output : " }, { "code": null, "e": 11179, "s": 10767, "text": "Enter lower range :-\n3\nEnter upper range :-\n10\n------Before Using Formatters-------\n3 9 27 81\n4 16 64 256\n5 25 125 625\n6 36 216 1296\n7 49 343 2401\n8 64 512 4096\n9 81 729 6561\n\n-------After Using Formatters---------\n\n 3 9 27 81\n 4 16 64 256\n 5 25 125 625\n 6 36 216 1296\n 7 49 343 2401\n 8 64 512 4096\n 9 81 729 6561" }, { "code": null, "e": 11400, "s": 11179, "text": "Using a dictionary to unpack values into the placeholders in the string that needs to be formatted. We basically use ** to unpack the values. This method can be useful in string substitution while preparing an SQL query." }, { "code": null, "e": 11408, "s": 11400, "text": "Python3" }, { "code": "introduction = 'My name is {first_name} {middle_name} {last_name} AKA the {aka}.'full_name = { 'first_name': 'Tony', 'middle_name': 'Howard', 'last_name': 'Stark', 'aka': 'Iron Man',} # Notice the use of \"**\" operator to unpack the values.print(introduction.format(**full_name))", "e": 11699, "s": 11408, "text": null }, { "code": null, "e": 11707, "s": 11699, "text": "Output:" }, { "code": null, "e": 11754, "s": 11707, "text": "My name is Tony Howard Stark AKA the Iron Man." }, { "code": null, "e": 11894, "s": 11754, "text": "Given a list of float values, the task is to truncate all float values to 2-decimal digits. Let’s see the different methods to do the task." }, { "code": null, "e": 11902, "s": 11894, "text": "Python3" }, { "code": "# Python code to truncate float# values to 2 decimal digits. # List initializationInput = [100.7689454, 17.232999, 60.98867, 300.83748789] # Using formatOutput = ['{:.2f}'.format(elem) for elem in Input] # Print outputprint(Output)", "e": 12140, "s": 11902, "text": null }, { "code": null, "e": 12148, "s": 12140, "text": "Output:" }, { "code": null, "e": 12187, "s": 12148, "text": "['100.77', '17.23', '60.99', '300.84']" }, { "code": null, "e": 12200, "s": 12187, "text": "harshsinha03" }, { "code": null, "e": 12211, "s": 12200, "text": "abhaystoic" }, { "code": null, "e": 12223, "s": 12211, "text": "anikaseth98" }, { "code": null, "e": 12236, "s": 12223, "text": "kumar_satyam" }, { "code": null, "e": 12253, "s": 12236, "text": "surinderdawra388" }, { "code": null, "e": 12275, "s": 12253, "text": "surajkumarguptaintern" }, { "code": null, "e": 12301, "s": 12275, "text": "Python-Built-in-functions" }, { "code": null, "e": 12315, "s": 12301, "text": "python-string" }, { "code": null, "e": 12322, "s": 12315, "text": "Python" } ]
C# Online Compiler (Editor / Interpreter)
With our online C# compiler, you can edit C# code, and view the result in your browser. using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } Click on the "Try it Yourself" button to see how it works. The window to the left is editable - edit the code and click on the "Run" button to view the result in the right window. The icons are explained in the table below: If you don't know C#, we suggest that you read our C# Tutorial from scratch. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 88, "s": 0, "text": "With our online C# compiler, you can edit C# code, and view the result in your browser." }, { "code": null, "e": 245, "s": 88, "text": "using System;\n\nnamespace HelloWorld\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(\"Hello World!\"); \n }\n }\n}" }, { "code": null, "e": 304, "s": 245, "text": "Click on the \"Try it Yourself\" button to see how it works." }, { "code": null, "e": 425, "s": 304, "text": "The window to the left is editable - edit the code and click on the \"Run\" button to view the result in the right window." }, { "code": null, "e": 469, "s": 425, "text": "The icons are explained in the table below:" }, { "code": null, "e": 546, "s": 469, "text": "If you don't know C#, we suggest that you read our C# Tutorial from scratch." }, { "code": null, "e": 579, "s": 546, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 621, "s": 579, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 728, "s": 621, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 747, "s": 728, "text": "[email protected]" } ]
Rexx - File I/O
Rexx provides a number of methods when working with I/O. Rexx provides easier classes to provide the following functionalities for files. Reading files Writing to files Seeing whether a file is a file or directory The functions available in Rexx for File I/O are based on both line input and character input and we will be looking at the functions available for both in detail. Let’s explore some of the file operations Rexx has to offer. For the purposes of these examples, we are going to assume that there is a file called NewFile.txt which contains the following lines of text − Example1 Example2 Example3 This file will be used for the read and write operations in the following examples. Here we will discuss regarding how to read the contents on a file in different ways. The general operations on files are carried out by using the methods available in the Rexx library itself. The reading of files is the simplest of all operations in Rexx. Let’s look at the function used to accomplish this. This method returns a line from the text file. The text file is the filename provided as the input parameter to the function. Syntax − linein(filename) Parameter − filename − This is the name of the file from where the line needs to be read. filename − This is the name of the file from where the line needs to be read. Return Value − This method returns one line of the file at a time. Example − /* Main program */ line_str = linein(Example.txt) say line_str The above code is pretty simple in the fact that the Example.txt file name is provided to the linein function. This function then reads a line of text and provides the result to the variable line_str. Output − When we run the above program we will get the following result. Example1 In Rexx, reading all the contents of a file can be achieved with the help of the while statement. The while statement will read each line, one by one till the end of the file is reached. An example on how this can be achieved is shown below. /* Main program */ do while lines(Example.txt) > 0 line_str = linein(Example.txt) say line_str end In the above program, the following things need to be noted − The lines function reads the Example.txt file. The lines function reads the Example.txt file. The while function is used to check if further lines exist in the Example.txt file. The while function is used to check if further lines exist in the Example.txt file. For each line read from the file, the line_str variable holds the value of the current line. This is then sent to the console as output. For each line read from the file, the line_str variable holds the value of the current line. This is then sent to the console as output. Output − When we run the above program we will get the following result. Example1 Example2 Example3 Just like reading of files, Rexx also has the ability to write to files. Let’s look at the function which is used to accomplish this. This method writes a line to a file. The file to which the line needs to be written to is provided as the parameter to the lineout statement. Syntax − lineout(filename) Parameter − filename − This is the name of the file from where the line needs to be written to. filename − This is the name of the file from where the line needs to be written to. Return Value − This method returns the status of the lineout function. The value returned is 0 if the line was successfully written else the value of 1 will be returned. Example − /* Main program */ out = lineout(Example.txt,"Example4") Output − Whenever the above code is run, the line “Example4” will be written to the file Example.txt. Print Add Notes Bookmark this page
[ { "code": null, "e": 2477, "s": 2339, "text": "Rexx provides a number of methods when working with I/O. Rexx provides easier classes to provide the following functionalities for files." }, { "code": null, "e": 2491, "s": 2477, "text": "Reading files" }, { "code": null, "e": 2508, "s": 2491, "text": "Writing to files" }, { "code": null, "e": 2553, "s": 2508, "text": "Seeing whether a file is a file or directory" }, { "code": null, "e": 2717, "s": 2553, "text": "The functions available in Rexx for File I/O are based on both line input and character input and we will be looking at the functions available for both in detail." }, { "code": null, "e": 2922, "s": 2717, "text": "Let’s explore some of the file operations Rexx has to offer. For the purposes of these examples, we are going to assume that there is a file called NewFile.txt which contains the following lines of text −" }, { "code": null, "e": 2931, "s": 2922, "text": "Example1" }, { "code": null, "e": 2940, "s": 2931, "text": "Example2" }, { "code": null, "e": 2949, "s": 2940, "text": "Example3" }, { "code": null, "e": 3118, "s": 2949, "text": "This file will be used for the read and write operations in the following examples. Here we will discuss regarding how to read the contents on a file in different ways." }, { "code": null, "e": 3289, "s": 3118, "text": "The general operations on files are carried out by using the methods available in the Rexx library itself. The reading of files is the simplest of all operations in Rexx." }, { "code": null, "e": 3341, "s": 3289, "text": "Let’s look at the function used to accomplish this." }, { "code": null, "e": 3467, "s": 3341, "text": "This method returns a line from the text file. The text file is the filename provided as the input parameter to the function." }, { "code": null, "e": 3476, "s": 3467, "text": "Syntax −" }, { "code": null, "e": 3495, "s": 3476, "text": "linein(filename) \n" }, { "code": null, "e": 3507, "s": 3495, "text": "Parameter −" }, { "code": null, "e": 3585, "s": 3507, "text": "filename − This is the name of the file from where the line needs to be read." }, { "code": null, "e": 3663, "s": 3585, "text": "filename − This is the name of the file from where the line needs to be read." }, { "code": null, "e": 3730, "s": 3663, "text": "Return Value − This method returns one line of the file at a time." }, { "code": null, "e": 3740, "s": 3730, "text": "Example −" }, { "code": null, "e": 3805, "s": 3740, "text": "/* Main program */ \nline_str = linein(Example.txt) \nsay line_str" }, { "code": null, "e": 4006, "s": 3805, "text": "The above code is pretty simple in the fact that the Example.txt file name is provided to the linein function. This function then reads a line of text and provides the result to the variable line_str." }, { "code": null, "e": 4079, "s": 4006, "text": "Output − When we run the above program we will get the following result." }, { "code": null, "e": 4089, "s": 4079, "text": "Example1\n" }, { "code": null, "e": 4276, "s": 4089, "text": "In Rexx, reading all the contents of a file can be achieved with the help of the while statement. The while statement will read each line, one by one till the end of the file is reached." }, { "code": null, "e": 4331, "s": 4276, "text": "An example on how this can be achieved is shown below." }, { "code": null, "e": 4436, "s": 4331, "text": "/* Main program */ \ndo while lines(Example.txt) > 0 \nline_str = linein(Example.txt) \nsay line_str \nend " }, { "code": null, "e": 4498, "s": 4436, "text": "In the above program, the following things need to be noted −" }, { "code": null, "e": 4545, "s": 4498, "text": "The lines function reads the Example.txt file." }, { "code": null, "e": 4592, "s": 4545, "text": "The lines function reads the Example.txt file." }, { "code": null, "e": 4676, "s": 4592, "text": "The while function is used to check if further lines exist in the Example.txt file." }, { "code": null, "e": 4760, "s": 4676, "text": "The while function is used to check if further lines exist in the Example.txt file." }, { "code": null, "e": 4897, "s": 4760, "text": "For each line read from the file, the line_str variable holds the value of the current line. This is then sent to the console as output." }, { "code": null, "e": 5034, "s": 4897, "text": "For each line read from the file, the line_str variable holds the value of the current line. This is then sent to the console as output." }, { "code": null, "e": 5107, "s": 5034, "text": "Output − When we run the above program we will get the following result." }, { "code": null, "e": 5138, "s": 5107, "text": "Example1 \nExample2 \nExample3 \n" }, { "code": null, "e": 5272, "s": 5138, "text": "Just like reading of files, Rexx also has the ability to write to files. Let’s look at the function which is used to accomplish this." }, { "code": null, "e": 5414, "s": 5272, "text": "This method writes a line to a file. The file to which the line needs to be written to is provided as the parameter to the lineout statement." }, { "code": null, "e": 5423, "s": 5414, "text": "Syntax −" }, { "code": null, "e": 5443, "s": 5423, "text": "lineout(filename) \n" }, { "code": null, "e": 5455, "s": 5443, "text": "Parameter −" }, { "code": null, "e": 5539, "s": 5455, "text": "filename − This is the name of the file from where the line needs to be written to." }, { "code": null, "e": 5623, "s": 5539, "text": "filename − This is the name of the file from where the line needs to be written to." }, { "code": null, "e": 5793, "s": 5623, "text": "Return Value − This method returns the status of the lineout function. The value returned is 0 if the line was successfully written else the value of 1 will be returned." }, { "code": null, "e": 5803, "s": 5793, "text": "Example −" }, { "code": null, "e": 5862, "s": 5803, "text": "/* Main program */ \nout = lineout(Example.txt,\"Example4\") " }, { "code": null, "e": 5964, "s": 5862, "text": "Output − Whenever the above code is run, the line “Example4” will be written to the file Example.txt." }, { "code": null, "e": 5971, "s": 5964, "text": " Print" }, { "code": null, "e": 5982, "s": 5971, "text": " Add Notes" } ]
Centered triangular number in PL/SQL - GeeksforGeeks
31 Oct, 2018 Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given n and task is to find nth centered triangular number. A centered triangular number is a centered number that represents a triangle with a dot in the center and all other dots surrounding the center in successive triangular layers.Examples: Input: n = 6 Output: 64 Input: n = 10 Output: 166 The first few centered triangular number series are:1, 4, 10, 19, 31, 46, 64, 85, 109, 136, 166, 199, 235, 274, 316, 361, 409, 460........................... Approachnth Term of centered triangular number is given by: Below is the required implementation: --PL/SQL Program to find the nth Centered triangular number -- declaration section DECLARE x NUMBER; n NUMBER; --utility function FUNCTION Centered_triangular_num(n IN NUMBER) RETURN NUMBER IS z NUMBER; BEGIN --formula applying z := (3 * n * n + 3 * n + 2) / 2; RETURN z; END; --driver code BEGIN n := 3; x := centered_triangular_num(n); dbms_output.Put_line(x); n := 12; x := centered_trigunal_num(n); dbms_output.Put_line(x); END; --End of program Output: 19 235 References:https://en.wikipedia.org/wiki/Centered_triangular_number SQL-PL/SQL triangular-number SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL MySQL | Group_CONCAT() Function What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python MySQL | Regular expressions (Regexp)
[ { "code": null, "e": 24292, "s": 24264, "text": "\n31 Oct, 2018" }, { "code": null, "e": 24536, "s": 24292, "text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 24782, "s": 24536, "text": "Given n and task is to find nth centered triangular number. A centered triangular number is a centered number that represents a triangle with a dot in the center and all other dots surrounding the center in successive triangular layers.Examples:" }, { "code": null, "e": 24835, "s": 24782, "text": "Input: n = 6 \nOutput: 64\n\nInput: n = 10\nOutput: 166\n" }, { "code": null, "e": 24993, "s": 24835, "text": "The first few centered triangular number series are:1, 4, 10, 19, 31, 46, 64, 85, 109, 136, 166, 199, 235, 274, 316, 361, 409, 460..........................." }, { "code": null, "e": 25053, "s": 24993, "text": "Approachnth Term of centered triangular number is given by:" }, { "code": null, "e": 25093, "s": 25055, "text": "Below is the required implementation:" }, { "code": "--PL/SQL Program to find the nth Centered triangular number -- declaration section DECLARE x NUMBER; n NUMBER; --utility function FUNCTION Centered_triangular_num(n IN NUMBER) RETURN NUMBER IS z NUMBER; BEGIN --formula applying z := (3 * n * n + 3 * n + 2) / 2; RETURN z; END; --driver code BEGIN n := 3; x := centered_triangular_num(n); dbms_output.Put_line(x); n := 12; x := centered_trigunal_num(n); dbms_output.Put_line(x); END; --End of program", "e": 25621, "s": 25093, "text": null }, { "code": null, "e": 25629, "s": 25621, "text": "Output:" }, { "code": null, "e": 25636, "s": 25629, "text": "19\n235" }, { "code": null, "e": 25704, "s": 25636, "text": "References:https://en.wikipedia.org/wiki/Centered_triangular_number" }, { "code": null, "e": 25715, "s": 25704, "text": "SQL-PL/SQL" }, { "code": null, "e": 25733, "s": 25715, "text": "triangular-number" }, { "code": null, "e": 25737, "s": 25733, "text": "SQL" }, { "code": null, "e": 25741, "s": 25737, "text": "SQL" }, { "code": null, "e": 25839, "s": 25741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25850, "s": 25839, "text": "CTE in SQL" }, { "code": null, "e": 25916, "s": 25850, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25940, "s": 25916, "text": "SQL Interview Questions" }, { "code": null, "e": 25985, "s": 25940, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26018, "s": 25985, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 26050, "s": 26018, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 26082, "s": 26050, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26160, "s": 26082, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 26177, "s": 26160, "text": "SQL using Python" } ]
C++ Algorithm Library - for_each() Function
The C++ function std::algorithm::for_each() applies provided function on each element of the range. Following is the declaration for std::algorithm::for_each() function form std::algorithm header. template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function fn); first − Input iterator to the initial position. first − Input iterator to the initial position. last − Final iterator to the final position. last − Final iterator to the final position. fn − Unary function that accepts an element in the range as argument. fn − Unary function that accepts an element in the range as argument. Returns function fn. Linear. Throws exception if either function fn or an operation on an iterator throws exception. Please note that invalid parameters cause undefined behavior. The following example shows the usage of std::algorithm::for_each() function. #include <iostream> #include <vector> #include <algorithm> using namespace std; int print_even(int n) { if (n % 2 == 0) cout << n << ' '; } int main(void) { vector<int> v = {1, 2, 3, 4, 5}; cout << "Vector contains following even numebr" << endl; for_each(v.begin(), v.end(), print_even); cout << endl; return 0; } Let us compile and run the above program, this will produce the following result − Vector contains following even numebr 2 4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2703, "s": 2603, "text": "The C++ function std::algorithm::for_each() applies provided function on each element of the range." }, { "code": null, "e": 2800, "s": 2703, "text": "Following is the declaration for std::algorithm::for_each() function form std::algorithm header." }, { "code": null, "e": 2922, "s": 2800, "text": "template <class InputIterator, class Function>\nFunction for_each (InputIterator first, InputIterator last, Function fn);\n" }, { "code": null, "e": 2970, "s": 2922, "text": "first − Input iterator to the initial position." }, { "code": null, "e": 3018, "s": 2970, "text": "first − Input iterator to the initial position." }, { "code": null, "e": 3063, "s": 3018, "text": "last − Final iterator to the final position." }, { "code": null, "e": 3108, "s": 3063, "text": "last − Final iterator to the final position." }, { "code": null, "e": 3178, "s": 3108, "text": "fn − Unary function that accepts an element in the range as argument." }, { "code": null, "e": 3248, "s": 3178, "text": "fn − Unary function that accepts an element in the range as argument." }, { "code": null, "e": 3269, "s": 3248, "text": "Returns function fn." }, { "code": null, "e": 3277, "s": 3269, "text": "Linear." }, { "code": null, "e": 3365, "s": 3277, "text": "Throws exception if either function fn or an operation on an iterator throws exception." }, { "code": null, "e": 3427, "s": 3365, "text": "Please note that invalid parameters cause undefined behavior." }, { "code": null, "e": 3505, "s": 3427, "text": "The following example shows the usage of std::algorithm::for_each() function." }, { "code": null, "e": 3851, "s": 3505, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint print_even(int n) {\n if (n % 2 == 0)\n cout << n << ' ';\n}\n\nint main(void) {\n vector<int> v = {1, 2, 3, 4, 5};\n\n cout << \"Vector contains following even numebr\" << endl;\n\n for_each(v.begin(), v.end(), print_even);\n\n cout << endl;\n\n return 0;\n}" }, { "code": null, "e": 3934, "s": 3851, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3978, "s": 3934, "text": "Vector contains following even numebr\n2 4 \n" }, { "code": null, "e": 3985, "s": 3978, "text": " Print" }, { "code": null, "e": 3996, "s": 3985, "text": " Add Notes" } ]
Java program to find if the given number is positive or negative
Read a number from the user using the Scanner class's method. check whether the given number is greater, lesser or, equal to 0. If it is greater given number is positive if the lesser given number is negative. the else given number is neither positive or negative. import java.util.Scanner; public class PositiveOrNegative { public static void main(String args[]){ int num; System.out.println("Enter a number ::"); Scanner sc = new Scanner(System.in); num = sc.nextInt(); if (num > 0){ System.out.println("Given number is a positive integer"); } else if(num < 0){ System.out.println("Given number is a negative integer"); } else { System.out.println("Given number is neither positive nor negative integer"); } } } Enter a number :: 55 Given number is a positive integer Enter a number :: -88 Given number is a negative integer
[ { "code": null, "e": 1327, "s": 1062, "text": "Read a number from the user using the Scanner class's method. check whether the given number is greater, lesser or, equal to 0. If it is greater given number is positive if the lesser given number is negative. the else given number is neither positive or negative." }, { "code": null, "e": 1859, "s": 1327, "text": "import java.util.Scanner;\n\npublic class PositiveOrNegative {\n public static void main(String args[]){\n int num;\n System.out.println(\"Enter a number ::\");\n Scanner sc = new Scanner(System.in);\n num = sc.nextInt();\n\n if (num > 0){\n System.out.println(\"Given number is a positive integer\");\n } else if(num < 0){\n System.out.println(\"Given number is a negative integer\");\n } else {\n System.out.println(\"Given number is neither positive nor negative integer\");\n }\n }\n}" }, { "code": null, "e": 1915, "s": 1859, "text": "Enter a number ::\n55\nGiven number is a positive integer" }, { "code": null, "e": 1972, "s": 1915, "text": "Enter a number ::\n-88\nGiven number is a negative integer" } ]
Scala - Files I/O
Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming to read and write files. The following is an example program to writing to a file. import java.io._ object Demo { def main(args: Array[String]) { val writer = new PrintWriter(new File("test.txt" )) writer.write("Hello Scala") writer.close() } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo It will create a file named Demo.txt in the current directory, where the program is placed. The following is the content of that file. Hello Scala Sometime you need to read user input from the screen and then proceed for some further processing. Following example program shows you how to read input from the command line. object Demo { def main(args: Array[String]) { print("Please enter your input : " ) val line = Console.readLine println("Thanks, you just typed: " + line) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Please enter your input : Scala is great Thanks, you just typed: Scala is great Reading from files is really simple. You can use Scala's Source class and its companion object to read files. Following is the example which shows you how to read from "Demo.txt" file which we created earlier. import scala.io.Source object Demo { def main(args: Array[String]) { println("Following is the content read:" ) Source.fromFile("Demo.txt" ).foreach { print } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Following is the content read: Hello Scala 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2147, "s": 1998, "text": "Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming to read and write files." }, { "code": null, "e": 2205, "s": 2147, "text": "The following is an example program to writing to a file." }, { "code": null, "e": 2393, "s": 2205, "text": "import java.io._\n\nobject Demo {\n def main(args: Array[String]) {\n val writer = new PrintWriter(new File(\"test.txt\" ))\n\n writer.write(\"Hello Scala\")\n writer.close()\n }\n}" }, { "code": null, "e": 2500, "s": 2393, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 2534, "s": 2500, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 2669, "s": 2534, "text": "It will create a file named Demo.txt in the current directory, where the program is placed. The following is the content of that file." }, { "code": null, "e": 2682, "s": 2669, "text": "Hello Scala\n" }, { "code": null, "e": 2858, "s": 2682, "text": "Sometime you need to read user input from the screen and then proceed for some further processing. Following example program shows you how to read input from the command line." }, { "code": null, "e": 3047, "s": 2858, "text": "object Demo {\n def main(args: Array[String]) {\n print(\"Please enter your input : \" )\n val line = Console.readLine\n \n println(\"Thanks, you just typed: \" + line)\n }\n}" }, { "code": null, "e": 3154, "s": 3047, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3188, "s": 3154, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 3269, "s": 3188, "text": "Please enter your input : Scala is great\nThanks, you just typed: Scala is great\n" }, { "code": null, "e": 3479, "s": 3269, "text": "Reading from files is really simple. You can use Scala's Source class and its companion object to read files. Following is the example which shows you how to read from \"Demo.txt\" file which we created earlier." }, { "code": null, "e": 3679, "s": 3479, "text": "import scala.io.Source\n\nobject Demo {\n def main(args: Array[String]) {\n println(\"Following is the content read:\" )\n\n Source.fromFile(\"Demo.txt\" ).foreach { \n print \n }\n }\n}" }, { "code": null, "e": 3786, "s": 3679, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3820, "s": 3786, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 3864, "s": 3820, "text": "Following is the content read:\nHello Scala\n" }, { "code": null, "e": 3897, "s": 3864, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 3916, "s": 3897, "text": " Arnab Chakraborty" }, { "code": null, "e": 3951, "s": 3916, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3972, "s": 3951, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 4007, "s": 3972, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4025, "s": 4007, "text": " Bigdata Engineer" }, { "code": null, "e": 4060, "s": 4025, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4078, "s": 4060, "text": " Bigdata Engineer" }, { "code": null, "e": 4113, "s": 4078, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4131, "s": 4113, "text": " Bigdata Engineer" }, { "code": null, "e": 4166, "s": 4131, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4189, "s": 4166, "text": " Stone River ELearning" }, { "code": null, "e": 4196, "s": 4189, "text": " Print" }, { "code": null, "e": 4207, "s": 4196, "text": " Add Notes" } ]
CardView using RecyclerView in Android with Example - GeeksforGeeks
09 Dec, 2020 RecyclerView is an extended version of ListView and GridView. It works on the ViewHolder design pattern. With the help of RecyclerView, we can add many extra features to our list of data. Before starting our example on implementation of CardView in RecyclerView. We should know what CardView and RecyclerView mean. CardView: CardView is an extended version of Framelayout which can be used to show items inside the card format. With the help of CardView, we can add radius, elevation to our items of RecyclerView. CardView gives a rich look and feels to our list of data. RecyclerView: RecyclerView is an extended version of ListView. in RecyclerView we can load a large amount of data and items of RecyclerView can have a custom design. RecyclerView works on ViewHolder design pattern so we have to create a Data class that holds data for RecyclerView and a ViewHolder class which will set data to each item of RecyclerView. RecyclerView is divided into 3 sections: Card Layout. Modal Class. ViewHolder class. Now we will move towards the implementation of our RecyclerView. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. So we are creating a simple example for displaying various courses available on GFG in the RecyclerView using a Card Layout. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add dependency for creating CardView and RecyclerView Navigate to the Gradle Scripts > build.gradle(Module:app) and add below dependency in the dependency section. implementation ‘com.google.android.material:material:1.2.1’ Step 3: Create RecyclerView Card Layout Card Layout: Card Layout is used to display a list of data. It is the design of a single item of our RecyclerView. For creating a Card Layout navigate to the app > res > layout > Right-Click on it > New > Layout Resource File > Give a name to it(here card_layout). Now we will write a code for our Card Layout of our RecyclerView. Below is the code for the card_layout.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" app:cardBackgroundColor="@color/white" app:cardCornerRadius="8dp" app:cardElevation="8dp" app:cardMaxElevation="10dp" app:cardPreventCornerOverlap="true" app:cardUseCompatPadding="true"> <!-- In the above cardview widget cardelevation property will give elevation to your card view card corner radius will provide radius to your card view card background color will give background color to your card view card max elevation will give the cardview maximum elevation card prevent corner overlap will add padding to CardView on v20 and before to prevent intersections between the Card content and rounded corners. card use compact padding will add padding in API v21+ as well to have the same measurements with previous versions. --> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!--ImageVIew to display our Course Image--> <ImageView android:id="@+id/idIVCourseImage" android:layout_width="100dp" android:layout_height="100dp" android:layout_margin="10dp" android:contentDescription="@string/app_name" android:padding="5dp" android:src="@drawable/gfgimage" /> <!--Text View to display Course Name--> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_toEndOf="@id/idIVCourseImage" android:text="@string/course_name" android:textColor="@color/black" android:textSize="18sp" android:textStyle="bold" /> <!--Text VIew to display COurse Rating--> <!--Image used in present in drawable folder--> <TextView android:id="@+id/idTVCourseRating" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVCourseName" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_toEndOf="@id/idIVCourseImage" android:drawablePadding="2dp" android:text="@string/course_rating" app:drawableStartCompat="@drawable/ic_star" /> </RelativeLayout></androidx.cardview.widget.CardView> Step 4: Create a Model Class for storing data Navigate to the app > java > your apps package name > Right-click on it > New > Java and name the Modal Class(here CourseModel). Model Class will store the data which we will display in our Recycler View. Below is the code for the CourseModel.java file. Java public class CourseModel { private String course_name; private int course_rating; private int course_image; // Constructor public CourseModel(String course_name, int course_rating, int course_image) { this.course_name = course_name; this.course_rating = course_rating; this.course_image = course_image; } // Getter and Setter public String getCourse_name() { return course_name; } public void setCourse_name(String course_name) { this.course_name = course_name; } public int getCourse_rating() { return course_rating; } public void setCourse_rating(int course_rating) { this.course_rating = course_rating; } public int getCourse_image() { return course_image; } public void setCourse_image(int course_image) { this.course_image = course_image; }} Step 5: Create Adapter Class for setting data to items of RecyclerView Navigate to the app > java > your apps package name > Right Click on it > New > Java Class and name your Adapter Class(Here CourseAdapter). Adapter Class in RecyclerView will get the data from your Modal Class and set that data to your item of RecyclerView. Below is the code for the CourseAdapter.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.Viewholder> { private Context context; private ArrayList<CourseModel> courseModelArrayList; // Constructor public CourseAdapter(Context context, ArrayList<CourseModel> courseModelArrayList) { this.context = context; this.courseModelArrayList = courseModelArrayList; } @NonNull @Override public CourseAdapter.Viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // to inflate the layout for each item of recycler view. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false); return new Viewholder(view); } @Override public void onBindViewHolder(@NonNull CourseAdapter.Viewholder holder, int position) { // to set data to textview and imageview of each card layout CourseModel model = courseModelArrayList.get(position); holder.courseNameTV.setText(model.getCourse_name()); holder.courseRatingTV.setText("" + model.getCourse_rating()); holder.courseIV.setImageResource(model.getCourse_image()); } @Override public int getItemCount() { // this method is used for showing number // of card items in recycler view. return courseModelArrayList.size(); } // View holder class for initializing of // your views such as TextView and Imageview. public class Viewholder extends RecyclerView.ViewHolder { private ImageView courseIV; private TextView courseNameTV, courseRatingTV; public Viewholder(@NonNull View itemView) { super(itemView); courseIV = itemView.findViewById(R.id.idIVCourseImage); courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseRatingTV = itemView.findViewById(R.id.idTVCourseRating); } }} Step 6: Now we will move towards creating our RecyclerView For creating of our RecyclerView. Navigate to the app > res > layout > activity_main.xml and add RecyclerView as shown below. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVCourse" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> Step 7: Now we will initialize our RecyclerView in our MainActivity.java Navigate to the app > java > your apps package name > MainActivity.java and initialize your RecyclerView. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private RecyclerView courseRV; // Arraylist for storing data private ArrayList<CourseModel> courseModelArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); courseRV = findViewById(R.id.idRVCourse); // here we have created new array list and added data to it. courseModelArrayList = new ArrayList<>(); courseModelArrayList.add(new CourseModel("DSA in Java", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel("Java Course", 3, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel("C++ COurse", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel("DSA in C++", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel("Kotlin for Android", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel("Java for Android", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel("HTML and CSS", 4, R.drawable.gfgimage)); // we are initializing our adapter class and passing our arraylist to it. CourseAdapter courseAdapter = new CourseAdapter(this, courseModelArrayList); // below line is for setting a layout manager for our recycler view. // here we are creating vertical list so we will provide orientation as vertical LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); // in below two lines we are setting layoutmanager and adapter to our recycler view. courseRV.setLayoutManager(linearLayoutManager); courseRV.setAdapter(courseAdapter); }} Now run the app on Emulator and see the output. Note: Star used as an image is stored in our drawable folder. Strings used are present in our strings.xml. strings.xml: Navigate to the app > res > values > strings.xml to add various strings in your app. drawable: Navigate to the app > res > drawable to add images used for your app. android Picked Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example How to Create and Add Data to SQLite Database in Android? Content Providers in Android with Example Android RecyclerView in Kotlin Flutter - Custom Bottom Navigation Bar Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 25512, "s": 25484, "text": "\n09 Dec, 2020" }, { "code": null, "e": 25828, "s": 25512, "text": "RecyclerView is an extended version of ListView and GridView. It works on the ViewHolder design pattern. With the help of RecyclerView, we can add many extra features to our list of data. Before starting our example on implementation of CardView in RecyclerView. We should know what CardView and RecyclerView mean. " }, { "code": null, "e": 26086, "s": 25828, "text": "CardView: CardView is an extended version of Framelayout which can be used to show items inside the card format. With the help of CardView, we can add radius, elevation to our items of RecyclerView. CardView gives a rich look and feels to our list of data. " }, { "code": null, "e": 26441, "s": 26086, "text": "RecyclerView: RecyclerView is an extended version of ListView. in RecyclerView we can load a large amount of data and items of RecyclerView can have a custom design. RecyclerView works on ViewHolder design pattern so we have to create a Data class that holds data for RecyclerView and a ViewHolder class which will set data to each item of RecyclerView. " }, { "code": null, "e": 26483, "s": 26441, "text": "RecyclerView is divided into 3 sections: " }, { "code": null, "e": 26496, "s": 26483, "text": "Card Layout." }, { "code": null, "e": 26509, "s": 26496, "text": "Modal Class." }, { "code": null, "e": 26528, "s": 26509, "text": "ViewHolder class. " }, { "code": null, "e": 26593, "s": 26528, "text": "Now we will move towards the implementation of our RecyclerView." }, { "code": null, "e": 26760, "s": 26593, "text": "A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 26887, "s": 26760, "text": "So we are creating a simple example for displaying various courses available on GFG in the RecyclerView using a Card Layout. " }, { "code": null, "e": 26916, "s": 26887, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27078, "s": 26916, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 27140, "s": 27078, "text": "Step 2: Add dependency for creating CardView and RecyclerView" }, { "code": null, "e": 27251, "s": 27140, "text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add below dependency in the dependency section. " }, { "code": null, "e": 27311, "s": 27251, "text": "implementation ‘com.google.android.material:material:1.2.1’" }, { "code": null, "e": 27352, "s": 27311, "text": "Step 3: Create RecyclerView Card Layout " }, { "code": null, "e": 27731, "s": 27352, "text": "Card Layout: Card Layout is used to display a list of data. It is the design of a single item of our RecyclerView. For creating a Card Layout navigate to the app > res > layout > Right-Click on it > New > Layout Resource File > Give a name to it(here card_layout). Now we will write a code for our Card Layout of our RecyclerView. Below is the code for the card_layout.xml file." }, { "code": null, "e": 27735, "s": 27731, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" app:cardBackgroundColor=\"@color/white\" app:cardCornerRadius=\"8dp\" app:cardElevation=\"8dp\" app:cardMaxElevation=\"10dp\" app:cardPreventCornerOverlap=\"true\" app:cardUseCompatPadding=\"true\"> <!-- In the above cardview widget cardelevation property will give elevation to your card view card corner radius will provide radius to your card view card background color will give background color to your card view card max elevation will give the cardview maximum elevation card prevent corner overlap will add padding to CardView on v20 and before to prevent intersections between the Card content and rounded corners. card use compact padding will add padding in API v21+ as well to have the same measurements with previous versions. --> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <!--ImageVIew to display our Course Image--> <ImageView android:id=\"@+id/idIVCourseImage\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_margin=\"10dp\" android:contentDescription=\"@string/app_name\" android:padding=\"5dp\" android:src=\"@drawable/gfgimage\" /> <!--Text View to display Course Name--> <TextView android:id=\"@+id/idTVCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_toEndOf=\"@id/idIVCourseImage\" android:text=\"@string/course_name\" android:textColor=\"@color/black\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <!--Text VIew to display COurse Rating--> <!--Image used in present in drawable folder--> <TextView android:id=\"@+id/idTVCourseRating\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVCourseName\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"20dp\" android:layout_toEndOf=\"@id/idIVCourseImage\" android:drawablePadding=\"2dp\" android:text=\"@string/course_rating\" app:drawableStartCompat=\"@drawable/ic_star\" /> </RelativeLayout></androidx.cardview.widget.CardView>", "e": 30548, "s": 27735, "text": null }, { "code": null, "e": 30594, "s": 30548, "text": "Step 4: Create a Model Class for storing data" }, { "code": null, "e": 30848, "s": 30594, "text": "Navigate to the app > java > your apps package name > Right-click on it > New > Java and name the Modal Class(here CourseModel). Model Class will store the data which we will display in our Recycler View. Below is the code for the CourseModel.java file." }, { "code": null, "e": 30853, "s": 30848, "text": "Java" }, { "code": "public class CourseModel { private String course_name; private int course_rating; private int course_image; // Constructor public CourseModel(String course_name, int course_rating, int course_image) { this.course_name = course_name; this.course_rating = course_rating; this.course_image = course_image; } // Getter and Setter public String getCourse_name() { return course_name; } public void setCourse_name(String course_name) { this.course_name = course_name; } public int getCourse_rating() { return course_rating; } public void setCourse_rating(int course_rating) { this.course_rating = course_rating; } public int getCourse_image() { return course_image; } public void setCourse_image(int course_image) { this.course_image = course_image; }}", "e": 31736, "s": 30853, "text": null }, { "code": null, "e": 31808, "s": 31736, "text": "Step 5: Create Adapter Class for setting data to items of RecyclerView " }, { "code": null, "e": 32191, "s": 31808, "text": "Navigate to the app > java > your apps package name > Right Click on it > New > Java Class and name your Adapter Class(Here CourseAdapter). Adapter Class in RecyclerView will get the data from your Modal Class and set that data to your item of RecyclerView. Below is the code for the CourseAdapter.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 32196, "s": 32191, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.Viewholder> { private Context context; private ArrayList<CourseModel> courseModelArrayList; // Constructor public CourseAdapter(Context context, ArrayList<CourseModel> courseModelArrayList) { this.context = context; this.courseModelArrayList = courseModelArrayList; } @NonNull @Override public CourseAdapter.Viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // to inflate the layout for each item of recycler view. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false); return new Viewholder(view); } @Override public void onBindViewHolder(@NonNull CourseAdapter.Viewholder holder, int position) { // to set data to textview and imageview of each card layout CourseModel model = courseModelArrayList.get(position); holder.courseNameTV.setText(model.getCourse_name()); holder.courseRatingTV.setText(\"\" + model.getCourse_rating()); holder.courseIV.setImageResource(model.getCourse_image()); } @Override public int getItemCount() { // this method is used for showing number // of card items in recycler view. return courseModelArrayList.size(); } // View holder class for initializing of // your views such as TextView and Imageview. public class Viewholder extends RecyclerView.ViewHolder { private ImageView courseIV; private TextView courseNameTV, courseRatingTV; public Viewholder(@NonNull View itemView) { super(itemView); courseIV = itemView.findViewById(R.id.idIVCourseImage); courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseRatingTV = itemView.findViewById(R.id.idTVCourseRating); } }}", "e": 34373, "s": 32196, "text": null }, { "code": null, "e": 34432, "s": 34373, "text": "Step 6: Now we will move towards creating our RecyclerView" }, { "code": null, "e": 34608, "s": 34432, "text": "For creating of our RecyclerView. Navigate to the app > res > layout > activity_main.xml and add RecyclerView as shown below. Below is the code for the activity_main.xml file." }, { "code": null, "e": 34612, "s": 34608, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </RelativeLayout>", "e": 35085, "s": 34612, "text": null }, { "code": null, "e": 35158, "s": 35085, "text": "Step 7: Now we will initialize our RecyclerView in our MainActivity.java" }, { "code": null, "e": 35388, "s": 35158, "text": "Navigate to the app > java > your apps package name > MainActivity.java and initialize your RecyclerView. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 35393, "s": 35388, "text": "Java" }, { "code": "import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private RecyclerView courseRV; // Arraylist for storing data private ArrayList<CourseModel> courseModelArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); courseRV = findViewById(R.id.idRVCourse); // here we have created new array list and added data to it. courseModelArrayList = new ArrayList<>(); courseModelArrayList.add(new CourseModel(\"DSA in Java\", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel(\"Java Course\", 3, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel(\"C++ COurse\", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel(\"DSA in C++\", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel(\"Kotlin for Android\", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel(\"Java for Android\", 4, R.drawable.gfgimage)); courseModelArrayList.add(new CourseModel(\"HTML and CSS\", 4, R.drawable.gfgimage)); // we are initializing our adapter class and passing our arraylist to it. CourseAdapter courseAdapter = new CourseAdapter(this, courseModelArrayList); // below line is for setting a layout manager for our recycler view. // here we are creating vertical list so we will provide orientation as vertical LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); // in below two lines we are setting layoutmanager and adapter to our recycler view. courseRV.setLayoutManager(linearLayoutManager); courseRV.setAdapter(courseAdapter); }}", "e": 37410, "s": 35393, "text": null }, { "code": null, "e": 37458, "s": 37410, "text": "Now run the app on Emulator and see the output." }, { "code": null, "e": 37465, "s": 37458, "text": "Note: " }, { "code": null, "e": 37566, "s": 37465, "text": "Star used as an image is stored in our drawable folder. Strings used are present in our strings.xml." }, { "code": null, "e": 37665, "s": 37566, "text": "strings.xml: Navigate to the app > res > values > strings.xml to add various strings in your app. " }, { "code": null, "e": 37747, "s": 37665, "text": "drawable: Navigate to the app > res > drawable to add images used for your app. " }, { "code": null, "e": 37755, "s": 37747, "text": "android" }, { "code": null, "e": 37762, "s": 37755, "text": "Picked" }, { "code": null, "e": 37786, "s": 37762, "text": "Technical Scripter 2020" }, { "code": null, "e": 37794, "s": 37786, "text": "Android" }, { "code": null, "e": 37799, "s": 37794, "text": "Java" }, { "code": null, "e": 37818, "s": 37799, "text": "Technical Scripter" }, { "code": null, "e": 37823, "s": 37818, "text": "Java" }, { "code": null, "e": 37831, "s": 37823, "text": "Android" }, { "code": null, "e": 37929, "s": 37831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37938, "s": 37929, "text": "Comments" }, { "code": null, "e": 37951, "s": 37938, "text": "Old Comments" }, { "code": null, "e": 37994, "s": 37951, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 38052, "s": 37994, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 38094, "s": 38052, "text": "Content Providers in Android with Example" }, { "code": null, "e": 38125, "s": 38094, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 38164, "s": 38125, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 38179, "s": 38164, "text": "Arrays in Java" }, { "code": null, "e": 38223, "s": 38179, "text": "Split() String method in Java with examples" }, { "code": null, "e": 38245, "s": 38223, "text": "For-each loop in Java" }, { "code": null, "e": 38281, "s": 38245, "text": "Arrays.sort() in Java with examples" } ]
How to find the number of levels in R for a factor column?
To find the number of levels in R for a factor column, we can use length function along with unique function. For example, if we have a data frame called df that contains a factor column X then we can find the number of levels in the factor column using the command − length(unique(df$X)) Consider the below data frame − Live Demo x1<-sample(c("A","B","C"),20,replace=TRUE) y1<-sample(0:9,20,replace=TRUE) df1<-data.frame(x1,y1) df1 x1 y1 1 C 8 2 B 9 3 B 2 4 A 7 5 A 8 6 C 4 7 B 0 8 C 3 9 B 3 10 A 5 11 A 8 12 B 0 13 A 6 14 C 2 15 A 4 16 B 7 17 A 9 18 B 1 19 B 3 20 A 5 Finding the number of levels in column x1 − length(unique(df1$x1)) [1] 3 Live Demo x2<-sample(c("id1","id2","id3","id4"),20,replace=TRUE) y2<-rnorm(20,1,0.05) df2<-data.frame(x2,y2) df2 x2 y2 1 id2 1.0582275 2 id4 0.8763659 3 id4 1.0091340 4 id1 1.0087233 5 id1 1.0022543 6 id3 0.9682852 7 id3 0.9458475 8 id2 1.0329383 9 id3 0.9890525 10 id1 0.9814830 11 id4 0.9732973 12 id1 1.0644264 13 id3 0.9328492 14 id1 0.9064330 15 id2 0.9781466 16 id2 0.9633579 17 id1 0.9985626 18 id4 1.0428324 19 id4 1.0047497 20 id4 0.9717654 Finding the number of levels in column x2 − length(unique(df2$x2)) [1] 4
[ { "code": null, "e": 1330, "s": 1062, "text": "To find the number of levels in R for a factor column, we can use length function along with unique function. For example, if we have a data frame called df that contains a factor column X then we can find the number of levels in the factor column using the command −" }, { "code": null, "e": 1351, "s": 1330, "text": "length(unique(df$X))" }, { "code": null, "e": 1383, "s": 1351, "text": "Consider the below data frame −" }, { "code": null, "e": 1394, "s": 1383, "text": " Live Demo" }, { "code": null, "e": 1496, "s": 1394, "text": "x1<-sample(c(\"A\",\"B\",\"C\"),20,replace=TRUE)\ny1<-sample(0:9,20,replace=TRUE)\ndf1<-data.frame(x1,y1)\ndf1" }, { "code": null, "e": 1665, "s": 1496, "text": " x1 y1\n1 C 8\n2 B 9\n3 B 2\n4 A 7\n5 A 8\n6 C 4\n7 B 0\n8 C 3\n9 B 3\n10 A 5\n11 A 8\n12 B 0\n13 A 6\n14 C 2\n15 A 4\n16 B 7\n17 A 9\n18 B 1\n19 B 3\n20 A 5" }, { "code": null, "e": 1709, "s": 1665, "text": "Finding the number of levels in column x1 −" }, { "code": null, "e": 1732, "s": 1709, "text": "length(unique(df1$x1))" }, { "code": null, "e": 1738, "s": 1732, "text": "[1] 3" }, { "code": null, "e": 1749, "s": 1738, "text": " Live Demo" }, { "code": null, "e": 1852, "s": 1749, "text": "x2<-sample(c(\"id1\",\"id2\",\"id3\",\"id4\"),20,replace=TRUE)\ny2<-rnorm(20,1,0.05)\ndf2<-data.frame(x2,y2)\ndf2" }, { "code": null, "e": 2225, "s": 1852, "text": " x2 y2\n1 id2 1.0582275\n2 id4 0.8763659\n3 id4 1.0091340\n4 id1 1.0087233\n5 id1 1.0022543\n6 id3 0.9682852\n7 id3 0.9458475\n8 id2 1.0329383\n9 id3 0.9890525\n10 id1 0.9814830\n11 id4 0.9732973\n12 id1 1.0644264\n13 id3 0.9328492\n14 id1 0.9064330\n15 id2 0.9781466\n16 id2 0.9633579\n17 id1 0.9985626\n18 id4 1.0428324\n19 id4 1.0047497\n20 id4 0.9717654" }, { "code": null, "e": 2269, "s": 2225, "text": "Finding the number of levels in column x2 −" }, { "code": null, "e": 2292, "s": 2269, "text": "length(unique(df2$x2))" }, { "code": null, "e": 2298, "s": 2292, "text": "[1] 4" } ]
What is the best way to break from nested loops in JavaScript?
The best way to break from nested loops is to use labels. A label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. You can try to run the following code to implement Label with a break statement to break from nested loops − Live Demo <html> <body> <script> document.write("Entering the loop! <br /> "); outerloop: // This is the label name for (var i = 0; i < 5; i++) { document.write("Outerloop: " + i + "<br />"); innerloop: for(var j = 0; j < 5; j++) { if(j > 3 ) break ; // Quit the innermost loop if(i == 2) break innerloop; // Do the same thing if(i == 4) break outerloop; // Quit the outer loop document.write("Innerloop: " + j + " <br />"); } } document.write("Exiting the loop!<br /> "); </script> </body> </html>
[ { "code": null, "e": 1307, "s": 1062, "text": "The best way to break from nested loops is to use labels. A label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code." }, { "code": null, "e": 1416, "s": 1307, "text": "You can try to run the following code to implement Label with a break statement to break from nested loops −" }, { "code": null, "e": 1426, "s": 1416, "text": "Live Demo" }, { "code": null, "e": 2088, "s": 1426, "text": "<html>\n <body>\n <script>\n document.write(\"Entering the loop! <br /> \");\n outerloop: // This is the label name\n\n for (var i = 0; i < 5; i++) {\n document.write(\"Outerloop: \" + i + \"<br />\");\n innerloop:\n for(var j = 0; j < 5; j++) {\n if(j > 3 ) break ; // Quit the innermost loop\n if(i == 2) break innerloop; // Do the same thing\n if(i == 4) break outerloop; // Quit the outer loop\n document.write(\"Innerloop: \" + j + \" <br />\");\n }\n }\n document.write(\"Exiting the loop!<br /> \");\n </script>\n </body>\n</html>" } ]
Mongoose | findById() Function - GeeksforGeeks
20 May, 2020 The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command. Installation of mongoose module: You can visit the link Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js You can visit the link Install mongoose module. You can install this package by using this command.npm install mongoose npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose npm version mongoose After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js node index.js Filename: index.js const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Finding a document whose id=5ebadc45a99bde77b2efb20evar id = '5ebadc45a99bde77b2efb20e';User.findById(id, function (err, docs) { if (err){ console.log(err); } else{ console.log("Result : ", docs); }}); Steps to run the program: The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.js The project structure will look like this: Make sure you have install mongoose module using following command:npm install mongoose npm install mongoose Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Run index.js file using below command:node index.js node index.js So this is how you can use the mongoose findById() function to find a single document by its _id field. Mongoose MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example MongoDB - Check the existence of the fields in the specified collection Aggregation in MongoDB MongoDB - db.collection.Find() Method Mongoose Populate() Method Installation of Node.js on Linux Node.js fs.readFileSync() Method How to update Node.js and NPM to next version ? Node.js fs.readFile() Method Node.js fs.writeFile() Method
[ { "code": null, "e": 24128, "s": 24100, "text": "\n20 May, 2020" }, { "code": null, "e": 24274, "s": 24128, "text": "The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command." }, { "code": null, "e": 24307, "s": 24274, "text": "Installation of mongoose module:" }, { "code": null, "e": 24699, "s": 24307, "text": "You can visit the link Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 24819, "s": 24699, "text": "You can visit the link Install mongoose module. You can install this package by using this command.npm install mongoose" }, { "code": null, "e": 24840, "s": 24819, "text": "npm install mongoose" }, { "code": null, "e": 24967, "s": 24840, "text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose" }, { "code": null, "e": 24988, "s": 24967, "text": "npm version mongoose" }, { "code": null, "e": 25135, "s": 24988, "text": "After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 25149, "s": 25135, "text": "node index.js" }, { "code": null, "e": 25168, "s": 25149, "text": "Filename: index.js" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Finding a document whose id=5ebadc45a99bde77b2efb20evar id = '5ebadc45a99bde77b2efb20e';User.findById(id, function (err, docs) { if (err){ console.log(err); } else{ console.log(\"Result : \", docs); }});", "e": 25712, "s": 25168, "text": null }, { "code": null, "e": 25738, "s": 25712, "text": "Steps to run the program:" }, { "code": null, "e": 26100, "s": 25738, "text": "The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.js" }, { "code": null, "e": 26143, "s": 26100, "text": "The project structure will look like this:" }, { "code": null, "e": 26231, "s": 26143, "text": "Make sure you have install mongoose module using following command:npm install mongoose" }, { "code": null, "e": 26252, "s": 26231, "text": "npm install mongoose" }, { "code": null, "e": 26434, "s": 26252, "text": "Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:" }, { "code": null, "e": 26486, "s": 26434, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 26500, "s": 26486, "text": "node index.js" }, { "code": null, "e": 26604, "s": 26500, "text": "So this is how you can use the mongoose findById() function to find a single document by its _id field." }, { "code": null, "e": 26613, "s": 26604, "text": "Mongoose" }, { "code": null, "e": 26621, "s": 26613, "text": "MongoDB" }, { "code": null, "e": 26629, "s": 26621, "text": "Node.js" }, { "code": null, "e": 26646, "s": 26629, "text": "Web Technologies" }, { "code": null, "e": 26744, "s": 26646, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26783, "s": 26744, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 26855, "s": 26783, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 26878, "s": 26855, "text": "Aggregation in MongoDB" }, { "code": null, "e": 26916, "s": 26878, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 26943, "s": 26916, "text": "Mongoose Populate() Method" }, { "code": null, "e": 26976, "s": 26943, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27009, "s": 26976, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 27057, "s": 27009, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27086, "s": 27057, "text": "Node.js fs.readFile() Method" } ]
Rust - Iterator and Closure
In this chapter, we will learn how iterators and closures work in RUST. An iterator helps to iterate over a collection of values such as arrays, vectors, maps, etc. Iterators implement the Iterator trait that is defined in the Rust standard library. The iter() method returns an iterator object of the collection. Values in an iterator object are called items. The next() method of the iterator can be used to traverse through the items. The next() method returns a value None when it reaches the end of the collection. The following example uses an iterator to read values from an array. fn main() { //declare an array let a = [10,20,30]; let mut iter = a.iter(); // fetch an iterator object for the array println!("{:?}",iter); //fetch individual values from the iterator object println!("{:?}",iter.next()); println!("{:?}",iter.next()); println!("{:?}",iter.next()); println!("{:?}",iter.next()); } Iter([10, 20, 30]) Some(10) Some(20) Some(30) None If a collection like array or Vector implements Iterator trait then it can be traversed using the for...in syntax as shown below- fn main() { let a = [10,20,30]; let iter = a.iter(); for data in iter{ print!("{}\t",data); } } 10 20 30 The following 3 methods return an iterator object from a collection, where T represents the elements in a collection. iter() gives an iterator over &T(reference to T) into_iter() gives an iterator over T iter_mut() gives an iterator over &mut T The iter() function uses the concept of borrowing. It returns a reference to each element of the collection, leaving the collection untouched and available for reuse after the loop. fn main() { let names = vec!["Kannan", "Mohtashim", "Kiran"]; for name in names.iter() { match name { &"Mohtashim" => println!("There is a rustacean among us!"), _ => println!("Hello {}", name), } } println!("{:?}",names); // reusing the collection after iteration } Hello Kannan There is a rustacean among us! Hello Kiran ["Kannan", "Mohtashim", "Kiran"] This function uses the concept of ownership. It moves values in the collection into an iter object, i.e., the collection is consumed and it is no longer available for reuse. fn main(){ let names = vec!["Kannan", "Mohtashim", "Kiran"]; for name in names.into_iter() { match name { "Mohtashim" => println!("There is a rustacean among us!"), _ => println!("Hello {}", name), } } // cannot reuse the collection after iteration //println!("{:?}",names); //Error:Cannot access after ownership move } Hello Kannan There is a rustacean among us! Hello Kiran This function is like the iter() function. However, this function can modify elements within the collection. fn main() { let mut names = vec!["Kannan", "Mohtashim", "Kiran"]; for name in names.iter_mut() { match name { &mut "Mohtashim" => println!("There is a rustacean among us!"), _ => println!("Hello {}", name), } } println!("{:?}",names); //// reusing the collection after iteration } Hello Kannan There is a rustacean among us! Hello Kiran ["Kannan", "Mohtashim", "Kiran"] Closure refers to a function within another function. These are anonymous functions – functions without a name. Closure can be used to assign a function to a variable. This allows a program to pass a function as a parameter to other functions. Closure is also known as an inline function. Variables in the outer function can be accessed by inline functions. A closure definition may optionally have parameters. Parameters are enclosed within two vertical bars. let closure_function = |parameter| { //logic } The syntax invoking a Closure implements Fn traits. So, it can be invoked with () syntax. closure_function(parameter); //invoking The following example defines a closure is_even within the function main(). The closure returns true if a number is even and returns false if the number is odd. fn main(){ let is_even = |x| { x%2==0 }; let no = 13; println!("{} is even ? {}",no,is_even(no)); } 13 is even ? false fn main(){ let val = 10; // declared outside let closure2 = |x| { x + val //inner function accessing outer fn variable }; println!("{}",closure2(2)); } The main() function declares a variable val and a closure. The closure accesses the variable declared in the outer function main(). 12 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2159, "s": 2087, "text": "In this chapter, we will learn how iterators and closures work in RUST." }, { "code": null, "e": 2607, "s": 2159, "text": "An iterator helps to iterate over a collection of values such as arrays, vectors, maps, etc. Iterators implement the Iterator trait that is defined in the Rust standard library. The iter() method returns an iterator object of the collection. Values in an iterator object are called items. The next() method of the iterator can be used to traverse through the items. The next() method returns a value None when it reaches the end of the collection." }, { "code": null, "e": 2676, "s": 2607, "text": "The following example uses an iterator to read values from an array." }, { "code": null, "e": 3023, "s": 2676, "text": "fn main() {\n //declare an array\n let a = [10,20,30];\n\n let mut iter = a.iter(); \n // fetch an iterator object for the array\n println!(\"{:?}\",iter);\n\n //fetch individual values from the iterator object\n println!(\"{:?}\",iter.next());\n println!(\"{:?}\",iter.next());\n println!(\"{:?}\",iter.next());\n println!(\"{:?}\",iter.next());\n}" }, { "code": null, "e": 3075, "s": 3023, "text": "Iter([10, 20, 30])\nSome(10)\nSome(20)\nSome(30)\nNone\n" }, { "code": null, "e": 3206, "s": 3075, "text": "If a collection like array or Vector implements Iterator trait then it can be traversed using the for...in syntax as shown below-" }, { "code": null, "e": 3321, "s": 3206, "text": "fn main() {\n let a = [10,20,30];\n let iter = a.iter();\n for data in iter{\n print!(\"{}\\t\",data);\n }\n}\n" }, { "code": null, "e": 3331, "s": 3321, "text": "10 20 30\n" }, { "code": null, "e": 3449, "s": 3331, "text": "The following 3 methods return an iterator object from a collection, where T represents the elements in a collection." }, { "code": null, "e": 3456, "s": 3449, "text": "iter()" }, { "code": null, "e": 3498, "s": 3456, "text": "gives an iterator over &T(reference to T)" }, { "code": null, "e": 3510, "s": 3498, "text": "into_iter()" }, { "code": null, "e": 3535, "s": 3510, "text": "gives an iterator over T" }, { "code": null, "e": 3546, "s": 3535, "text": "iter_mut()" }, { "code": null, "e": 3576, "s": 3546, "text": "gives an iterator over &mut T" }, { "code": null, "e": 3758, "s": 3576, "text": "The iter() function uses the concept of borrowing. It returns a reference to each element of the collection, leaving the collection untouched and available for reuse after the loop." }, { "code": null, "e": 4071, "s": 3758, "text": "fn main() {\n let names = vec![\"Kannan\", \"Mohtashim\", \"Kiran\"];\n for name in names.iter() {\n match name {\n &\"Mohtashim\" => println!(\"There is a rustacean among us!\"),\n _ => println!(\"Hello {}\", name),\n }\n }\n println!(\"{:?}\",names); \n // reusing the collection after iteration\n}" }, { "code": null, "e": 4161, "s": 4071, "text": "Hello Kannan\nThere is a rustacean among us!\nHello Kiran\n[\"Kannan\", \"Mohtashim\", \"Kiran\"]\n" }, { "code": null, "e": 4335, "s": 4161, "text": "This function uses the concept of ownership. It moves values in the collection into an iter object, i.e., the collection is consumed and it is no longer available for reuse." }, { "code": null, "e": 4704, "s": 4335, "text": "fn main(){\n let names = vec![\"Kannan\", \"Mohtashim\", \"Kiran\"];\n for name in names.into_iter() {\n match name {\n \"Mohtashim\" => println!(\"There is a rustacean among us!\"),\n _ => println!(\"Hello {}\", name),\n }\n }\n // cannot reuse the collection after iteration\n //println!(\"{:?}\",names); \n //Error:Cannot access after ownership move\n}" }, { "code": null, "e": 4761, "s": 4704, "text": "Hello Kannan\nThere is a rustacean among us!\nHello Kiran\n" }, { "code": null, "e": 4870, "s": 4761, "text": "This function is like the iter() function. However, this function can modify elements within the collection." }, { "code": null, "e": 5196, "s": 4870, "text": "fn main() {\n let mut names = vec![\"Kannan\", \"Mohtashim\", \"Kiran\"];\n for name in names.iter_mut() {\n match name {\n &mut \"Mohtashim\" => println!(\"There is a rustacean among us!\"),\n _ => println!(\"Hello {}\", name),\n }\n }\n println!(\"{:?}\",names);\n //// reusing the collection after iteration\n}" }, { "code": null, "e": 5286, "s": 5196, "text": "Hello Kannan\nThere is a rustacean among us!\nHello Kiran\n[\"Kannan\", \"Mohtashim\", \"Kiran\"]\n" }, { "code": null, "e": 5644, "s": 5286, "text": "Closure refers to a function within another function. These are anonymous functions – functions without a name. Closure can be used to assign a function to a variable. This allows a program to pass a function as a parameter to other functions. Closure is also known as an inline function. Variables in the outer function can be accessed by inline functions." }, { "code": null, "e": 5747, "s": 5644, "text": "A closure definition may optionally have parameters. Parameters are enclosed within two vertical bars." }, { "code": null, "e": 5798, "s": 5747, "text": "let closure_function = |parameter| {\n //logic\n}\n" }, { "code": null, "e": 5888, "s": 5798, "text": "The syntax invoking a Closure implements Fn traits. So, it can be invoked with () syntax." }, { "code": null, "e": 5932, "s": 5888, "text": "closure_function(parameter); //invoking\n" }, { "code": null, "e": 6093, "s": 5932, "text": "The following example defines a closure is_even within the function main(). The closure returns true if a number is even and returns false if the number is odd." }, { "code": null, "e": 6211, "s": 6093, "text": "fn main(){\n let is_even = |x| {\n x%2==0\n };\n let no = 13;\n println!(\"{} is even ? {}\",no,is_even(no));\n}" }, { "code": null, "e": 6231, "s": 6211, "text": "13 is even ? false\n" }, { "code": null, "e": 6405, "s": 6231, "text": "fn main(){\n let val = 10; \n // declared outside\n let closure2 = |x| {\n x + val //inner function accessing outer fn variable\n };\n println!(\"{}\",closure2(2));\n}" }, { "code": null, "e": 6537, "s": 6405, "text": "The main() function declares a variable val and a closure. The closure accesses the variable declared in the outer function main()." }, { "code": null, "e": 6541, "s": 6537, "text": "12\n" }, { "code": null, "e": 6576, "s": 6541, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6599, "s": 6576, "text": " Stone River ELearning" }, { "code": null, "e": 6631, "s": 6599, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 6642, "s": 6631, "text": " Ken Burke" }, { "code": null, "e": 6649, "s": 6642, "text": " Print" }, { "code": null, "e": 6660, "s": 6649, "text": " Add Notes" } ]
Maximum distinct elements after removing k elements - GeeksforGeeks
17 Feb, 2022 Given an array arr[] containing n elements. The problem is to find the maximum number of distinct elements (non-repeating) after removing k elements from the array. Note: 1 <= k <= n.Examples: Input : arr[] = {5, 7, 5, 5, 1, 2, 2}, k = 3 Output : 4 Remove 2 occurrences of element 5 and 1 occurrence of element 2. Input : arr[] = {1, 2, 3, 4, 5, 6, 7}, k = 5 Output : 2 Input : arr[] = {1, 2, 2, 2}, k = 1 Output : 1 Approach: Following are the steps: 1. Make a multi set from the given array. 2. During making this multiset check if the current element is present or not in multiset, if it is already present then simply reduce the k value and donot insert in the multiset. 3. If k becomes 0 then simply just put values in multiset. 4. After traversing the whole given array, a) if k is not equal to zero then it means the multiset is consist of only unique elements and we have to remove any of the k elements from the multiset to make k=0, so in this case the answer will be size of multiset minus k value at that time. b) if k is equal to zero then it means there may be duplicate values present in the multiset so put all the values in a set and the size of this set will be the number of distinct elements after removing k elements C++ Java Javascript // CPP implementation of the above approach#include <bits/stdc++.h>using namespace std; // function to find maximum distinct elements// after removing k elementsint maxDistinctNum(int a[], int n, int k){ int i; multiset<int> s; // making multiset from given array for(i=0;i<n;i++){ if(s.find(a[i])==s.end()||k==0) s.insert(a[i]); else { k--; } } if(k!=0) return s.size()-k; else{ set<int> st; for(auto it:s){ st.insert(it); } return st.size(); }} // Driver Codeint main(){ int arr[] = { 5, 7, 5, 5, 1, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; // Function Call cout << "Maximum distinct elements = " << maxDistinctNum(arr, n, k); return 0;} // Java implementation of the// above approachimport java.util.*;class GFG{ // Function to find maximum// distinct elements after// removing k elementsstatic int maxDistinctNum(int arr[], int n, int k){ HashMap<Integer, Integer> numToFreq = new HashMap<>(); // Build frequency map for(int i = 0 ; i < n ; i++) { numToFreq.put(arr[i], numToFreq.getOrDefault(arr[i], 0) + 1); } int result = 0; // Min-heap PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(); // Add all number with freq=1 to // result and push others to minHeap for(Map.Entry<Integer, Integer> p : numToFreq.entrySet()) { if(p.getValue() == 1) ++result; else minHeap.add(p.getValue()); } // Perform k operations while(k != 0 && !minHeap.isEmpty()) { // Pop the top() element Integer t = minHeap.poll(); // Increment Result if(t == 1) { ++result; } // Reduce t and k // Push it again else { --t; --k; minHeap.add(t); } } // Return result return result;} // Driver codepublic static void main(String[] args){ int arr[] = {5, 7, 5, 5, 1, 2, 2}; int n = arr.length; int k = 3; // Function Call System.out.println("Maximum distinct elements = " + maxDistinctNum(arr, n, k));}} // This code is contributed by rutvik_56 <script> // Javascript implementation of the above approach // function to find maximum distinct elements// after removing k elementsfunction maxDistinctNum(a, n, k){ var i; var s = []; // making multiset from given array for(i=0;i<n;i++){ if(!s.includes(a[i])||k==0) s.push(a[i]); else { k--; } } if(k!=0) return s.size-k; else{ var st = new Set(); s.forEach(element => { st.add(element); }); return st.size; }} // Driver Codevar arr = [5, 7, 5, 5, 1, 2, 2];var n = arr.length;var k = 3; // Function Calldocument.write( "Maximum distinct elements = " + maxDistinctNum(arr, n, k)); // This code is contributed by itsok.</script> Maximum distinct elements = 4 Output: Maximum distinct elements = 4 Time Complexity: O(k*logd), where d is the number of distinct elements in the given array. Another Approach: Follow the below steps, to solve this problem: Find the Number of distinct Toys. Sum of number of element except one element form every distinct Toys. Check sum if greater than or equal K then Return all distinct element. Otherwise decrement number of distinct element and to fill K. Return Size of vector. Below is the implementation of the above approach: C++ // C++ code for the above approach#include <bits/stdc++.h>using namespace std;// function to return maximum number of distinct Toysint MaxNumber(int arr[], int N, int K){ // Count Number of distinct Number unordered_map<int, int> mp; for (int i = 0; i < N; i++) { mp[arr[i]]++; } // push them into vector vector<int> v1; for (auto i : mp) { v1.push_back(i.second); } // add number of element except one element from every // distinct element int temp = 0; for (int i = 0; i < v1.size(); i++) { temp += v1[i] - 1; } // check if it is greater then simply return size of // vector otherwise decrement size of vector to fill k if (K <= temp) { return v1.size(); } else { K = K - temp; int ans = v1.size(); while (K) { ans--; K--; } return ans; }}// Driver Codeint main(){ // array int arr[] = { 10, 10, 10, 50, 50 }; int K = 3; // size of array int N = sizeof(arr) / sizeof(arr[0]); cout << MaxNumber(arr, N, K) << endl; return 0;} 2 Time Complexity: O(N) Space Complexity: O(N) rachana soma sonugiri rutvik_56 deepanshujindal634 itsok anikakapoor sauarbhyadav varshagumber28 sagar0719kumar simmytarika5 cpp-priority-queue Arrays Hash Heap Arrays Hash Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 24431, "s": 24403, "text": "\n17 Feb, 2022" }, { "code": null, "e": 24625, "s": 24431, "text": "Given an array arr[] containing n elements. The problem is to find the maximum number of distinct elements (non-repeating) after removing k elements from the array. Note: 1 <= k <= n.Examples: " }, { "code": null, "e": 24851, "s": 24625, "text": "Input : arr[] = {5, 7, 5, 5, 1, 2, 2}, k = 3\nOutput : 4\nRemove 2 occurrences of element 5 and\n1 occurrence of element 2.\n\nInput : arr[] = {1, 2, 3, 4, 5, 6, 7}, k = 5\nOutput : 2\n\nInput : arr[] = {1, 2, 2, 2}, k = 1\nOutput : 1" }, { "code": null, "e": 24887, "s": 24851, "text": "Approach: Following are the steps: " }, { "code": null, "e": 24929, "s": 24887, "text": "1. Make a multi set from the given array." }, { "code": null, "e": 25110, "s": 24929, "text": "2. During making this multiset check if the current element is present or not in multiset, if it is already present then simply reduce the k value and donot insert in the multiset." }, { "code": null, "e": 25169, "s": 25110, "text": "3. If k becomes 0 then simply just put values in multiset." }, { "code": null, "e": 25213, "s": 25169, "text": "4. After traversing the whole given array, " }, { "code": null, "e": 25466, "s": 25213, "text": " a) if k is not equal to zero then it means the multiset is consist of only unique elements and we have to remove any of the k elements from the multiset to make k=0, so in this case the answer will be size of multiset minus k value at that time." }, { "code": null, "e": 25689, "s": 25466, "text": " b) if k is equal to zero then it means there may be duplicate values present in the multiset so put all the values in a set and the size of this set will be the number of distinct elements after removing k elements" }, { "code": null, "e": 25693, "s": 25689, "text": "C++" }, { "code": null, "e": 25698, "s": 25693, "text": "Java" }, { "code": null, "e": 25709, "s": 25698, "text": "Javascript" }, { "code": "// CPP implementation of the above approach#include <bits/stdc++.h>using namespace std; // function to find maximum distinct elements// after removing k elementsint maxDistinctNum(int a[], int n, int k){ int i; multiset<int> s; // making multiset from given array for(i=0;i<n;i++){ if(s.find(a[i])==s.end()||k==0) s.insert(a[i]); else { k--; } } if(k!=0) return s.size()-k; else{ set<int> st; for(auto it:s){ st.insert(it); } return st.size(); }} // Driver Codeint main(){ int arr[] = { 5, 7, 5, 5, 1, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; // Function Call cout << \"Maximum distinct elements = \" << maxDistinctNum(arr, n, k); return 0;}", "e": 26573, "s": 25709, "text": null }, { "code": "// Java implementation of the// above approachimport java.util.*;class GFG{ // Function to find maximum// distinct elements after// removing k elementsstatic int maxDistinctNum(int arr[], int n, int k){ HashMap<Integer, Integer> numToFreq = new HashMap<>(); // Build frequency map for(int i = 0 ; i < n ; i++) { numToFreq.put(arr[i], numToFreq.getOrDefault(arr[i], 0) + 1); } int result = 0; // Min-heap PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(); // Add all number with freq=1 to // result and push others to minHeap for(Map.Entry<Integer, Integer> p : numToFreq.entrySet()) { if(p.getValue() == 1) ++result; else minHeap.add(p.getValue()); } // Perform k operations while(k != 0 && !minHeap.isEmpty()) { // Pop the top() element Integer t = minHeap.poll(); // Increment Result if(t == 1) { ++result; } // Reduce t and k // Push it again else { --t; --k; minHeap.add(t); } } // Return result return result;} // Driver codepublic static void main(String[] args){ int arr[] = {5, 7, 5, 5, 1, 2, 2}; int n = arr.length; int k = 3; // Function Call System.out.println(\"Maximum distinct elements = \" + maxDistinctNum(arr, n, k));}} // This code is contributed by rutvik_56", "e": 27970, "s": 26573, "text": null }, { "code": "<script> // Javascript implementation of the above approach // function to find maximum distinct elements// after removing k elementsfunction maxDistinctNum(a, n, k){ var i; var s = []; // making multiset from given array for(i=0;i<n;i++){ if(!s.includes(a[i])||k==0) s.push(a[i]); else { k--; } } if(k!=0) return s.size-k; else{ var st = new Set(); s.forEach(element => { st.add(element); }); return st.size; }} // Driver Codevar arr = [5, 7, 5, 5, 1, 2, 2];var n = arr.length;var k = 3; // Function Calldocument.write( \"Maximum distinct elements = \" + maxDistinctNum(arr, n, k)); // This code is contributed by itsok.</script>", "e": 28801, "s": 27970, "text": null }, { "code": null, "e": 28831, "s": 28801, "text": "Maximum distinct elements = 4" }, { "code": null, "e": 28841, "s": 28831, "text": "Output: " }, { "code": null, "e": 28871, "s": 28841, "text": "Maximum distinct elements = 4" }, { "code": null, "e": 28962, "s": 28871, "text": "Time Complexity: O(k*logd), where d is the number of distinct elements in the given array." }, { "code": null, "e": 29027, "s": 28962, "text": "Another Approach: Follow the below steps, to solve this problem:" }, { "code": null, "e": 29061, "s": 29027, "text": "Find the Number of distinct Toys." }, { "code": null, "e": 29131, "s": 29061, "text": "Sum of number of element except one element form every distinct Toys." }, { "code": null, "e": 29202, "s": 29131, "text": "Check sum if greater than or equal K then Return all distinct element." }, { "code": null, "e": 29264, "s": 29202, "text": "Otherwise decrement number of distinct element and to fill K." }, { "code": null, "e": 29287, "s": 29264, "text": "Return Size of vector." }, { "code": null, "e": 29338, "s": 29287, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29342, "s": 29338, "text": "C++" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std;// function to return maximum number of distinct Toysint MaxNumber(int arr[], int N, int K){ // Count Number of distinct Number unordered_map<int, int> mp; for (int i = 0; i < N; i++) { mp[arr[i]]++; } // push them into vector vector<int> v1; for (auto i : mp) { v1.push_back(i.second); } // add number of element except one element from every // distinct element int temp = 0; for (int i = 0; i < v1.size(); i++) { temp += v1[i] - 1; } // check if it is greater then simply return size of // vector otherwise decrement size of vector to fill k if (K <= temp) { return v1.size(); } else { K = K - temp; int ans = v1.size(); while (K) { ans--; K--; } return ans; }}// Driver Codeint main(){ // array int arr[] = { 10, 10, 10, 50, 50 }; int K = 3; // size of array int N = sizeof(arr) / sizeof(arr[0]); cout << MaxNumber(arr, N, K) << endl; return 0;}", "e": 30433, "s": 29342, "text": null }, { "code": null, "e": 30435, "s": 30433, "text": "2" }, { "code": null, "e": 30457, "s": 30435, "text": "Time Complexity: O(N)" }, { "code": null, "e": 30480, "s": 30457, "text": "Space Complexity: O(N)" }, { "code": null, "e": 30493, "s": 30480, "text": "rachana soma" }, { "code": null, "e": 30502, "s": 30493, "text": "sonugiri" }, { "code": null, "e": 30512, "s": 30502, "text": "rutvik_56" }, { "code": null, "e": 30531, "s": 30512, "text": "deepanshujindal634" }, { "code": null, "e": 30537, "s": 30531, "text": "itsok" }, { "code": null, "e": 30549, "s": 30537, "text": "anikakapoor" }, { "code": null, "e": 30562, "s": 30549, "text": "sauarbhyadav" }, { "code": null, "e": 30577, "s": 30562, "text": "varshagumber28" }, { "code": null, "e": 30592, "s": 30577, "text": "sagar0719kumar" }, { "code": null, "e": 30605, "s": 30592, "text": "simmytarika5" }, { "code": null, "e": 30624, "s": 30605, "text": "cpp-priority-queue" }, { "code": null, "e": 30631, "s": 30624, "text": "Arrays" }, { "code": null, "e": 30636, "s": 30631, "text": "Hash" }, { "code": null, "e": 30641, "s": 30636, "text": "Heap" }, { "code": null, "e": 30648, "s": 30641, "text": "Arrays" }, { "code": null, "e": 30653, "s": 30648, "text": "Hash" }, { "code": null, "e": 30658, "s": 30653, "text": "Heap" }, { "code": null, "e": 30756, "s": 30658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30765, "s": 30756, "text": "Comments" }, { "code": null, "e": 30778, "s": 30765, "text": "Old Comments" }, { "code": null, "e": 30799, "s": 30778, "text": "Next Greater Element" }, { "code": null, "e": 30824, "s": 30799, "text": "Window Sliding Technique" }, { "code": null, "e": 30851, "s": 30824, "text": "Count pairs with given sum" }, { "code": null, "e": 30900, "s": 30851, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30938, "s": 30900, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30974, "s": 30938, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 31005, "s": 30974, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 31032, "s": 31005, "text": "Count pairs with given sum" }, { "code": null, "e": 31066, "s": 31032, "text": "Hashing | Set 3 (Open Addressing)" } ]
Java Program to convert ASCII code to String
To convert ASCII to string, use the toString() method. Using this method will return the associated character. Let’s say we have the following int value, which works as ASCII for us. int asciiVal = 89; Now, use the toString() method. String str = new Character((char) asciiVal).toString(); Live Demo public class Demo { public static void main(String []args) { int asciiVal = 87; String str = new Character((char) asciiVal).toString(); System.out.println(str); } } W
[ { "code": null, "e": 1173, "s": 1062, "text": "To convert ASCII to string, use the toString() method. Using this method will return the associated character." }, { "code": null, "e": 1245, "s": 1173, "text": "Let’s say we have the following int value, which works as ASCII for us." }, { "code": null, "e": 1264, "s": 1245, "text": "int asciiVal = 89;" }, { "code": null, "e": 1296, "s": 1264, "text": "Now, use the toString() method." }, { "code": null, "e": 1352, "s": 1296, "text": "String str = new Character((char) asciiVal).toString();" }, { "code": null, "e": 1363, "s": 1352, "text": " Live Demo" }, { "code": null, "e": 1552, "s": 1363, "text": "public class Demo {\n public static void main(String []args) {\n int asciiVal = 87;\n String str = new Character((char) asciiVal).toString();\n System.out.println(str);\n }\n}" }, { "code": null, "e": 1554, "s": 1552, "text": "W" } ]
5 Minute Guide to Detecting Holidays in Python | by Dario Radečić | Towards Data Science
If you decide to dive deep into data analysis and want to, for example, analyze purchasing trends, you’ll probably want to construct a new attribute in your dataset having only two possible outcomes — 0 or 1 — is a holiday, isn’t a holiday. Take a moment to think about why this derived variable might be useful. You probably won’t uncover a greater volume of purchases on holidays itself, but how did the sales do in the week leading to the holiday? A whole another animal, isn’t it? Anyway, in today’s rather quick post I want to discuss one Python library I’ve found some time ago — holidays — yes, that’s the name. It allows you to get dates and names of major holidays for specific year(s) and for a specific country. You might be wondering now how many countries does it support, and the answer will positively surprise you — around 50-ish (with the ability to specify individual regions for some countries). You can find the whole list here: pypi.org The goal of this article is to do some exploration of the library and showcase functions you’ll use most often. We’ll create a list of dates for the whole year of 2019, and from there declare another column which will have the value of 1 if there is (or was) a holiday on that date, and 0 otherwise. Before jumping into code you’ll need to install the library, so fire up the terminal and execute the following: pip install holidays Is everything good? I mean it should, it’s only a pip install for Pete’s sake. Nevertheless, let’s do some real stuff now. Ass always, your Notebook should start with imports. Nothing special here, only Numpy, Pandas, Datetime, and yeah, newly installed Holidays library: You probably won’t need Numpy to follow along, but I always like to have it imported. If you open the documentation of Holidays library and scroll down a bit, you’ll see a list of 50-ish supported countries. It’s now very easy to extract holidays, you’ll need to loop over the holidays in the country of interest, and also specify the year(s) of interest: Yeah, it’s that easy. The dates obtained, however, aren’t in desired format. Most of the time you’ll care only the date itself, not what holiday it represents — as you’ll most like have a binary attribute in dataset having the value 1 if the holiday is present and 0 otherwise. The good news is, it’s fairly easy to extract string representation of the dates: Let’s now store all the string representations in a separate list — it will come in handy later: That’s great. Now we can construct a Pandas DataFrame object and play around with those holidays. With Pandas, it’s fairly straightforward to construct a list of dates, let’s say for the whole year of 2019: Great. Now we can construct a DataFrame object from those dates — let’s put them into Dates column: Now here comes a slight problem. The dates look to be stored in a string format, just like our us_holidays list, but that’s not the case. It’s a Timestamp object. The next cell verifies that claim: So let’s explore how to extract only the date as a string, and discard the time information. You’ll want to convert Timestamp to a string, and then split the string and keep only the left portion (date information). It’s a fairly straightforward thing to do: Now we can use the power of the list comprehensions to construct a binary list, having the value of 1 if the date is holiday and 0 otherwise. I’ve decided to wrap everything into print() and specify a different ending parameter, so the whole list can fit on screen: And now, finally, by the same principle, you can add that list as a column in previously created Pandas DataFrame: And you’re pretty much done. You can now proceed further with your analysis. The dataset you have will have more attributes, of course, so this new binary column might come in handy for analysis. Thanks for reading, I hope you can somehow utilize this knowledge in your workflow. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 412, "s": 171, "text": "If you decide to dive deep into data analysis and want to, for example, analyze purchasing trends, you’ll probably want to construct a new attribute in your dataset having only two possible outcomes — 0 or 1 — is a holiday, isn’t a holiday." }, { "code": null, "e": 622, "s": 412, "text": "Take a moment to think about why this derived variable might be useful. You probably won’t uncover a greater volume of purchases on holidays itself, but how did the sales do in the week leading to the holiday?" }, { "code": null, "e": 656, "s": 622, "text": "A whole another animal, isn’t it?" }, { "code": null, "e": 1086, "s": 656, "text": "Anyway, in today’s rather quick post I want to discuss one Python library I’ve found some time ago — holidays — yes, that’s the name. It allows you to get dates and names of major holidays for specific year(s) and for a specific country. You might be wondering now how many countries does it support, and the answer will positively surprise you — around 50-ish (with the ability to specify individual regions for some countries)." }, { "code": null, "e": 1120, "s": 1086, "text": "You can find the whole list here:" }, { "code": null, "e": 1129, "s": 1120, "text": "pypi.org" }, { "code": null, "e": 1429, "s": 1129, "text": "The goal of this article is to do some exploration of the library and showcase functions you’ll use most often. We’ll create a list of dates for the whole year of 2019, and from there declare another column which will have the value of 1 if there is (or was) a holiday on that date, and 0 otherwise." }, { "code": null, "e": 1541, "s": 1429, "text": "Before jumping into code you’ll need to install the library, so fire up the terminal and execute the following:" }, { "code": null, "e": 1562, "s": 1541, "text": "pip install holidays" }, { "code": null, "e": 1685, "s": 1562, "text": "Is everything good? I mean it should, it’s only a pip install for Pete’s sake. Nevertheless, let’s do some real stuff now." }, { "code": null, "e": 1834, "s": 1685, "text": "Ass always, your Notebook should start with imports. Nothing special here, only Numpy, Pandas, Datetime, and yeah, newly installed Holidays library:" }, { "code": null, "e": 1920, "s": 1834, "text": "You probably won’t need Numpy to follow along, but I always like to have it imported." }, { "code": null, "e": 2042, "s": 1920, "text": "If you open the documentation of Holidays library and scroll down a bit, you’ll see a list of 50-ish supported countries." }, { "code": null, "e": 2190, "s": 2042, "text": "It’s now very easy to extract holidays, you’ll need to loop over the holidays in the country of interest, and also specify the year(s) of interest:" }, { "code": null, "e": 2468, "s": 2190, "text": "Yeah, it’s that easy. The dates obtained, however, aren’t in desired format. Most of the time you’ll care only the date itself, not what holiday it represents — as you’ll most like have a binary attribute in dataset having the value 1 if the holiday is present and 0 otherwise." }, { "code": null, "e": 2550, "s": 2468, "text": "The good news is, it’s fairly easy to extract string representation of the dates:" }, { "code": null, "e": 2647, "s": 2550, "text": "Let’s now store all the string representations in a separate list — it will come in handy later:" }, { "code": null, "e": 2745, "s": 2647, "text": "That’s great. Now we can construct a Pandas DataFrame object and play around with those holidays." }, { "code": null, "e": 2854, "s": 2745, "text": "With Pandas, it’s fairly straightforward to construct a list of dates, let’s say for the whole year of 2019:" }, { "code": null, "e": 2954, "s": 2854, "text": "Great. Now we can construct a DataFrame object from those dates — let’s put them into Dates column:" }, { "code": null, "e": 3152, "s": 2954, "text": "Now here comes a slight problem. The dates look to be stored in a string format, just like our us_holidays list, but that’s not the case. It’s a Timestamp object. The next cell verifies that claim:" }, { "code": null, "e": 3411, "s": 3152, "text": "So let’s explore how to extract only the date as a string, and discard the time information. You’ll want to convert Timestamp to a string, and then split the string and keep only the left portion (date information). It’s a fairly straightforward thing to do:" }, { "code": null, "e": 3677, "s": 3411, "text": "Now we can use the power of the list comprehensions to construct a binary list, having the value of 1 if the date is holiday and 0 otherwise. I’ve decided to wrap everything into print() and specify a different ending parameter, so the whole list can fit on screen:" }, { "code": null, "e": 3792, "s": 3677, "text": "And now, finally, by the same principle, you can add that list as a column in previously created Pandas DataFrame:" }, { "code": null, "e": 3988, "s": 3792, "text": "And you’re pretty much done. You can now proceed further with your analysis. The dataset you have will have more attributes, of course, so this new binary column might come in handy for analysis." }, { "code": null, "e": 4072, "s": 3988, "text": "Thanks for reading, I hope you can somehow utilize this knowledge in your workflow." } ]
Tk - Selection Widgets
Selection widgets are used to select different options in a Tk application. The list of available selection widgets are as shown below. Widget that has a set of on/off buttons and labels, one of which may be selected. Widget that has a set of on/off buttons and labels, many of which may be selected. Widget that acts as holder for menu items. Widget that displays a list of cells, one or more of which may be selected. A simple Tk example is shown below using selection widgets − #!/usr/bin/wish grid [frame .gender ] grid [label .label1 -text "Male" -textvariable myLabel1 ] grid [radiobutton .gender.maleBtn -text "Male" -variable gender -value "Male" -command "set myLabel1 Male"] -row 1 -column 2 grid [radiobutton .gender.femaleBtn -text "Female" -variable gender -value "Female" -command "set myLabel1 Female"] -row 1 -column 3 .gender.maleBtn select grid [label .myLabel2 -text "Range 1 not selected" -textvariable myLabelValue2 ] grid [checkbutton .chk1 -text "Range 1" -variable occupied1 -command {if {$occupied1 } { set myLabelValue2 {Range 1 selected} } else { set myLabelValue2 {Range 1 not selected} } }] proc setLabel {text} { .label configure -text $text } When we run the above program, we will get the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2337, "s": 2201, "text": "Selection widgets are used to select different options in a Tk application. The list of available selection widgets are as shown below." }, { "code": null, "e": 2419, "s": 2337, "text": "Widget that has a set of on/off buttons and labels, one of which may be selected." }, { "code": null, "e": 2502, "s": 2419, "text": "Widget that has a set of on/off buttons and labels, many of which may be selected." }, { "code": null, "e": 2545, "s": 2502, "text": "Widget that acts as holder for menu items." }, { "code": null, "e": 2621, "s": 2545, "text": "Widget that displays a list of cells, one or more of which may be selected." }, { "code": null, "e": 2682, "s": 2621, "text": "A simple Tk example is shown below using selection widgets −" }, { "code": null, "e": 3400, "s": 2682, "text": "#!/usr/bin/wish\n\ngrid [frame .gender ]\ngrid [label .label1 -text \"Male\" -textvariable myLabel1 ] \ngrid [radiobutton .gender.maleBtn -text \"Male\" -variable gender -value \"Male\"\n -command \"set myLabel1 Male\"] -row 1 -column 2\ngrid [radiobutton .gender.femaleBtn -text \"Female\" -variable gender -value \"Female\"\n -command \"set myLabel1 Female\"] -row 1 -column 3\n.gender.maleBtn select\ngrid [label .myLabel2 -text \"Range 1 not selected\" -textvariable myLabelValue2 ] \ngrid [checkbutton .chk1 -text \"Range 1\" -variable occupied1 -command {if {$occupied1 } {\n set myLabelValue2 {Range 1 selected}\n} else {\n set myLabelValue2 {Range 1 not selected}\n} }]\nproc setLabel {text} {\n .label configure -text $text \n}" }, { "code": null, "e": 3466, "s": 3400, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 3473, "s": 3466, "text": " Print" }, { "code": null, "e": 3484, "s": 3473, "text": " Add Notes" } ]
PyQt5 - Multiple Document Interface
A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden. One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc. MDI (Multiple Document Interface) applications consume lesser memory resources. The sub windows are laid down inside main container with relation to each other. The container widget is called QMdiArea. QMdiArea widget generally occupies the central widget of QMainWondow object. Child windows in this area are instances of QMdiSubWindow class. It is possible to set any QWidget as the internal widget of subWindow object. Sub-windows in the MDI area can be arranged in cascaded or tile fashion. The following table lists important methods of QMdiArea class and QMdiSubWindow class − addSubWindow() Adds a widget as a new subwindow in MDI area removeSubWindow() Removes a widget that is internal widget of a subwindow setActiveSubWindow() Activates a subwindow cascadeSubWindows() Arranges subwindows in MDiArea in a cascaded fashion tileSubWindows() Arranges subwindows in MDiArea in a tiled fashion closeActiveSubWindow() Closes the active subwindow subWindowList() Returns the list of subwindows in MDI Area setWidget() Sets a QWidget as an internal widget of a QMdiSubwindow instance QMdiArea object emits subWindowActivated() signal whereas windowStateChanged() signal is emitted by QMdisubWindow object. In the following example, top level window comprising of QMainWindow has a menu and MdiArea. self.mdi = QMdiArea() self.setCentralWidget(self.mdi) bar = self.menuBar() file = bar.addMenu("File") file.addAction("New") file.addAction("cascade") file.addAction("Tiled") Triggered() signal of the menu is connected to windowaction() function. file.triggered[QAction].connect(self.windowaction) The new action of menu adds a subwindow in MDI area with a title having an incremental number to it. MainWindow.count = MainWindow.count+1 sub = QMdiSubWindow() sub.setWidget(QTextEdit()) sub.setWindowTitle("subwindow"+str(MainWindow.count)) self.mdi.addSubWindow(sub) sub.show() Cascaded and tiled buttons of the menu arrange currently displayed subwindows in cascaded and tiled fashion respectively. The complete code is as follows − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class MainWindow(QMainWindow): count = 0 def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.mdi = QMdiArea() self.setCentralWidget(self.mdi) bar = self.menuBar() file = bar.addMenu("File") file.addAction("New") file.addAction("cascade") file.addAction("Tiled") file.triggered[QAction].connect(self.windowaction) self.setWindowTitle("MDI demo") def windowaction(self, q): print ("triggered") if q.text() == "New": MainWindow.count = MainWindow.count+1 sub = QMdiSubWindow() sub.setWidget(QTextEdit()) sub.setWindowTitle("subwindow"+str(MainWindow.count)) self.mdi.addSubWindow(sub) sub.show() if q.text() == "cascade": self.mdi.cascadeSubWindows() if q.text() == "Tiled": self.mdi.tileSubWindows() def main(): app = QApplication(sys.argv) ex = MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() Run above code and three windows in cascased and tiled formation − 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2178, "s": 1963, "text": "A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden." }, { "code": null, "e": 2417, "s": 2178, "text": "One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc." }, { "code": null, "e": 2619, "s": 2417, "text": "MDI (Multiple Document Interface) applications consume lesser memory resources. The sub windows are laid down inside main container with relation to each other. The container widget is called QMdiArea." }, { "code": null, "e": 2912, "s": 2619, "text": "QMdiArea widget generally occupies the central widget of QMainWondow object. Child windows in this area are instances of QMdiSubWindow class. It is possible to set any QWidget as the internal widget of subWindow object. Sub-windows in the MDI area can be arranged in cascaded or tile fashion." }, { "code": null, "e": 3000, "s": 2912, "text": "The following table lists important methods of QMdiArea class and QMdiSubWindow class −" }, { "code": null, "e": 3015, "s": 3000, "text": "addSubWindow()" }, { "code": null, "e": 3060, "s": 3015, "text": "Adds a widget as a new subwindow in MDI area" }, { "code": null, "e": 3078, "s": 3060, "text": "removeSubWindow()" }, { "code": null, "e": 3134, "s": 3078, "text": "Removes a widget that is internal widget of a subwindow" }, { "code": null, "e": 3155, "s": 3134, "text": "setActiveSubWindow()" }, { "code": null, "e": 3177, "s": 3155, "text": "Activates a subwindow" }, { "code": null, "e": 3197, "s": 3177, "text": "cascadeSubWindows()" }, { "code": null, "e": 3250, "s": 3197, "text": "Arranges subwindows in MDiArea in a cascaded fashion" }, { "code": null, "e": 3267, "s": 3250, "text": "tileSubWindows()" }, { "code": null, "e": 3317, "s": 3267, "text": "Arranges subwindows in MDiArea in a tiled fashion" }, { "code": null, "e": 3340, "s": 3317, "text": "closeActiveSubWindow()" }, { "code": null, "e": 3368, "s": 3340, "text": "Closes the active subwindow" }, { "code": null, "e": 3384, "s": 3368, "text": "subWindowList()" }, { "code": null, "e": 3427, "s": 3384, "text": "Returns the list of subwindows in MDI Area" }, { "code": null, "e": 3439, "s": 3427, "text": "setWidget()" }, { "code": null, "e": 3504, "s": 3439, "text": "Sets a QWidget as an internal widget of a QMdiSubwindow instance" }, { "code": null, "e": 3626, "s": 3504, "text": "QMdiArea object emits subWindowActivated() signal whereas windowStateChanged() signal is emitted by QMdisubWindow object." }, { "code": null, "e": 3719, "s": 3626, "text": "In the following example, top level window comprising of QMainWindow has a menu and MdiArea." }, { "code": null, "e": 3894, "s": 3719, "text": "self.mdi = QMdiArea()\nself.setCentralWidget(self.mdi)\nbar = self.menuBar()\nfile = bar.addMenu(\"File\")\n\nfile.addAction(\"New\")\nfile.addAction(\"cascade\")\nfile.addAction(\"Tiled\")" }, { "code": null, "e": 3966, "s": 3894, "text": "Triggered() signal of the menu is connected to windowaction() function." }, { "code": null, "e": 4018, "s": 3966, "text": "file.triggered[QAction].connect(self.windowaction)\n" }, { "code": null, "e": 4119, "s": 4018, "text": "The new action of menu adds a subwindow in MDI area with a title having an incremental number to it." }, { "code": null, "e": 4298, "s": 4119, "text": "MainWindow.count = MainWindow.count+1\nsub = QMdiSubWindow()\nsub.setWidget(QTextEdit())\nsub.setWindowTitle(\"subwindow\"+str(MainWindow.count))\nself.mdi.addSubWindow(sub)\nsub.show()" }, { "code": null, "e": 4420, "s": 4298, "text": "Cascaded and tiled buttons of the menu arrange currently displayed subwindows in cascaded and tiled fashion respectively." }, { "code": null, "e": 4454, "s": 4420, "text": "The complete code is as follows −" }, { "code": null, "e": 5592, "s": 4454, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass MainWindow(QMainWindow):\n count = 0\n\n def __init__(self, parent = None):\n super(MainWindow, self).__init__(parent)\n self.mdi = QMdiArea()\n self.setCentralWidget(self.mdi)\n bar = self.menuBar()\n\n file = bar.addMenu(\"File\")\n file.addAction(\"New\")\n file.addAction(\"cascade\")\n file.addAction(\"Tiled\")\n file.triggered[QAction].connect(self.windowaction)\n self.setWindowTitle(\"MDI demo\")\n\n def windowaction(self, q):\n print (\"triggered\")\n \n if q.text() == \"New\":\n MainWindow.count = MainWindow.count+1\n sub = QMdiSubWindow()\n sub.setWidget(QTextEdit())\n sub.setWindowTitle(\"subwindow\"+str(MainWindow.count))\n self.mdi.addSubWindow(sub)\n sub.show()\n\n if q.text() == \"cascade\":\n self.mdi.cascadeSubWindows()\n\n if q.text() == \"Tiled\":\n self.mdi.tileSubWindows()\n\ndef main():\n app = QApplication(sys.argv)\n ex = MainWindow()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 5659, "s": 5592, "text": "Run above code and three windows in cascased and tiled formation −" }, { "code": null, "e": 5696, "s": 5659, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 5706, "s": 5696, "text": " ALAA EID" }, { "code": null, "e": 5713, "s": 5706, "text": " Print" }, { "code": null, "e": 5724, "s": 5713, "text": " Add Notes" } ]
Find position of the only set bit - GeeksforGeeks
21 Jun, 2021 Given a number N having only one ‘1’ and all other ’0’s in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of set bit ‘1’ should be counted starting with 1 from the LSB side in the binary representation of the number. Source: Microsoft Interview | 18 Examples:- Input: N = 2 Output: 2 Explanation: 2 is represented as "10" in Binary. As we see there's only one set bit and it's in Position 2 and thus the Output 2. here is another example Input: N = 5 Output: -1 Explanation: 5 is represented as "101" in Binary. As we see there's two set bits and thus the Output -1. The idea is to start from the rightmost bit and one by one check value of every bit. Following is a detailed algorithm.1) If number is power of two then and then only its binary representation contains only one ‘1’. That’s why check whether the given number is a power of 2 or not. If given number is not a power of 2, then print error message and exit.2) Initialize two variables; i = 1 (for looping) and pos = 1 (to find position of set bit)3) Inside loop, do bitwise AND of i and number ‘N’. If value of this operation is true, then “pos” bit is set, so break the loop and return position. Otherwise, increment “pos” by 1 and left shift i by 1 and repeat the procedure. C++ C Java Python3 C# PHP Javascript // C++ program to find position of only set bit in a given number#include <bits/stdc++.h>using namespace std; // A utility function to check whether n is a power of 2 or not.// See http://goo.gl/17Arjint isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} // Returns position of the only set bit in 'n'int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; unsigned i = 1, pos = 1; // Iterate through bits of n till we find a set bit // i&n will be non-zero only when 'i' and 'n' have a set bit // at same position while (!(i & n)) { // Unset current bit and set the next bit in 'i' i = i << 1; // increment position ++pos; } return pos;} // Driver program to test above functionint main(void){ int n = 16; int pos = findPosition(n); (pos == -1) ? cout << "n = " << n << ", Invalid number" << endl : cout << "n = " << n << ", Position " << pos << endl; n = 12; pos = findPosition(n); (pos == -1) ? cout << "n = " << n << ", Invalid number" << endl : cout << "n = " << n << ", Position " << pos << endl; n = 128; pos = findPosition(n); (pos == -1) ? cout << "n = " << n << ", Invalid number" << endl : cout << "n = " << n << ", Position " << pos << endl; return 0;} // This code is contributed by rathbhupendra // C program to find position of only set bit in a given number#include <stdio.h> // A utility function to check whether n is a power of 2 or not.// See http://goo.gl/17Arjint isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} // Returns position of the only set bit in 'n'int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; unsigned i = 1, pos = 1; // Iterate through bits of n till we find a set bit // i&n will be non-zero only when 'i' and 'n' have a set bit // at same position while (!(i & n)) { // Unset current bit and set the next bit in 'i' i = i << 1; // increment position ++pos; } return pos;} // Driver program to test above functionint main(void){ int n = 16; int pos = findPosition(n); (pos == -1) ? printf("n = %d, Invalid number\n", n) : printf("n = %d, Position %d \n", n, pos); n = 12; pos = findPosition(n); (pos == -1) ? printf("n = %d, Invalid number\n", n) : printf("n = %d, Position %d \n", n, pos); n = 128; pos = findPosition(n); (pos == -1) ? printf("n = %d, Invalid number\n", n) : printf("n = %d, Position %d \n", n, pos); return 0;} // Java program to find position of only set bit in a given numberclass GFG { // A utility function to check whether n is a power of 2 or not. // See http://goo.gl/17Arj static boolean isPowerOfTwo(int n) { return (n > 0 && ((n & (n - 1)) == 0)) ? true : false; } // Returns position of the only set bit in 'n' static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; int i = 1, pos = 1; // Iterate through bits of n till we find a set bit // i&n will be non-zero only when 'i' and 'n' have a set bit // at same position while ((i & n) == 0) { // Unset current bit and set the next bit in 'i' i = i << 1; // increment position ++pos; } return pos; } // Driver code public static void main(String[] args) { int n = 16; int pos = findPosition(n); if (pos == -1) System.out.println("n = " + n + ", Invalid number"); else System.out.println("n = " + n + ", Position " + pos); n = 12; pos = findPosition(n); if (pos == -1) System.out.println("n = " + n + ", Invalid number"); else System.out.println("n = " + n + ", Position " + pos); n = 128; pos = findPosition(n); if (pos == -1) System.out.println("n = " + n + ", Invalid number"); else System.out.println("n = " + n + ", Position " + pos); }} // This code is contributed by mits # Python3 program to find position of# only set bit in a given number # A utility function to check# whether n is power of 2 or# not.def isPowerOfTwo(n): return (True if(n > 0 and ((n & (n - 1)) > 0)) else False); # Returns position of the# only set bit in 'n'def findPosition(n): if (isPowerOfTwo(n) == True): return -1; i = 1; pos = 1; # Iterate through bits of n # till we find a set bit i&n # will be non-zero only when # 'i' and 'n' have a set bit # at same position while ((i & n) == 0): # Unset current bit and # set the next bit in 'i' i = i << 1; # increment position pos += 1; return pos; # Driver Coden = 16;pos = findPosition(n);if (pos == -1): print("n =", n, ", Invalid number");else: print("n =", n, ", Position ", pos); n = 12;pos = findPosition(n);if (pos == -1): print("n =", n, ", Invalid number");else: print("n =", n, ", Position ", pos); n = 128;pos = findPosition(n);if (pos == -1): print("n =", n, ", Invalid number");else: print("n =", n, ", Position ", pos); # This code is contributed by mits // C# program to find position of only set bit in a given numberusing System; class GFG { // A utility function to check whether n is a power of 2 or not. // See http://goo.gl/17Arj static bool isPowerOfTwo(int n) { return (n > 0 && ((n & (n - 1)) == 0)) ? true : false; } // Returns position of the only set bit in 'n' static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; int i = 1, pos = 1; // Iterate through bits of n till we find a set bit // i&n will be non-zero only when 'i' and 'n' have a set bit // at same position while ((i & n) == 0) { // Unset current bit and set the next bit in 'i' i = i << 1; // increment position ++pos; } return pos; } // Driver code static void Main() { int n = 16; int pos = findPosition(n); if (pos == -1) Console.WriteLine("n = " + n + ", Invalid number"); else Console.WriteLine("n = " + n + ", Position " + pos); n = 12; pos = findPosition(n); if (pos == -1) Console.WriteLine("n = " + n + ", Invalid number"); else Console.WriteLine("n = " + n + ", Position " + pos); n = 128; pos = findPosition(n); if (pos == -1) Console.WriteLine("n = " + n + ", Invalid number"); else Console.WriteLine("n = " + n + ", Position " + pos); }} // This code is contributed by mits <?php// PHP program to find position of// only set bit in a given number // A utility function to check// whether n is power of 2 or// not. See http://goo.gl/17Arjfunction isPowerOfTwo($n){ return $n && (!($n & ($n - 1))); } // Returns position of the// only set bit in 'n'function findPosition($n){ if (!isPowerOfTwo($n)) return -1; $i = 1; $pos = 1; // Iterate through bits of n // till we find a set bit i&n // will be non-zero only when // 'i' and 'n' have a set bit // at same position while (!($i & $n)) { // Unset current bit and // set the next bit in 'i' $i = $i << 1; // increment position ++$pos; } return $pos;} // Driver Code$n = 16;$pos = findPosition($n);if (($pos == -1) == true) echo "n =", $n, ", ", " Invalid number", "\n";else echo "n = ", $n, ", ", " Position ", $pos, "\n"; $n = 12;$pos = findPosition($n);if(($pos == -1) == true) echo "n = ", $n, ", ", " Invalid number", "\n";else echo "n =", $n, ", ", " Position ", $pos, "\n";$n = 128;$pos = findPosition($n);if(($pos == -1) == true) echo "n =", $n, ", ", " Invalid number", "\n";else echo "n = ", $n, ", ", " Position ", $pos, "\n"; // This code is contributed by ajit?> <script> // JavaScript program to find position of// only set bit in a given number // A utility function to check// whether n is power of 2 or// not.function isPowerOfTwo(n){ return (n > 0 && ((n & (n - 1)) == 0)) ? true : false;} // Returns position of the// only set bit in 'n'function findPosition(n){ if (isPowerOfTwo(n) == false) return -1; var i = 1; var pos = 1; // Iterate through bits of n // till we find a set bit i&n // will be non-zero only when // 'i' and 'n' have a set bit // at same position while ((i & n) == 0){ // Unset current bit and // set the next bit in 'i' i = i << 1; // increment position pos += 1; } return pos;} // Driver Codevar n = 16;var pos = findPosition(n);if (pos == -1) document.write("n =" + n + ", Invalid number");else document.write("n =" + n + ", Position " + pos); document.write("<br>"); n = 12;pos = findPosition(n);if (pos == -1) document.write("n =" + n + ", Invalid number");else document.write("n =" + n + ", Position ", pos); document.write("<br>"); n = 128;pos = findPosition(n);if (pos == -1) document.write("n =" + n + ", Invalid number");else document.write("n =" + n + ", Position " + pos); // This code is contributed by AnkThon </script> Output : n = 16, Position 5 n = 12, Invalid number n = 128, Position 8 Following is another method for this problem. The idea is to one by one right shift the set bit of given number ‘n’ until ‘n’ becomes 0. Count how many times we shifted to make ‘n’ zero. The final count is the position of the set bit. C++ C Java Python3 C# PHP Javascript // C++ program to find position of only set bit in a given number#include <bits/stdc++.h>using namespace std; // A utility function to check whether n is power of 2 or notint isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} // Returns position of the only set bit in 'n'int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; unsigned count = 0; // One by one move the only set bit to right till it reaches end while (n) { n = n >> 1; // increment count of shifts ++count; } return count;} // Driver codeint main(void){ int n = 0; int pos = findPosition(n); (pos == -1) ? cout<<"n = "<<n<<", Invalid number\n" : cout<<"n = "<<n<<", Position "<< pos<<endl; n = 12; pos = findPosition(n); (pos == -1) ? cout<<"n = "<<n<<", Invalid number\n" : cout<<"n = "<<n<<", Position "<< pos<<endl; n = 128; pos = findPosition(n); (pos == -1) ? cout<<"n = "<<n<<", Invalid number\n" : cout<<"n = "<<n<<", Position "<< pos<<endl; return 0;} // This code is contributed by rathbhupendra // C program to find position of only set bit in a given number#include <stdio.h> // A utility function to check whether n is power of 2 or notint isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} // Returns position of the only set bit in 'n'int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; unsigned count = 0; // One by one move the only set bit to right till it reaches end while (n) { n = n >> 1; // increment count of shifts ++count; } return count;} // Driver program to test above functionint main(void){ int n = 0; int pos = findPosition(n); (pos == -1) ? printf("n = %d, Invalid number\n", n) : printf("n = %d, Position %d \n", n, pos); n = 12; pos = findPosition(n); (pos == -1) ? printf("n = %d, Invalid number\n", n) : printf("n = %d, Position %d \n", n, pos); n = 128; pos = findPosition(n); (pos == -1) ? printf("n = %d, Invalid number\n", n) : printf("n = %d, Position %d \n", n, pos); return 0;} // Java program to find position of only// set bit in a given number class GFG { // A utility function to check whether // n is power of 2 or not static boolean isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0); } // Returns position of the only set bit in 'n' static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; int count = 0; // One by one move the only set bit // to right till it reaches end while (n > 0) { n = n >> 1; // increment count of shifts ++count; } return count; } // Driver code public static void main(String[] args) { int n = 0; int pos = findPosition(n); if (pos == -1) System.out.println("n = " + n + ", Invalid number"); else System.out.println("n = " + n + ", Position " + pos); n = 12; pos = findPosition(n); if (pos == -1) System.out.println("n = " + n + ", Invalid number"); else System.out.println("n = " + n + ", Position " + pos); n = 128; pos = findPosition(n); if (pos == -1) System.out.println("n = " + n + ", Invalid number"); else System.out.println("n = " + n + ", Position " + pos); }} // This code is contributed by mits # Python 3 program to find position# of only set bit in a given number # A utility function to check whether# n is power of 2 or notdef isPowerOfTwo(n) : return (n and ( not (n & (n-1)))) # Returns position of the only set bit in 'n'def findPosition(n) : if not isPowerOfTwo(n) : return -1 count = 0 # One by one move the only set bit to # right till it reaches end while (n) : n = n >> 1 # increment count of shifts count += 1 return count # Driver program to test above functionif __name__ == "__main__" : n = 0 pos = findPosition(n) if pos == -1 : print("n =", n, "Invalid number") else : print("n =", n, "Position", pos) n = 12 pos = findPosition(n) if pos == -1 : print("n =", n, "Invalid number") else : print("n =", n, "Position", pos) n = 128 pos = findPosition(n) if pos == -1 : print("n =", n, "Invalid number") else : print("n =", n, "Position", pos) # This code is contributed by ANKITRAI1 // C# program to find position of only// set bit in a given numberusing System; class GFG { // A utility function to check whether // n is power of 2 or not static bool isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0); } // Returns position of the only set bit in 'n' static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; int count = 0; // One by one move the only set bit // to right till it reaches end while (n > 0) { n = n >> 1; // increment count of shifts ++count; } return count; } // Driver code static void Main() { int n = 0; int pos = findPosition(n); if (pos == -1) Console.WriteLine("n = " + n + ", Invalid number"); else Console.WriteLine("n = " + n + ", Position " + pos); n = 12; pos = findPosition(n); if (pos == -1) Console.WriteLine("n = " + n + ", Invalid number"); else Console.WriteLine("n = " + n + ", Position " + pos); n = 128; pos = findPosition(n); if (pos == -1) Console.WriteLine("n = " + n + ", Invalid number"); else Console.WriteLine("n = " + n + ", Position " + pos); }} // This code is contributed by mits <?php// PHP program to find position of// only set bit in a given number // A utility function to check// whether n is power of 2 or notfunction isPowerOfTwo($n){ return $n && (! ($n & ($n - 1)));} // Returns position of the// only set bit in 'n'function findPosition($n){ if (!isPowerOfTwo($n)) return -1; $count = 0; // One by one move the only set // bit to right till it reaches end while ($n) { $n = $n >> 1; // increment count of shifts ++$count; } return $count;} // Driver Code$n = 0;$pos = findPosition($n);if(($pos == -1) == true) echo "n = ", $n, ", ", " Invalid number", "\n";else echo "n = ", $n, ", ", " Position ", $pos, "\n"; $n = 12;$pos = findPosition($n);if (($pos == -1) == true) echo "n = ", $n, ", ", " Invalid number", "\n";else echo "n = ", $n, " Position ", $pos, "\n"; $n = 128;$pos = findPosition($n); if(($pos == -1) == true) echo "n = ", $n, ", ", " Invalid number", "\n";else echo "n = ", $n, ", ", " Position ", $pos, "\n"; // This code is contributed by ajit?> <script> // JavaScript program to find position// of only set bit in a given number // A utility function to check whether// n is power of 2 or notfunction isPowerOfTwo(n) { return (n && ( !(n & (n-1))))} // Returns position of the only set bit in 'n'function findPosition(n) { if (!isPowerOfTwo(n)) return -1 var count = 0 // One by one move the only set bit to // right till it reaches end while (n) { n = n >> 1 // increment count of shifts count += 1 } return count } // Driver program to test above functionvar n = 0var pos = findPosition(n) if (pos == -1) document.write("n = ", n, ", Invalid number ")else document.write("n =", n, ", Position ", pos) document.write("<br>") n = 12pos = findPosition(n) if (pos == -1) document.write("n = ", n, ", Invalid number")else document.write("n = ", n, ", Position ", pos) document.write("<br>") n = 128pos = findPosition(n) if (pos == -1) document.write("n = ", n, ", Invalid number")else document.write("n = ", n, ", Position ", pos) document.write("<br>") // This code is contributed by AnkThon </script> Output : n = 0, Invalid number n = 12, Invalid number n = 128, Position 8 We can also use log base 2 to find the position. Thanks to Arunkumar for suggesting this solution. C++ C Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; unsigned int Log2n(unsigned int n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} int isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; return Log2n(n) + 1;} // Driver codeint main(void){ int n = 0; int pos = findPosition(n); (pos == -1) ? cout<<"n = "<<n<<", Invalid number\n" : cout<<"n = "<<n<<", Position "<<pos<<" \n"; n = 12; pos = findPosition(n); (pos == -1) ? cout<<"n = "<<n<<", Invalid number\n" : cout<<"n = "<<n<<", Position "<<pos<<" \n"; n = 128; pos = findPosition(n); (pos == -1) ? cout<<"n = "<<n<<", Invalid number\n" : cout<<"n = "<<n<<", Position "<<pos<<" \n"; return 0;} // This code is contributed by rathbhupendra #include <stdio.h> unsigned int Log2n(unsigned int n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} int isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; return Log2n(n) + 1;} // Driver program to test above functionint main(void){ int n = 0; int pos = findPosition(n); (pos == -1) ? printf("n = %d, Invalid number\n", n) : printf("n = %d, Position %d \n", n, pos); n = 12; pos = findPosition(n); (pos == -1) ? printf("n = %d, Invalid number\n", n) : printf("n = %d, Position %d \n", n, pos); n = 128; pos = findPosition(n); (pos == -1) ? printf("n = %d, Invalid number\n", n) : printf("n = %d, Position %d \n", n, pos); return 0;} // Java program to find position// of only set bit in a given number class GFG { static int Log2n(int n) { return (n > 1) ? 1 + Log2n(n / 2) : 0; } static boolean isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0); } static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; return Log2n(n) + 1; } // Driver code public static void main(String[] args) { int n = 0; int pos = findPosition(n); if (pos == -1) System.out.println("n = " + n + ", Invalid number "); else System.out.println("n = " + n + ", Position " + pos); n = 12; pos = findPosition(n); if (pos == -1) System.out.println("n = " + n + ", Invalid number "); else System.out.println("n = " + n + ", Position " + pos); n = 128; pos = findPosition(n); if (pos == -1) System.out.println("n = " + n + ", Invalid number "); else System.out.println("n = " + n + ", Position " + pos); }} // This code is contributed by mits # Python program to find position# of only set bit in a given number def Log2n(n): if (n > 1): return (1 + Log2n(n / 2)) else: return 0 # A utility function to check# whether n is power of 2 or not def isPowerOfTwo(n): return n and (not (n & (n-1)) ) def findPosition(n): if (not isPowerOfTwo(n)): return -1 return Log2n(n) + 1 # Driver program to test above function n = 0pos = findPosition(n)if(pos == -1): print("n =", n, ", Invalid number")else: print("n = ", n, ", Position ", pos) n = 12pos = findPosition(n)if(pos == -1): print("n =", n, ", Invalid number")else: print("n = ", n, ", Position ", pos)n = 128pos = findPosition(n)if(pos == -1): print("n = ", n, ", Invalid number")else: print("n = ", n, ", Position ", pos) # This code is contributed# by Sumit Sudhakar // C# program to find position// of only set bit in a given number using System; class GFG { static int Log2n(int n) { return (n > 1) ? 1 + Log2n(n / 2) : 0; } static bool isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0); } static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; return Log2n(n) + 1; } // Driver program to test above function static void Main() { int n = 0; int pos = findPosition(n); if (pos == -1) Console.WriteLine("n = " + n + ", Invalid number "); else Console.WriteLine("n = " + n + ", Position " + pos); n = 12; pos = findPosition(n); if (pos == -1) Console.WriteLine("n = " + n + ", Invalid number "); else Console.WriteLine("n = " + n + ", Position " + pos); n = 128; pos = findPosition(n); if (pos == -1) Console.WriteLine("n = " + n + ", Invalid number "); else Console.WriteLine("n = " + n + ", Position " + pos); }}// This code is contributed by mits <?php// PHP program to find position// of only set bit in a given numberfunction Log2n($n){return ($n > 1) ? 1 + Log2n($n / 2) : 0;} function isPowerOfTwo($n){ return $n && (! ($n & ($n - 1)));} function findPosition($n){ if (!isPowerOfTwo($n)) return -1; return Log2n($n) + 1;} // Driver Code$n = 0;$pos = findPosition($n);if(($pos == -1) == true) echo "n =", $n, ", ", " Invalid number", "\n";else echo "n = ", $n, ", ", " Position n", $pos, "\n"; $n = 12;$pos = findPosition($n);if(($pos == -1) == true) echo "n = ", $n, ", ", " Invalid number", "\n"; else echo "n =", $n, ", ", " Position", $pos, "\n"; // Driver Code$n = 128;$pos = findPosition($n);if(($pos == -1) == true) echo "n = ", $n, ", ", " Invalid number", "\n";else echo "n = ", $n, ", ", " Position ", $pos, "\n"; // This code is contributed by aj_36?> <script> // JavaScript program to find position// of only set bit in a given number function Log2n(n){ if (n > 1) return (1 + Log2n(n / 2)) else return 0} // A utility function to check// whether n is power of 2 or not function isPowerOfTwo(n){ return n && ( ! (n & (n-1)) )} function findPosition(n){ if (isPowerOfTwo(n) == false) return -1 return Log2n(n) + 1 } // Driver program to test above function var n = 0var pos = findPosition(n)if(pos == -1) document.write("n = ", n, ", Invalid number")else document.write("n = ", n, ", Position ", pos) document.write("<br>") n = 12pos = findPosition(n)if(pos == -1) document.write("n = ", n, ", Invalid number")else document.write("n = ", n, ", Position ", pos) document.write("<br>")n = 128pos = findPosition(n)if(pos == -1) document.write("n = ", n, ", Invalid number")else document.write("n = ", n, ", Position ", pos) // This code is contributed AnkThon </script> Output : n = 0, Invalid number n = 12, Invalid number n = 128, Position 8 This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Mithun Kumar ankthon rathbhupendra CheshtaKwatra surinderdawra388 jpafymzpbi Microsoft Bit Magic Microsoft Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Add two numbers without using arithmetic operators Binary representation of a given number Program to find whether a given number is power of 2 Find the element that appears once Set, Clear and Toggle a given bit of a number in C Bit Fields in C Bits manipulation (Important tactics) Josephus problem | Set 1 (A O(n) Solution)
[ { "code": null, "e": 24263, "s": 24235, "text": "\n21 Jun, 2021" }, { "code": null, "e": 24567, "s": 24263, "text": "Given a number N having only one ‘1’ and all other ’0’s in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of set bit ‘1’ should be counted starting with 1 from the LSB side in the binary representation of the number." }, { "code": null, "e": 24601, "s": 24567, "text": " Source: Microsoft Interview | 18" }, { "code": null, "e": 24612, "s": 24601, "text": "Examples:-" }, { "code": null, "e": 24766, "s": 24612, "text": "Input:\nN = 2\nOutput:\n2\nExplanation:\n2 is represented as \"10\" in Binary.\nAs we see there's only one set bit\nand it's in Position 2 and thus the\nOutput 2.\n" }, { "code": null, "e": 24790, "s": 24766, "text": "here is another example" }, { "code": null, "e": 24919, "s": 24790, "text": "Input:\nN = 5\nOutput:\n-1\nExplanation:\n5 is represented as \"101\" in Binary.\nAs we see there's two set bits\nand thus the Output -1." }, { "code": null, "e": 25593, "s": 24919, "text": "The idea is to start from the rightmost bit and one by one check value of every bit. Following is a detailed algorithm.1) If number is power of two then and then only its binary representation contains only one ‘1’. That’s why check whether the given number is a power of 2 or not. If given number is not a power of 2, then print error message and exit.2) Initialize two variables; i = 1 (for looping) and pos = 1 (to find position of set bit)3) Inside loop, do bitwise AND of i and number ‘N’. If value of this operation is true, then “pos” bit is set, so break the loop and return position. Otherwise, increment “pos” by 1 and left shift i by 1 and repeat the procedure. " }, { "code": null, "e": 25597, "s": 25593, "text": "C++" }, { "code": null, "e": 25599, "s": 25597, "text": "C" }, { "code": null, "e": 25604, "s": 25599, "text": "Java" }, { "code": null, "e": 25612, "s": 25604, "text": "Python3" }, { "code": null, "e": 25615, "s": 25612, "text": "C#" }, { "code": null, "e": 25619, "s": 25615, "text": "PHP" }, { "code": null, "e": 25630, "s": 25619, "text": "Javascript" }, { "code": "// C++ program to find position of only set bit in a given number#include <bits/stdc++.h>using namespace std; // A utility function to check whether n is a power of 2 or not.// See http://goo.gl/17Arjint isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} // Returns position of the only set bit in 'n'int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; unsigned i = 1, pos = 1; // Iterate through bits of n till we find a set bit // i&n will be non-zero only when 'i' and 'n' have a set bit // at same position while (!(i & n)) { // Unset current bit and set the next bit in 'i' i = i << 1; // increment position ++pos; } return pos;} // Driver program to test above functionint main(void){ int n = 16; int pos = findPosition(n); (pos == -1) ? cout << \"n = \" << n << \", Invalid number\" << endl : cout << \"n = \" << n << \", Position \" << pos << endl; n = 12; pos = findPosition(n); (pos == -1) ? cout << \"n = \" << n << \", Invalid number\" << endl : cout << \"n = \" << n << \", Position \" << pos << endl; n = 128; pos = findPosition(n); (pos == -1) ? cout << \"n = \" << n << \", Invalid number\" << endl : cout << \"n = \" << n << \", Position \" << pos << endl; return 0;} // This code is contributed by rathbhupendra", "e": 26952, "s": 25630, "text": null }, { "code": "// C program to find position of only set bit in a given number#include <stdio.h> // A utility function to check whether n is a power of 2 or not.// See http://goo.gl/17Arjint isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} // Returns position of the only set bit in 'n'int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; unsigned i = 1, pos = 1; // Iterate through bits of n till we find a set bit // i&n will be non-zero only when 'i' and 'n' have a set bit // at same position while (!(i & n)) { // Unset current bit and set the next bit in 'i' i = i << 1; // increment position ++pos; } return pos;} // Driver program to test above functionint main(void){ int n = 16; int pos = findPosition(n); (pos == -1) ? printf(\"n = %d, Invalid number\\n\", n) : printf(\"n = %d, Position %d \\n\", n, pos); n = 12; pos = findPosition(n); (pos == -1) ? printf(\"n = %d, Invalid number\\n\", n) : printf(\"n = %d, Position %d \\n\", n, pos); n = 128; pos = findPosition(n); (pos == -1) ? printf(\"n = %d, Invalid number\\n\", n) : printf(\"n = %d, Position %d \\n\", n, pos); return 0;}", "e": 28132, "s": 26952, "text": null }, { "code": "// Java program to find position of only set bit in a given numberclass GFG { // A utility function to check whether n is a power of 2 or not. // See http://goo.gl/17Arj static boolean isPowerOfTwo(int n) { return (n > 0 && ((n & (n - 1)) == 0)) ? true : false; } // Returns position of the only set bit in 'n' static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; int i = 1, pos = 1; // Iterate through bits of n till we find a set bit // i&n will be non-zero only when 'i' and 'n' have a set bit // at same position while ((i & n) == 0) { // Unset current bit and set the next bit in 'i' i = i << 1; // increment position ++pos; } return pos; } // Driver code public static void main(String[] args) { int n = 16; int pos = findPosition(n); if (pos == -1) System.out.println(\"n = \" + n + \", Invalid number\"); else System.out.println(\"n = \" + n + \", Position \" + pos); n = 12; pos = findPosition(n); if (pos == -1) System.out.println(\"n = \" + n + \", Invalid number\"); else System.out.println(\"n = \" + n + \", Position \" + pos); n = 128; pos = findPosition(n); if (pos == -1) System.out.println(\"n = \" + n + \", Invalid number\"); else System.out.println(\"n = \" + n + \", Position \" + pos); }} // This code is contributed by mits", "e": 29685, "s": 28132, "text": null }, { "code": "# Python3 program to find position of# only set bit in a given number # A utility function to check# whether n is power of 2 or# not.def isPowerOfTwo(n): return (True if(n > 0 and ((n & (n - 1)) > 0)) else False); # Returns position of the# only set bit in 'n'def findPosition(n): if (isPowerOfTwo(n) == True): return -1; i = 1; pos = 1; # Iterate through bits of n # till we find a set bit i&n # will be non-zero only when # 'i' and 'n' have a set bit # at same position while ((i & n) == 0): # Unset current bit and # set the next bit in 'i' i = i << 1; # increment position pos += 1; return pos; # Driver Coden = 16;pos = findPosition(n);if (pos == -1): print(\"n =\", n, \", Invalid number\");else: print(\"n =\", n, \", Position \", pos); n = 12;pos = findPosition(n);if (pos == -1): print(\"n =\", n, \", Invalid number\");else: print(\"n =\", n, \", Position \", pos); n = 128;pos = findPosition(n);if (pos == -1): print(\"n =\", n, \", Invalid number\");else: print(\"n =\", n, \", Position \", pos); # This code is contributed by mits", "e": 30849, "s": 29685, "text": null }, { "code": "// C# program to find position of only set bit in a given numberusing System; class GFG { // A utility function to check whether n is a power of 2 or not. // See http://goo.gl/17Arj static bool isPowerOfTwo(int n) { return (n > 0 && ((n & (n - 1)) == 0)) ? true : false; } // Returns position of the only set bit in 'n' static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; int i = 1, pos = 1; // Iterate through bits of n till we find a set bit // i&n will be non-zero only when 'i' and 'n' have a set bit // at same position while ((i & n) == 0) { // Unset current bit and set the next bit in 'i' i = i << 1; // increment position ++pos; } return pos; } // Driver code static void Main() { int n = 16; int pos = findPosition(n); if (pos == -1) Console.WriteLine(\"n = \" + n + \", Invalid number\"); else Console.WriteLine(\"n = \" + n + \", Position \" + pos); n = 12; pos = findPosition(n); if (pos == -1) Console.WriteLine(\"n = \" + n + \", Invalid number\"); else Console.WriteLine(\"n = \" + n + \", Position \" + pos); n = 128; pos = findPosition(n); if (pos == -1) Console.WriteLine(\"n = \" + n + \", Invalid number\"); else Console.WriteLine(\"n = \" + n + \", Position \" + pos); }} // This code is contributed by mits", "e": 32385, "s": 30849, "text": null }, { "code": "<?php// PHP program to find position of// only set bit in a given number // A utility function to check// whether n is power of 2 or// not. See http://goo.gl/17Arjfunction isPowerOfTwo($n){ return $n && (!($n & ($n - 1))); } // Returns position of the// only set bit in 'n'function findPosition($n){ if (!isPowerOfTwo($n)) return -1; $i = 1; $pos = 1; // Iterate through bits of n // till we find a set bit i&n // will be non-zero only when // 'i' and 'n' have a set bit // at same position while (!($i & $n)) { // Unset current bit and // set the next bit in 'i' $i = $i << 1; // increment position ++$pos; } return $pos;} // Driver Code$n = 16;$pos = findPosition($n);if (($pos == -1) == true) echo \"n =\", $n, \", \", \" Invalid number\", \"\\n\";else echo \"n = \", $n, \", \", \" Position \", $pos, \"\\n\"; $n = 12;$pos = findPosition($n);if(($pos == -1) == true) echo \"n = \", $n, \", \", \" Invalid number\", \"\\n\";else echo \"n =\", $n, \", \", \" Position \", $pos, \"\\n\";$n = 128;$pos = findPosition($n);if(($pos == -1) == true) echo \"n =\", $n, \", \", \" Invalid number\", \"\\n\";else echo \"n = \", $n, \", \", \" Position \", $pos, \"\\n\"; // This code is contributed by ajit?>", "e": 33744, "s": 32385, "text": null }, { "code": "<script> // JavaScript program to find position of// only set bit in a given number // A utility function to check// whether n is power of 2 or// not.function isPowerOfTwo(n){ return (n > 0 && ((n & (n - 1)) == 0)) ? true : false;} // Returns position of the// only set bit in 'n'function findPosition(n){ if (isPowerOfTwo(n) == false) return -1; var i = 1; var pos = 1; // Iterate through bits of n // till we find a set bit i&n // will be non-zero only when // 'i' and 'n' have a set bit // at same position while ((i & n) == 0){ // Unset current bit and // set the next bit in 'i' i = i << 1; // increment position pos += 1; } return pos;} // Driver Codevar n = 16;var pos = findPosition(n);if (pos == -1) document.write(\"n =\" + n + \", Invalid number\");else document.write(\"n =\" + n + \", Position \" + pos); document.write(\"<br>\"); n = 12;pos = findPosition(n);if (pos == -1) document.write(\"n =\" + n + \", Invalid number\");else document.write(\"n =\" + n + \", Position \", pos); document.write(\"<br>\"); n = 128;pos = findPosition(n);if (pos == -1) document.write(\"n =\" + n + \", Invalid number\");else document.write(\"n =\" + n + \", Position \" + pos); // This code is contributed by AnkThon </script>", "e": 35064, "s": 33744, "text": null }, { "code": null, "e": 35074, "s": 35064, "text": "Output : " }, { "code": null, "e": 35136, "s": 35074, "text": "n = 16, Position 5\nn = 12, Invalid number\nn = 128, Position 8" }, { "code": null, "e": 35372, "s": 35136, "text": "Following is another method for this problem. The idea is to one by one right shift the set bit of given number ‘n’ until ‘n’ becomes 0. Count how many times we shifted to make ‘n’ zero. The final count is the position of the set bit. " }, { "code": null, "e": 35376, "s": 35372, "text": "C++" }, { "code": null, "e": 35378, "s": 35376, "text": "C" }, { "code": null, "e": 35383, "s": 35378, "text": "Java" }, { "code": null, "e": 35391, "s": 35383, "text": "Python3" }, { "code": null, "e": 35394, "s": 35391, "text": "C#" }, { "code": null, "e": 35398, "s": 35394, "text": "PHP" }, { "code": null, "e": 35409, "s": 35398, "text": "Javascript" }, { "code": "// C++ program to find position of only set bit in a given number#include <bits/stdc++.h>using namespace std; // A utility function to check whether n is power of 2 or notint isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} // Returns position of the only set bit in 'n'int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; unsigned count = 0; // One by one move the only set bit to right till it reaches end while (n) { n = n >> 1; // increment count of shifts ++count; } return count;} // Driver codeint main(void){ int n = 0; int pos = findPosition(n); (pos == -1) ? cout<<\"n = \"<<n<<\", Invalid number\\n\" : cout<<\"n = \"<<n<<\", Position \"<< pos<<endl; n = 12; pos = findPosition(n); (pos == -1) ? cout<<\"n = \"<<n<<\", Invalid number\\n\" : cout<<\"n = \"<<n<<\", Position \"<< pos<<endl; n = 128; pos = findPosition(n); (pos == -1) ? cout<<\"n = \"<<n<<\", Invalid number\\n\" : cout<<\"n = \"<<n<<\", Position \"<< pos<<endl; return 0;} // This code is contributed by rathbhupendra", "e": 36532, "s": 35409, "text": null }, { "code": "// C program to find position of only set bit in a given number#include <stdio.h> // A utility function to check whether n is power of 2 or notint isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} // Returns position of the only set bit in 'n'int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; unsigned count = 0; // One by one move the only set bit to right till it reaches end while (n) { n = n >> 1; // increment count of shifts ++count; } return count;} // Driver program to test above functionint main(void){ int n = 0; int pos = findPosition(n); (pos == -1) ? printf(\"n = %d, Invalid number\\n\", n) : printf(\"n = %d, Position %d \\n\", n, pos); n = 12; pos = findPosition(n); (pos == -1) ? printf(\"n = %d, Invalid number\\n\", n) : printf(\"n = %d, Position %d \\n\", n, pos); n = 128; pos = findPosition(n); (pos == -1) ? printf(\"n = %d, Invalid number\\n\", n) : printf(\"n = %d, Position %d \\n\", n, pos); return 0;}", "e": 37551, "s": 36532, "text": null }, { "code": "// Java program to find position of only// set bit in a given number class GFG { // A utility function to check whether // n is power of 2 or not static boolean isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0); } // Returns position of the only set bit in 'n' static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; int count = 0; // One by one move the only set bit // to right till it reaches end while (n > 0) { n = n >> 1; // increment count of shifts ++count; } return count; } // Driver code public static void main(String[] args) { int n = 0; int pos = findPosition(n); if (pos == -1) System.out.println(\"n = \" + n + \", Invalid number\"); else System.out.println(\"n = \" + n + \", Position \" + pos); n = 12; pos = findPosition(n); if (pos == -1) System.out.println(\"n = \" + n + \", Invalid number\"); else System.out.println(\"n = \" + n + \", Position \" + pos); n = 128; pos = findPosition(n); if (pos == -1) System.out.println(\"n = \" + n + \", Invalid number\"); else System.out.println(\"n = \" + n + \", Position \" + pos); }} // This code is contributed by mits", "e": 38929, "s": 37551, "text": null }, { "code": "# Python 3 program to find position# of only set bit in a given number # A utility function to check whether# n is power of 2 or notdef isPowerOfTwo(n) : return (n and ( not (n & (n-1)))) # Returns position of the only set bit in 'n'def findPosition(n) : if not isPowerOfTwo(n) : return -1 count = 0 # One by one move the only set bit to # right till it reaches end while (n) : n = n >> 1 # increment count of shifts count += 1 return count # Driver program to test above functionif __name__ == \"__main__\" : n = 0 pos = findPosition(n) if pos == -1 : print(\"n =\", n, \"Invalid number\") else : print(\"n =\", n, \"Position\", pos) n = 12 pos = findPosition(n) if pos == -1 : print(\"n =\", n, \"Invalid number\") else : print(\"n =\", n, \"Position\", pos) n = 128 pos = findPosition(n) if pos == -1 : print(\"n =\", n, \"Invalid number\") else : print(\"n =\", n, \"Position\", pos) # This code is contributed by ANKITRAI1", "e": 39982, "s": 38929, "text": null }, { "code": "// C# program to find position of only// set bit in a given numberusing System; class GFG { // A utility function to check whether // n is power of 2 or not static bool isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0); } // Returns position of the only set bit in 'n' static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; int count = 0; // One by one move the only set bit // to right till it reaches end while (n > 0) { n = n >> 1; // increment count of shifts ++count; } return count; } // Driver code static void Main() { int n = 0; int pos = findPosition(n); if (pos == -1) Console.WriteLine(\"n = \" + n + \", Invalid number\"); else Console.WriteLine(\"n = \" + n + \", Position \" + pos); n = 12; pos = findPosition(n); if (pos == -1) Console.WriteLine(\"n = \" + n + \", Invalid number\"); else Console.WriteLine(\"n = \" + n + \", Position \" + pos); n = 128; pos = findPosition(n); if (pos == -1) Console.WriteLine(\"n = \" + n + \", Invalid number\"); else Console.WriteLine(\"n = \" + n + \", Position \" + pos); }} // This code is contributed by mits", "e": 41342, "s": 39982, "text": null }, { "code": "<?php// PHP program to find position of// only set bit in a given number // A utility function to check// whether n is power of 2 or notfunction isPowerOfTwo($n){ return $n && (! ($n & ($n - 1)));} // Returns position of the// only set bit in 'n'function findPosition($n){ if (!isPowerOfTwo($n)) return -1; $count = 0; // One by one move the only set // bit to right till it reaches end while ($n) { $n = $n >> 1; // increment count of shifts ++$count; } return $count;} // Driver Code$n = 0;$pos = findPosition($n);if(($pos == -1) == true) echo \"n = \", $n, \", \", \" Invalid number\", \"\\n\";else echo \"n = \", $n, \", \", \" Position \", $pos, \"\\n\"; $n = 12;$pos = findPosition($n);if (($pos == -1) == true) echo \"n = \", $n, \", \", \" Invalid number\", \"\\n\";else echo \"n = \", $n, \" Position \", $pos, \"\\n\"; $n = 128;$pos = findPosition($n); if(($pos == -1) == true) echo \"n = \", $n, \", \", \" Invalid number\", \"\\n\";else echo \"n = \", $n, \", \", \" Position \", $pos, \"\\n\"; // This code is contributed by ajit?>", "e": 42503, "s": 41342, "text": null }, { "code": "<script> // JavaScript program to find position// of only set bit in a given number // A utility function to check whether// n is power of 2 or notfunction isPowerOfTwo(n) { return (n && ( !(n & (n-1))))} // Returns position of the only set bit in 'n'function findPosition(n) { if (!isPowerOfTwo(n)) return -1 var count = 0 // One by one move the only set bit to // right till it reaches end while (n) { n = n >> 1 // increment count of shifts count += 1 } return count } // Driver program to test above functionvar n = 0var pos = findPosition(n) if (pos == -1) document.write(\"n = \", n, \", Invalid number \")else document.write(\"n =\", n, \", Position \", pos) document.write(\"<br>\") n = 12pos = findPosition(n) if (pos == -1) document.write(\"n = \", n, \", Invalid number\")else document.write(\"n = \", n, \", Position \", pos) document.write(\"<br>\") n = 128pos = findPosition(n) if (pos == -1) document.write(\"n = \", n, \", Invalid number\")else document.write(\"n = \", n, \", Position \", pos) document.write(\"<br>\") // This code is contributed by AnkThon </script>", "e": 43649, "s": 42503, "text": null }, { "code": null, "e": 43659, "s": 43649, "text": "Output : " }, { "code": null, "e": 43724, "s": 43659, "text": "n = 0, Invalid number\nn = 12, Invalid number\nn = 128, Position 8" }, { "code": null, "e": 43824, "s": 43724, "text": "We can also use log base 2 to find the position. Thanks to Arunkumar for suggesting this solution. " }, { "code": null, "e": 43828, "s": 43824, "text": "C++" }, { "code": null, "e": 43830, "s": 43828, "text": "C" }, { "code": null, "e": 43835, "s": 43830, "text": "Java" }, { "code": null, "e": 43843, "s": 43835, "text": "Python3" }, { "code": null, "e": 43846, "s": 43843, "text": "C#" }, { "code": null, "e": 43850, "s": 43846, "text": "PHP" }, { "code": null, "e": 43861, "s": 43850, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; unsigned int Log2n(unsigned int n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} int isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; return Log2n(n) + 1;} // Driver codeint main(void){ int n = 0; int pos = findPosition(n); (pos == -1) ? cout<<\"n = \"<<n<<\", Invalid number\\n\" : cout<<\"n = \"<<n<<\", Position \"<<pos<<\" \\n\"; n = 12; pos = findPosition(n); (pos == -1) ? cout<<\"n = \"<<n<<\", Invalid number\\n\" : cout<<\"n = \"<<n<<\", Position \"<<pos<<\" \\n\"; n = 128; pos = findPosition(n); (pos == -1) ? cout<<\"n = \"<<n<<\", Invalid number\\n\" : cout<<\"n = \"<<n<<\", Position \"<<pos<<\" \\n\"; return 0;} // This code is contributed by rathbhupendra", "e": 44695, "s": 43861, "text": null }, { "code": "#include <stdio.h> unsigned int Log2n(unsigned int n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} int isPowerOfTwo(unsigned n){ return n && (!(n & (n - 1)));} int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; return Log2n(n) + 1;} // Driver program to test above functionint main(void){ int n = 0; int pos = findPosition(n); (pos == -1) ? printf(\"n = %d, Invalid number\\n\", n) : printf(\"n = %d, Position %d \\n\", n, pos); n = 12; pos = findPosition(n); (pos == -1) ? printf(\"n = %d, Invalid number\\n\", n) : printf(\"n = %d, Position %d \\n\", n, pos); n = 128; pos = findPosition(n); (pos == -1) ? printf(\"n = %d, Invalid number\\n\", n) : printf(\"n = %d, Position %d \\n\", n, pos); return 0;}", "e": 45444, "s": 44695, "text": null }, { "code": "// Java program to find position// of only set bit in a given number class GFG { static int Log2n(int n) { return (n > 1) ? 1 + Log2n(n / 2) : 0; } static boolean isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0); } static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; return Log2n(n) + 1; } // Driver code public static void main(String[] args) { int n = 0; int pos = findPosition(n); if (pos == -1) System.out.println(\"n = \" + n + \", Invalid number \"); else System.out.println(\"n = \" + n + \", Position \" + pos); n = 12; pos = findPosition(n); if (pos == -1) System.out.println(\"n = \" + n + \", Invalid number \"); else System.out.println(\"n = \" + n + \", Position \" + pos); n = 128; pos = findPosition(n); if (pos == -1) System.out.println(\"n = \" + n + \", Invalid number \"); else System.out.println(\"n = \" + n + \", Position \" + pos); }} // This code is contributed by mits", "e": 46571, "s": 45444, "text": null }, { "code": "# Python program to find position# of only set bit in a given number def Log2n(n): if (n > 1): return (1 + Log2n(n / 2)) else: return 0 # A utility function to check# whether n is power of 2 or not def isPowerOfTwo(n): return n and (not (n & (n-1)) ) def findPosition(n): if (not isPowerOfTwo(n)): return -1 return Log2n(n) + 1 # Driver program to test above function n = 0pos = findPosition(n)if(pos == -1): print(\"n =\", n, \", Invalid number\")else: print(\"n = \", n, \", Position \", pos) n = 12pos = findPosition(n)if(pos == -1): print(\"n =\", n, \", Invalid number\")else: print(\"n = \", n, \", Position \", pos)n = 128pos = findPosition(n)if(pos == -1): print(\"n = \", n, \", Invalid number\")else: print(\"n = \", n, \", Position \", pos) # This code is contributed# by Sumit Sudhakar", "e": 47415, "s": 46571, "text": null }, { "code": "// C# program to find position// of only set bit in a given number using System; class GFG { static int Log2n(int n) { return (n > 1) ? 1 + Log2n(n / 2) : 0; } static bool isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0); } static int findPosition(int n) { if (!isPowerOfTwo(n)) return -1; return Log2n(n) + 1; } // Driver program to test above function static void Main() { int n = 0; int pos = findPosition(n); if (pos == -1) Console.WriteLine(\"n = \" + n + \", Invalid number \"); else Console.WriteLine(\"n = \" + n + \", Position \" + pos); n = 12; pos = findPosition(n); if (pos == -1) Console.WriteLine(\"n = \" + n + \", Invalid number \"); else Console.WriteLine(\"n = \" + n + \", Position \" + pos); n = 128; pos = findPosition(n); if (pos == -1) Console.WriteLine(\"n = \" + n + \", Invalid number \"); else Console.WriteLine(\"n = \" + n + \", Position \" + pos); }}// This code is contributed by mits", "e": 48550, "s": 47415, "text": null }, { "code": "<?php// PHP program to find position// of only set bit in a given numberfunction Log2n($n){return ($n > 1) ? 1 + Log2n($n / 2) : 0;} function isPowerOfTwo($n){ return $n && (! ($n & ($n - 1)));} function findPosition($n){ if (!isPowerOfTwo($n)) return -1; return Log2n($n) + 1;} // Driver Code$n = 0;$pos = findPosition($n);if(($pos == -1) == true) echo \"n =\", $n, \", \", \" Invalid number\", \"\\n\";else echo \"n = \", $n, \", \", \" Position n\", $pos, \"\\n\"; $n = 12;$pos = findPosition($n);if(($pos == -1) == true) echo \"n = \", $n, \", \", \" Invalid number\", \"\\n\"; else echo \"n =\", $n, \", \", \" Position\", $pos, \"\\n\"; // Driver Code$n = 128;$pos = findPosition($n);if(($pos == -1) == true) echo \"n = \", $n, \", \", \" Invalid number\", \"\\n\";else echo \"n = \", $n, \", \", \" Position \", $pos, \"\\n\"; // This code is contributed by aj_36?>", "e": 49550, "s": 48550, "text": null }, { "code": "<script> // JavaScript program to find position// of only set bit in a given number function Log2n(n){ if (n > 1) return (1 + Log2n(n / 2)) else return 0} // A utility function to check// whether n is power of 2 or not function isPowerOfTwo(n){ return n && ( ! (n & (n-1)) )} function findPosition(n){ if (isPowerOfTwo(n) == false) return -1 return Log2n(n) + 1 } // Driver program to test above function var n = 0var pos = findPosition(n)if(pos == -1) document.write(\"n = \", n, \", Invalid number\")else document.write(\"n = \", n, \", Position \", pos) document.write(\"<br>\") n = 12pos = findPosition(n)if(pos == -1) document.write(\"n = \", n, \", Invalid number\")else document.write(\"n = \", n, \", Position \", pos) document.write(\"<br>\")n = 128pos = findPosition(n)if(pos == -1) document.write(\"n = \", n, \", Invalid number\")else document.write(\"n = \", n, \", Position \", pos) // This code is contributed AnkThon </script>", "e": 50536, "s": 49550, "text": null }, { "code": null, "e": 50546, "s": 50536, "text": "Output : " }, { "code": null, "e": 50611, "s": 50546, "text": "n = 0, Invalid number\nn = 12, Invalid number\nn = 128, Position 8" }, { "code": null, "e": 50786, "s": 50611, "text": "This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 50792, "s": 50786, "text": "jit_t" }, { "code": null, "e": 50805, "s": 50792, "text": "Mithun Kumar" }, { "code": null, "e": 50813, "s": 50805, "text": "ankthon" }, { "code": null, "e": 50827, "s": 50813, "text": "rathbhupendra" }, { "code": null, "e": 50841, "s": 50827, "text": "CheshtaKwatra" }, { "code": null, "e": 50858, "s": 50841, "text": "surinderdawra388" }, { "code": null, "e": 50869, "s": 50858, "text": "jpafymzpbi" }, { "code": null, "e": 50879, "s": 50869, "text": "Microsoft" }, { "code": null, "e": 50889, "s": 50879, "text": "Bit Magic" }, { "code": null, "e": 50899, "s": 50889, "text": "Microsoft" }, { "code": null, "e": 50909, "s": 50899, "text": "Bit Magic" }, { "code": null, "e": 51007, "s": 50909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51016, "s": 51007, "text": "Comments" }, { "code": null, "e": 51029, "s": 51016, "text": "Old Comments" }, { "code": null, "e": 51075, "s": 51029, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 51105, "s": 51075, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 51156, "s": 51105, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 51196, "s": 51156, "text": "Binary representation of a given number" }, { "code": null, "e": 51249, "s": 51196, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 51284, "s": 51249, "text": "Find the element that appears once" }, { "code": null, "e": 51335, "s": 51284, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 51351, "s": 51335, "text": "Bit Fields in C" }, { "code": null, "e": 51389, "s": 51351, "text": "Bits manipulation (Important tactics)" } ]
Merging subarrays in JavaScript
Suppose, we have an array of arrays that contains information about the name and email of some people like this − const arr = [ ["John", "[email protected]", "[email protected]"], ["John", "[email protected]"], ["John", "[email protected]", "[email protected]"], ["Mary", "[email protected]"] ]; Each element of the array is a subarray of strings, where the first element is a name, and the rest of the elements are emails belonging to that name. Now, we would like to merge these subarrays. Two subarrays definitely belong to the same person if there is some email that is common to both subarrays. Note that even if two subarrays have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the subarrays, we need to return them in the following format − the first element of each subarray is the name, and the rest of the elements are emails in sorted order. The subarrays themselves can be returned in any order. Therefore, for the above array, the output should look like − const output = [ ["John", '[email protected]', '[email protected]', '[email protected]'], ["John", "[email protected]"], ["Mary", "[email protected]"] ]; The code for this will be − const arr = [ ["John", "[email protected]", "[email protected]"], ["John", "[email protected]"], ["John", "[email protected]", "[email protected]"], ["Mary", "[email protected]"] ]; const recusiveMatch = (included, i, tmp, arr, res) => { for(let j = 1; j < arr[i].length; j += 1) { let currentEmail = arr[i][j]; if(included.has(currentEmail)) continue; res.push(currentEmail); included.add(currentEmail); let currentAccountIndexes = tmp.get(currentEmail); for(let c = 0; c < currentAccountIndexes.length; c += 1) { let currentIndex = currentAccountIndexes[c]; if(i !== currentIndex) { recusiveMatch(included, currentIndex, tmp, arr, res); } } } }; const merge = (arr) => { const tmp = new Map(), included = new Set(), res = []; arr.forEach((account, i) => { for(let u = 1; u < account.length; u += 1) { let currentEMail = account[u]; tmp.set(currentEMail, tmp.get(currentEMail) || []); tmp.get(currentEMail).push(i); } }); arr.forEach((account, i) => { if(!included.has(arr[1])) { let u = []; recusiveMatch(included, i, tmp, arr, u); if(u.length) { res.push(u); u.sort(); u.unshift(account[0]); } } }); return res; }; console.log(merge(arr)); And the output in the console will be − [ [ 'John', '[email protected]', '[email protected]', '[email protected]' ], [ 'John', '[email protected]' ], [ 'Mary', '[email protected]' ] ]
[ { "code": null, "e": 1176, "s": 1062, "text": "Suppose, we have an array of arrays that contains information about the name and email of some people like this −" }, { "code": null, "e": 1373, "s": 1176, "text": "const arr = [\n [\"John\", \"[email protected]\", \"[email protected]\"],\n [\"John\", \"[email protected]\"],\n [\"John\", \"[email protected]\", \"[email protected]\"],\n [\"Mary\", \"[email protected]\"]\n];" }, { "code": null, "e": 1524, "s": 1373, "text": "Each element of the array is a subarray of strings, where the first element is a name, and the rest of the elements are emails belonging to that name." }, { "code": null, "e": 1677, "s": 1524, "text": "Now, we would like to merge these subarrays. Two subarrays definitely belong to the same person if there is some email that is common to both subarrays." }, { "code": null, "e": 1801, "s": 1677, "text": "Note that even if two subarrays have the same name, they may belong to different people as people could have the same name." }, { "code": null, "e": 1910, "s": 1801, "text": "A person can have any number of accounts initially, but all of their accounts definitely have the same name." }, { "code": null, "e": 2148, "s": 1910, "text": "After merging the subarrays, we need to return them in the following format − the first element of each subarray is the name, and the rest of the elements are emails in sorted order. The subarrays themselves can be returned in any order." }, { "code": null, "e": 2210, "s": 2148, "text": "Therefore, for the above array, the output should look like −" }, { "code": null, "e": 2378, "s": 2210, "text": "const output = [\n [\"John\", '[email protected]', '[email protected]',\n '[email protected]'],\n [\"John\", \"[email protected]\"],\n [\"Mary\", \"[email protected]\"]\n];" }, { "code": null, "e": 2406, "s": 2378, "text": "The code for this will be −" }, { "code": null, "e": 3798, "s": 2406, "text": "const arr = [\n [\"John\", \"[email protected]\", \"[email protected]\"],\n [\"John\", \"[email protected]\"],\n [\"John\", \"[email protected]\", \"[email protected]\"],\n [\"Mary\", \"[email protected]\"]\n];\nconst recusiveMatch = (included, i, tmp, arr, res) => {\n for(let j = 1; j < arr[i].length; j += 1) {\n let currentEmail = arr[i][j];\n if(included.has(currentEmail)) continue;\n res.push(currentEmail);\n included.add(currentEmail);\n let currentAccountIndexes = tmp.get(currentEmail);\n for(let c = 0; c < currentAccountIndexes.length; c += 1) {\n let currentIndex = currentAccountIndexes[c];\n if(i !== currentIndex) {\n recusiveMatch(included, currentIndex, tmp, arr, res);\n }\n }\n }\n};\nconst merge = (arr) => {\n const tmp = new Map(),\n included = new Set(),\n res = [];\n arr.forEach((account, i) => {\n for(let u = 1; u < account.length; u += 1) {\n let currentEMail = account[u];\n tmp.set(currentEMail, tmp.get(currentEMail) || []);\n tmp.get(currentEMail).push(i);\n }\n });\n arr.forEach((account, i) => {\n if(!included.has(arr[1])) {\n let u = [];\n recusiveMatch(included, i, tmp, arr, u);\n if(u.length) {\n res.push(u);\n u.sort();\n u.unshift(account[0]);\n }\n }\n });\n return res;\n};\nconsole.log(merge(arr));" }, { "code": null, "e": 3838, "s": 3798, "text": "And the output in the console will be −" }, { "code": null, "e": 4020, "s": 3838, "text": "[\n [\n 'John',\n '[email protected]',\n '[email protected]',\n '[email protected]'\n ],\n [ 'John', '[email protected]' ],\n [ 'Mary', '[email protected]' ]\n]" } ]
Dart Programming - continue Statement
The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue statement doesn’t exit the loop. It terminates the current iteration and starts the subsequent iteration. The following example shows how you can use the continue statement in Dart − void main() { var num = 0; var count = 0; for(num = 0;num<=20;num++) { if (num % 2==0) { continue; } count++; } print(" The count of odd values between 0 and 20 is: ${count}"); } The above example displays the number of even values between 0 and 20. The loop exits the current iteration if the number is even. This is achieved using the continue statement. The following output is displayed on successful execution of the above code. The count of odd values between 0 and 20 is: 10 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2809, "s": 2525, "text": "The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue statement doesn’t exit the loop. It terminates the current iteration and starts the subsequent iteration." }, { "code": null, "e": 2886, "s": 2809, "text": "The following example shows how you can use the continue statement in Dart −" }, { "code": null, "e": 3123, "s": 2886, "text": "void main() { \n var num = 0; \n var count = 0; \n \n for(num = 0;num<=20;num++) { \n if (num % 2==0) { \n continue; \n } \n count++; \n } \n print(\" The count of odd values between 0 and 20 is: ${count}\"); \n} " }, { "code": null, "e": 3301, "s": 3123, "text": "The above example displays the number of even values between 0 and 20. The loop exits the current iteration if the number is even. This is achieved using the continue statement." }, { "code": null, "e": 3378, "s": 3301, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 3428, "s": 3378, "text": "The count of odd values between 0 and 20 is: 10 \n" }, { "code": null, "e": 3463, "s": 3428, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3483, "s": 3463, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3516, "s": 3483, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3536, "s": 3516, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3569, "s": 3536, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 3586, "s": 3569, "text": " Frahaan Hussain" }, { "code": null, "e": 3621, "s": 3586, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 3638, "s": 3621, "text": " Frahaan Hussain" }, { "code": null, "e": 3673, "s": 3638, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3693, "s": 3673, "text": " Pranjal Srivastava" }, { "code": null, "e": 3726, "s": 3693, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 3746, "s": 3726, "text": " Pranjal Srivastava" }, { "code": null, "e": 3753, "s": 3746, "text": " Print" }, { "code": null, "e": 3764, "s": 3753, "text": " Add Notes" } ]
Boundary traversal of matrix | Practice | GeeksforGeeks
You are given a matrix of dimensions n x m. The task is to perform boundary traversal on the matrix in a clockwise manner. Example 1: Input: n = 4, m = 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 Explanation: The matrix is: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 The boundary traversal is: 1 2 3 4 8 12 16 15 14 13 9 5 Example 2: Input: n = 3, m = 4 matrrix[][] = {{12, 11, 10, 9}, {8, 7, 6, 5}, {4, 3, 2, 1}} Output: 12 11 10 9 5 1 2 3 4 8 Your Task: Complete the function boundaryTraversal() that takes matrix, n and m as input parameters and returns the list of integers that form the boundary traversal of the matrix in a clockwise manner. Expected Time Complexity: O(N + M) Expected Auxiliary Space: O(1) Constraints: 1 <= n, m<= 100 0 <= matrixi <= 1000 0 jerinfrancis1 week ago vector<int> boundaryTraversal(vector<vector<int> > arr, int n, int m) { // code here vector<int> r; int i=0, j=0; while(j<=m-1) { r.push_back(arr[i][j++]); } i++; if(i==n) return r; j--; while(i<=n-1) { r.push_back(arr[i++][j]); } j--; if(j==-1) return r; i--; while(j>=0) { r.push_back(arr[i][j--]); } i--; j++; while(i>=1) { r.push_back(arr[i--][j]); } return r; } 0 kuldeepy104591 week ago vector<int> boundaryTraversal(vector<vector<int> > matrix, int n, int m) { // code here // starting row int strow=0,endcol=m-1,endrow=n-1,stcol=0; int total=0; if(m==1){ total=n; } else if(n==1){ total=m; } else{ total=2*(m+n-2); } int count=0; vector<int>ans; for(int i=0;i<=endcol&&count<total;i++){ ans.push_back(matrix[strow][i]); count++; } strow++; // ending col for(int i=strow;i<=endrow&&count<total;i++){ ans.push_back(matrix[i][endcol]); count++; } endcol--; // ending row for(int i=endcol;i>=stcol&&count<total;i--){ ans.push_back(matrix[endrow][i]); count++; } endrow--; // start col for(int i=endrow;i>=strow&&count<total;i--){ ans.push_back(matrix[i][stcol]); count++; } stcol++; return ans; } 0 badgujarsachin834 weeks ago vector<int> boundaryTraversal(vector<vector<int> > matrix, int n, int m) { // code here vector<int> v; if(n==1){ for(int i=0;i<m;i++){ v.push_back(matrix[0][i]); } }else if(m==1){ for(int i=0;i<n;i++){ v.push_back(matrix[i][0]); } }else{ for(int i=0;i<m;i++){ v.push_back(matrix[0][i]); } for(int i=1;i<n;i++){ v.push_back(matrix[i][m-1]); } for(int i=m-2;i>=0;i--){ v.push_back(matrix[n-1][i]); } for(int i=n-2;i>=1;i--){ v.push_back(matrix[i][0]); } } return v; } 0 rahul8781 month ago static ArrayList<Integer> boundaryTraversal(int a[][], int n, int m) { ArrayList<Integer> l=new ArrayList<>(); if(n==1 || m==1){ for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ l.add(a[i][j]); } } } else{ for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(i==0 ) l.add(a[i][j]); if(j==m-1 && i!=0) l.add(a[i][j]); } } for(int i=n-1;i>=0;i--){ for(int j=m-1;j>=0;j--){ if(i==n-1 && j<m-1) l.add(a[i][j]); else if(j==0 && i!=n-1 && i!=0) l.add(a[i][j]); } }} return l; } -1 amiransarimy1 month ago Simple Python Solutions def BoundaryTraversal(self,matrix, n, m): res =[] if n == 1: for j in range(m): res.append(matrix[0][j]) elif m == 1: for i in range(n): res.append(matrix[i][0]) else: for i in range(m): res.append(matrix[0][i]) if m > 1: for i in range(1,n): res.append(matrix[i][m-1]) if n > 1: for i in range(m-2,-1,-1): res.append(matrix[n-1][i]) for i in range(n-2,0,-1): res.append(matrix[i][0]) return res 0 saiakhilpodduturi1 month ago Boundary traversal of matrix class Solution { //Function to return list of integers that form the boundary //traversal of the matrix in a clockwise manner. static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m) { // code here ArrayList<Integer> res = new ArrayList<>(); // if matrix has only one row if (n == 1) { for (int i=0; i<m; i++) res.add(matrix[0][i]); return res; } // if matrix has only one column else if (m == 1) { for (int i=0; i<n; i++) res.add(matrix[i][0]); return res; } // if matrix has more than one row and more than one column // first row elements for (int i=0; i<m; i++) { res.add(matrix[0][i]); } // second to last but one row, corner elements for (int i=1; i<n-1; i++) { res.add(matrix[i][m-1]); } // last row elements for (int i=m-1; i>=0; i--) { res.add(matrix[n-1][i]); } // last but one row to second row starting elements for (int i=n-2; i>=1; i--) { res.add(matrix[i][0]); } return res; } } -1 pritamaber1 month ago vector<int> res; if(n==1){ for(int i=0; i<m; i++){ res.push_back(matrix[0][i]); } }else if(m==1){ for(int i=0; i<n; i++){ res.push_back(matrix[i][0]); } }else{ for(int i=0; i<m; i++){ res.push_back(matrix[0][i]); } for(int i=1; i<n; i++){ res.push_back(matrix[i][m-1]); } for(int i=m-2;i>=0;i--){ res.push_back(matrix[n-1][i]); } for(int i=n-2; i>=1;i--){ res.push_back(matrix[i][0]); } } return res; -1 akshatmathur232 months ago JAVA SOLUTION class Solution{ //Function to return list of integers that form the boundary //traversal of the matrix in a clockwise manner. static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m) { // code here ArrayList<Integer> list = new ArrayList<>(); if(matrix == null || n == 0) return list; int top = 0, left = 0, bottom = n - 1, right = m - 1; if(n == 1) { for(int i = left; i<= right; i++) list.add(matrix[top][i]); return list; } if(m == 1) { for(int i = top; i <= bottom; i++) list.add(matrix[i][right]); return list; } for(int i = left; i <= right; i++) list.add(matrix[top][i]); top++; for(int i = top; i <= bottom; i++) list.add(matrix[i][right]); right--; for(int i = right; i >= left; i--) list.add(matrix[bottom][i]); bottom--; for(int i = bottom; i >= top; i--) list.add(matrix[i][left]); left++; return list; }} -1 subhammahanta183 months ago //Java Solution class Solution{ //Function to return list of integers that form the boundary //traversal of the matrix in a clockwise manner. static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m) { ArrayList<Integer>ar=new ArrayList<>(); int j; for(int i=0;i<n;i++) { if(i==0 || i==n-1) { if(i==0) { for(j=0;j<m;j++) ar.add(matrix[i][j]); } else { for(j=m-1;j>=0;j--) ar.add(matrix[i][j]); if(matrix[i].length==1) continue; while((i-1)!=0) { i--; ar.add(matrix[i][0]); } break; } } else { j=m-1; ar.add(matrix[i][j]); } } return ar; }} -1 rohithsowmithra3 months ago python: ========= def BoundaryTraversal(self,matrix, n, m): # code here res = [] for i in range(m): res.append(matrix[0][i]) if n > 1: for i in range(1, n): res.append(matrix[i][m-1]) if m > 1: for i in range(m-2,0,-1): res.append(matrix[n-1][i]) for i in range(n-1, 0, -1): res.append(matrix[i][0]) return res We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 374, "s": 238, "text": "You are given a matrix of dimensions n x m. The task is to perform boundary traversal on the matrix in a clockwise manner. \n\nExample 1:" }, { "code": null, "e": 658, "s": 374, "text": "Input:\nn = 4, m = 4\nmatrix[][] = {{1, 2, 3, 4},\n {5, 6, 7, 8},\n {9, 10, 11, 12},\n {13, 14, 15,16}}\nOutput: 1 2 3 4 8 12 16 15 14 13 9 5\nExplanation:\nThe matrix is:\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\nThe boundary traversal is:\n1 2 3 4 8 12 16 15 14 13 9 5\n" }, { "code": null, "e": 669, "s": 658, "text": "Example 2:" }, { "code": null, "e": 800, "s": 669, "text": "Input:\nn = 3, m = 4\nmatrrix[][] = {{12, 11, 10, 9},\n {8, 7, 6, 5},\n {4, 3, 2, 1}}\nOutput: 12 11 10 9 5 1 2 3 4 8\n\n" }, { "code": null, "e": 1121, "s": 800, "text": "Your Task:\nComplete the function boundaryTraversal() that takes matrix, n and m as input parameters and returns the list of integers that form the boundary traversal of the matrix in a clockwise manner.\n\nExpected Time Complexity: O(N + M)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 <= n, m<= 100\n0 <= matrixi <= 1000" }, { "code": null, "e": 1123, "s": 1121, "text": "0" }, { "code": null, "e": 1146, "s": 1123, "text": "jerinfrancis1 week ago" }, { "code": null, "e": 1739, "s": 1146, "text": "vector<int> boundaryTraversal(vector<vector<int> > arr, int n, int m) \n {\n // code here\n vector<int> r;\n \n int i=0, j=0;\n while(j<=m-1) {\n r.push_back(arr[i][j++]);\n }\n i++;\n if(i==n) return r;\n j--;\n while(i<=n-1) {\n r.push_back(arr[i++][j]);\n }\n j--;\n if(j==-1) return r;\n i--;\n while(j>=0) {\n r.push_back(arr[i][j--]);\n }\n i--;\n j++;\n while(i>=1) {\n r.push_back(arr[i--][j]);\n }\n return r;\n }" }, { "code": null, "e": 1741, "s": 1739, "text": "0" }, { "code": null, "e": 1765, "s": 1741, "text": "kuldeepy104591 week ago" }, { "code": null, "e": 2779, "s": 1765, "text": " vector<int> boundaryTraversal(vector<vector<int> > matrix, int n, int m) { // code here // starting row int strow=0,endcol=m-1,endrow=n-1,stcol=0; int total=0; if(m==1){ total=n; } else if(n==1){ total=m; } else{ total=2*(m+n-2); } int count=0; vector<int>ans; for(int i=0;i<=endcol&&count<total;i++){ ans.push_back(matrix[strow][i]); count++; } strow++; // ending col for(int i=strow;i<=endrow&&count<total;i++){ ans.push_back(matrix[i][endcol]); count++; } endcol--; // ending row for(int i=endcol;i>=stcol&&count<total;i--){ ans.push_back(matrix[endrow][i]); count++; } endrow--; // start col for(int i=endrow;i>=strow&&count<total;i--){ ans.push_back(matrix[i][stcol]); count++; } stcol++; return ans; }" }, { "code": null, "e": 2781, "s": 2779, "text": "0" }, { "code": null, "e": 2809, "s": 2781, "text": "badgujarsachin834 weeks ago" }, { "code": null, "e": 3580, "s": 2809, "text": "vector<int> boundaryTraversal(vector<vector<int> > matrix, int n, int m) \n {\n // code here\n vector<int> v;\n if(n==1){\n for(int i=0;i<m;i++){\n v.push_back(matrix[0][i]);\n }\n }else if(m==1){\n for(int i=0;i<n;i++){\n v.push_back(matrix[i][0]);\n }\n }else{\n for(int i=0;i<m;i++){\n v.push_back(matrix[0][i]);\n }\n for(int i=1;i<n;i++){\n v.push_back(matrix[i][m-1]);\n }\n for(int i=m-2;i>=0;i--){\n v.push_back(matrix[n-1][i]);\n }\n for(int i=n-2;i>=1;i--){\n v.push_back(matrix[i][0]);\n }\n }\n return v;\n }" }, { "code": null, "e": 3582, "s": 3580, "text": "0" }, { "code": null, "e": 3602, "s": 3582, "text": "rahul8781 month ago" }, { "code": null, "e": 4513, "s": 3602, "text": " static ArrayList<Integer> boundaryTraversal(int a[][], int n, int m)\n {\n ArrayList<Integer> l=new ArrayList<>();\n if(n==1 || m==1){\n for(int i=0;i<n;i++){\n \n for(int j=0;j<m;j++){\n \n l.add(a[i][j]);\n \n \n }\n }\n \n }\n else{\n for(int i=0;i<n;i++){\n \n for(int j=0;j<m;j++){\n if(i==0 )\n l.add(a[i][j]);\n if(j==m-1 && i!=0)\n l.add(a[i][j]);\n \n }\n }\n for(int i=n-1;i>=0;i--){\n \n for(int j=m-1;j>=0;j--){\n if(i==n-1 && j<m-1)\n l.add(a[i][j]);\n else if(j==0 && i!=n-1 && i!=0)\n l.add(a[i][j]);\n \n }\n }}\n return l;\n }" }, { "code": null, "e": 4516, "s": 4513, "text": "-1" }, { "code": null, "e": 4540, "s": 4516, "text": "amiransarimy1 month ago" }, { "code": null, "e": 4564, "s": 4540, "text": "Simple Python Solutions" }, { "code": null, "e": 5256, "s": 4566, "text": "def BoundaryTraversal(self,matrix, n, m):\n res =[] \n if n == 1:\n for j in range(m):\n res.append(matrix[0][j])\n elif m == 1:\n for i in range(n):\n res.append(matrix[i][0])\n \n else:\n for i in range(m):\n res.append(matrix[0][i])\n \n if m > 1:\n for i in range(1,n):\n res.append(matrix[i][m-1])\n \n if n > 1:\n for i in range(m-2,-1,-1):\n res.append(matrix[n-1][i])\n \n for i in range(n-2,0,-1):\n res.append(matrix[i][0])\n \n return res" }, { "code": null, "e": 5258, "s": 5256, "text": "0" }, { "code": null, "e": 5287, "s": 5258, "text": "saiakhilpodduturi1 month ago" }, { "code": null, "e": 5316, "s": 5287, "text": "Boundary traversal of matrix" }, { "code": null, "e": 6602, "s": 5316, "text": "class Solution\n{\n //Function to return list of integers that form the boundary \n //traversal of the matrix in a clockwise manner.\n static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m)\n {\n // code here \n ArrayList<Integer> res = new ArrayList<>();\n // if matrix has only one row\n if (n == 1)\n {\n for (int i=0; i<m; i++)\n res.add(matrix[0][i]);\n return res;\n }\n // if matrix has only one column\n else if (m == 1)\n {\n for (int i=0; i<n; i++)\n res.add(matrix[i][0]);\n return res;\n }\n // if matrix has more than one row and more than one column\n // first row elements\n for (int i=0; i<m; i++)\n {\n res.add(matrix[0][i]);\n }\n // second to last but one row, corner elements\n for (int i=1; i<n-1; i++)\n {\n res.add(matrix[i][m-1]);\n }\n // last row elements\n for (int i=m-1; i>=0; i--)\n {\n res.add(matrix[n-1][i]);\n }\n // last but one row to second row starting elements\n for (int i=n-2; i>=1; i--)\n {\n res.add(matrix[i][0]);\n }\n return res;\n }\n}" }, { "code": null, "e": 6605, "s": 6602, "text": "-1" }, { "code": null, "e": 6627, "s": 6605, "text": "pritamaber1 month ago" }, { "code": null, "e": 7328, "s": 6627, "text": " vector<int> res;\n \n if(n==1){\n for(int i=0; i<m; i++){\n res.push_back(matrix[0][i]);\n }\n }else if(m==1){\n for(int i=0; i<n; i++){\n res.push_back(matrix[i][0]);\n }\n }else{\n for(int i=0; i<m; i++){\n res.push_back(matrix[0][i]);\n }\n for(int i=1; i<n; i++){\n res.push_back(matrix[i][m-1]);\n }\n for(int i=m-2;i>=0;i--){\n res.push_back(matrix[n-1][i]);\n }\n for(int i=n-2; i>=1;i--){\n res.push_back(matrix[i][0]);\n } \n }\n return res;" }, { "code": null, "e": 7331, "s": 7328, "text": "-1" }, { "code": null, "e": 7358, "s": 7331, "text": "akshatmathur232 months ago" }, { "code": null, "e": 7372, "s": 7358, "text": "JAVA SOLUTION" }, { "code": null, "e": 8448, "s": 7372, "text": "class Solution{ //Function to return list of integers that form the boundary //traversal of the matrix in a clockwise manner. static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m) { // code here ArrayList<Integer> list = new ArrayList<>(); if(matrix == null || n == 0) return list; int top = 0, left = 0, bottom = n - 1, right = m - 1; if(n == 1) { for(int i = left; i<= right; i++) list.add(matrix[top][i]); return list; } if(m == 1) { for(int i = top; i <= bottom; i++) list.add(matrix[i][right]); return list; } for(int i = left; i <= right; i++) list.add(matrix[top][i]); top++; for(int i = top; i <= bottom; i++) list.add(matrix[i][right]); right--; for(int i = right; i >= left; i--) list.add(matrix[bottom][i]); bottom--; for(int i = bottom; i >= top; i--) list.add(matrix[i][left]); left++; return list; }} " }, { "code": null, "e": 8451, "s": 8448, "text": "-1" }, { "code": null, "e": 8479, "s": 8451, "text": "subhammahanta183 months ago" }, { "code": null, "e": 8495, "s": 8479, "text": "//Java Solution" }, { "code": null, "e": 9385, "s": 8497, "text": "class Solution{ //Function to return list of integers that form the boundary //traversal of the matrix in a clockwise manner. static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m) { ArrayList<Integer>ar=new ArrayList<>(); int j; for(int i=0;i<n;i++) { if(i==0 || i==n-1) { if(i==0) { for(j=0;j<m;j++) ar.add(matrix[i][j]); } else { for(j=m-1;j>=0;j--) ar.add(matrix[i][j]); if(matrix[i].length==1) continue; while((i-1)!=0) { i--; ar.add(matrix[i][0]); } break; } } else { j=m-1; ar.add(matrix[i][j]); } } return ar; }} " }, { "code": null, "e": 9388, "s": 9385, "text": "-1" }, { "code": null, "e": 9416, "s": 9388, "text": "rohithsowmithra3 months ago" }, { "code": null, "e": 9424, "s": 9416, "text": "python:" }, { "code": null, "e": 9434, "s": 9424, "text": "=========" }, { "code": null, "e": 9906, "s": 9434, "text": "def BoundaryTraversal(self,matrix, n, m): # code here res = [] for i in range(m): res.append(matrix[0][i]) if n > 1: for i in range(1, n): res.append(matrix[i][m-1]) if m > 1: for i in range(m-2,0,-1): res.append(matrix[n-1][i]) for i in range(n-1, 0, -1): res.append(matrix[i][0]) return res" }, { "code": null, "e": 10052, "s": 9906, "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": 10088, "s": 10052, "text": " Login to access your submissions. " }, { "code": null, "e": 10098, "s": 10088, "text": "\nProblem\n" }, { "code": null, "e": 10108, "s": 10098, "text": "\nContest\n" }, { "code": null, "e": 10171, "s": 10108, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 10319, "s": 10171, "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": 10527, "s": 10319, "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": 10633, "s": 10527, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
JavaScript String concat() Method - GeeksforGeeks
05 Oct, 2021 Below is the example of the concat() Method Method. Example:<script> // JavaScript to illustrate concat() function function func() { // Original string var str = 'Geeks'; // Joining the strings together var value = str.concat(' for',' Geeks'); document.write(value); } func(); </script> <script> // JavaScript to illustrate concat() function function func() { // Original string var str = 'Geeks'; // Joining the strings together var value = str.concat(' for',' Geeks'); document.write(value); } func(); </script> Output:Geeks for Geeks Geeks for Geeks str.concat() function is used to join two or more strings together in JavaScript. Syntax: str.concat(string2, string3, string4,......, stringN) Arguments:The arguments to this function are the strings that need to be joined together. The number of arguments to this function is equal to the number of strings to be joined together. Return value:This function returns a new string that is the combination of all the different strings passed to it as the argument. Example for the above function is provided below: Example 1: print('It'.concat(' is',' a',' great',' day.')); Output: It is a great day. In this example the function concat() joins together “It” with ” is”, ” a”, ” great”, “day.” to create a final string containing all the strings. Code for the above function is provided below: Program 1: <script>// JavaScript to illustrate concat() functionfunction func() { // Original string var str = 'It'; // Joining the strings together var value = str.concat(' is',' a',' great',' day.'); document.write(value); }func();</script> Output: It is a great day. Supported Browsers: Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 4 and above Opera 4 and above Safari 1 and above ysachin2314 javascript-string JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25789, "s": 25761, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25841, "s": 25789, "text": "Below is the example of the concat() Method Method." }, { "code": null, "e": 26105, "s": 25841, "text": "Example:<script> // JavaScript to illustrate concat() function function func() { // Original string var str = 'Geeks'; // Joining the strings together var value = str.concat(' for',' Geeks'); document.write(value); } func(); </script> " }, { "code": "<script> // JavaScript to illustrate concat() function function func() { // Original string var str = 'Geeks'; // Joining the strings together var value = str.concat(' for',' Geeks'); document.write(value); } func(); </script> ", "e": 26361, "s": 26105, "text": null }, { "code": null, "e": 26385, "s": 26361, "text": "Output:Geeks for Geeks\n" }, { "code": null, "e": 26402, "s": 26385, "text": "Geeks for Geeks\n" }, { "code": null, "e": 26484, "s": 26402, "text": "str.concat() function is used to join two or more strings together in JavaScript." }, { "code": null, "e": 26492, "s": 26484, "text": "Syntax:" }, { "code": null, "e": 26546, "s": 26492, "text": "str.concat(string2, string3, string4,......, stringN)" }, { "code": null, "e": 26734, "s": 26546, "text": "Arguments:The arguments to this function are the strings that need to be joined together. The number of arguments to this function is equal to the number of strings to be joined together." }, { "code": null, "e": 26865, "s": 26734, "text": "Return value:This function returns a new string that is the combination of all the different strings passed to it as the argument." }, { "code": null, "e": 26915, "s": 26865, "text": "Example for the above function is provided below:" }, { "code": null, "e": 26926, "s": 26915, "text": "Example 1:" }, { "code": null, "e": 26976, "s": 26926, "text": "print('It'.concat(' is',' a',' great',' day.'));\n" }, { "code": null, "e": 26984, "s": 26976, "text": "Output:" }, { "code": null, "e": 27004, "s": 26984, "text": "It is a great day.\n" }, { "code": null, "e": 27150, "s": 27004, "text": "In this example the function concat() joins together “It” with ” is”, ” a”, ” great”, “day.” to create a final string containing all the strings." }, { "code": null, "e": 27197, "s": 27150, "text": "Code for the above function is provided below:" }, { "code": null, "e": 27208, "s": 27197, "text": "Program 1:" }, { "code": "<script>// JavaScript to illustrate concat() functionfunction func() { // Original string var str = 'It'; // Joining the strings together var value = str.concat(' is',' a',' great',' day.'); document.write(value); }func();</script> ", "e": 27463, "s": 27208, "text": null }, { "code": null, "e": 27471, "s": 27463, "text": "Output:" }, { "code": null, "e": 27491, "s": 27471, "text": "It is a great day.\n" }, { "code": null, "e": 27511, "s": 27491, "text": "Supported Browsers:" }, { "code": null, "e": 27530, "s": 27511, "text": "Chrome 1 and above" }, { "code": null, "e": 27548, "s": 27530, "text": "Edge 12 and above" }, { "code": null, "e": 27568, "s": 27548, "text": "Firefox 1 and above" }, { "code": null, "e": 27598, "s": 27568, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 27616, "s": 27598, "text": "Opera 4 and above" }, { "code": null, "e": 27635, "s": 27616, "text": "Safari 1 and above" }, { "code": null, "e": 27647, "s": 27635, "text": "ysachin2314" }, { "code": null, "e": 27665, "s": 27647, "text": "javascript-string" }, { "code": null, "e": 27676, "s": 27665, "text": "JavaScript" }, { "code": null, "e": 27693, "s": 27676, "text": "Web Technologies" }, { "code": null, "e": 27791, "s": 27693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27831, "s": 27791, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27876, "s": 27831, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27937, "s": 27876, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28009, "s": 27937, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28055, "s": 28009, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28095, "s": 28055, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28128, "s": 28095, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28173, "s": 28128, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28216, "s": 28173, "text": "How to fetch data from an API in ReactJS ?" } ]
Flutter - File Structure - GeeksforGeeks
23 Feb, 2022 Flutter in 2021 is the rising star in the field of cross-platform app development. Be it a student’s college project, a small startup, a unicorn or big tech giants all are using flutter. The file structure is the organization of the data of an application. The file structure is something that plays a very important role in the effective and easy management of the project be it of any size. As the size of a project grows, it becomes more and more important to have a proper structure and format for the code otherwise it can lead to many undesired problems such as: Unable to find the specific file in a repository, making it a time-consuming task. Unfit for teamwork. Difficult to maintain. Or in the worst-case scenario, it can result in low performant app. Note: There is a package available for minimizing this task without spending much time on creating or organizing files in flutter. If you wanted to create your own you can follow the below steps. To take charge of all these problems we need to have a good file structure in our flutter app, and that is what we are going to discuss in this article. Although flutter does not give any recommendations in the structuring of the app, still we should do it in the best possible manner. To achieve the best possible file structure of a general flutter application we will divide it into seven parts. But before that one important thing that we always need to keep in mind is the naming of the file and directories must always be in the proper format. For instance, if someone is creating a social media app and wants to make a file to store data of its uses, then this is how it should be named. Naming for files and directories //this is the right method user_data.dart (lower case for both words separated by underscore) //these methods should be avoided userData.dart (camel case) UserData.dart (upper case for both words) Loginview.dart (upper case for first word) Login_View.dart (upper case for both words separated by underscore) Whenever we create a new project in flutter these are the files and directories that we are provided with. But these are just the bare basics we will add some other folders and files in the project that are listed below. 1. Assets: Static assets for the app. This directory is on the root level will contain all the static assets that are used in the application, for example, fonts, icons, logos, background images, demo videos, etc. It is very much recommended that we should have different directories for a different type of data for example images, videos & logos, should have a different folder of their own so that it becomes easier to maintain and access them. 2. Cloud Functions: Cloud functions used in the app. Cloud functions are the back-end code is stored on some servers such as Google Cloud, these functions run when some specific event happens. An example of the cloud function in social media would be a function which at the click of a button opens a URL that receives the text, audio, or video data and stores it on the server for future use. It becomes very convenient when all the cloud function is on the root level of the application. 3. Screens: Screen /UI of the app. This directory will contain the actual layout of the UI for the entire application. It can further be distributed into two-three folders. One which stored the flash screen and onboarding pages such as login/sign-up screen, the second folder can store the home screen and other generally used screens, and the third folder can contain screens that are not that important 4. Providers: Interactions outside the app. This directory is supposed to hold all the interactions that transact the data from outside the app. This is different from the cloud functions, in regards to that none of the code in this directory will interact will cloud storage or server. If we take into consideration a weather app a good example would be the weather and the location data that is received from the API in the form of JSON that needs to be translated for use. 5. Utilities: Function or logic used in the app. This directory will hold all the app logic or business logic of our entire application. Again a good example in the weather app would be when a user selects a different location the weather data should also change accordingly. Or in the case of the social media app when logins the app data should also change accordingly. 6. Widgets: Widgets / Layouts used in the app. It becomes clear all by the name itself that this folder will hold all the static widgets or the widgets that are used multiple times in the application. For example, if it is a social media app like Instagram, the list view of all the suggested friends is always the same, the only thing that changes in the data. Or if it is a weather app the tile which shows a particular location is the same for all the location, the only thing that change is the name of the place. 7. Models: Collection of data. Models are the collection of data that are usually sourced from the servers, users, or external APIs, these are used in combination with widgets to complete the user interface of the app. Again, taking an example of the weather app a model or a set of data could be the name of the location, temperature in both Celsius and Fahrenheit. If we take into consideration a social media app that is showing a user’s profile page then it may contain the username, age, a profile pic, a description, etc. To a beginner, it might seem absurd or useless to bifurcate a flutter application into so many portions, but if maintaining a good file structure becomes a habit it could be many benefits. And for big organizations working on production applications, maintaining a good file structure is not an option it’s a necessity. akshaysingh98088 mujmildafedaar samitkapoor77 android Flutter Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Checkbox Widget Flutter - Flexible Widget Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Checkbox Widget Flutter - Flexible Widget
[ { "code": null, "e": 26469, "s": 26441, "text": "\n23 Feb, 2022" }, { "code": null, "e": 27038, "s": 26469, "text": "Flutter in 2021 is the rising star in the field of cross-platform app development. Be it a student’s college project, a small startup, a unicorn or big tech giants all are using flutter. The file structure is the organization of the data of an application. The file structure is something that plays a very important role in the effective and easy management of the project be it of any size. As the size of a project grows, it becomes more and more important to have a proper structure and format for the code otherwise it can lead to many undesired problems such as:" }, { "code": null, "e": 27121, "s": 27038, "text": "Unable to find the specific file in a repository, making it a time-consuming task." }, { "code": null, "e": 27141, "s": 27121, "text": "Unfit for teamwork." }, { "code": null, "e": 27164, "s": 27141, "text": "Difficult to maintain." }, { "code": null, "e": 27232, "s": 27164, "text": "Or in the worst-case scenario, it can result in low performant app." }, { "code": null, "e": 27428, "s": 27232, "text": "Note: There is a package available for minimizing this task without spending much time on creating or organizing files in flutter. If you wanted to create your own you can follow the below steps." }, { "code": null, "e": 28123, "s": 27428, "text": "To take charge of all these problems we need to have a good file structure in our flutter app, and that is what we are going to discuss in this article. Although flutter does not give any recommendations in the structuring of the app, still we should do it in the best possible manner. To achieve the best possible file structure of a general flutter application we will divide it into seven parts. But before that one important thing that we always need to keep in mind is the naming of the file and directories must always be in the proper format. For instance, if someone is creating a social media app and wants to make a file to store data of its uses, then this is how it should be named." }, { "code": null, "e": 28464, "s": 28123, "text": "Naming for files and directories\n//this is the right method\nuser_data.dart (lower case for both words separated by underscore)\n//these methods should be avoided\nuserData.dart (camel case)\nUserData.dart (upper case for both words)\nLoginview.dart (upper case for first word)\nLogin_View.dart (upper case for both words separated by underscore)" }, { "code": null, "e": 28685, "s": 28464, "text": "Whenever we create a new project in flutter these are the files and directories that we are provided with. But these are just the bare basics we will add some other folders and files in the project that are listed below." }, { "code": null, "e": 28724, "s": 28685, "text": "1. Assets: Static assets for the app." }, { "code": null, "e": 29134, "s": 28724, "text": "This directory is on the root level will contain all the static assets that are used in the application, for example, fonts, icons, logos, background images, demo videos, etc. It is very much recommended that we should have different directories for a different type of data for example images, videos & logos, should have a different folder of their own so that it becomes easier to maintain and access them." }, { "code": null, "e": 29187, "s": 29134, "text": "2. Cloud Functions: Cloud functions used in the app." }, { "code": null, "e": 29624, "s": 29187, "text": "Cloud functions are the back-end code is stored on some servers such as Google Cloud, these functions run when some specific event happens. An example of the cloud function in social media would be a function which at the click of a button opens a URL that receives the text, audio, or video data and stores it on the server for future use. It becomes very convenient when all the cloud function is on the root level of the application." }, { "code": null, "e": 29659, "s": 29624, "text": "3. Screens: Screen /UI of the app." }, { "code": null, "e": 30029, "s": 29659, "text": "This directory will contain the actual layout of the UI for the entire application. It can further be distributed into two-three folders. One which stored the flash screen and onboarding pages such as login/sign-up screen, the second folder can store the home screen and other generally used screens, and the third folder can contain screens that are not that important" }, { "code": null, "e": 30073, "s": 30029, "text": "4. Providers: Interactions outside the app." }, { "code": null, "e": 30505, "s": 30073, "text": "This directory is supposed to hold all the interactions that transact the data from outside the app. This is different from the cloud functions, in regards to that none of the code in this directory will interact will cloud storage or server. If we take into consideration a weather app a good example would be the weather and the location data that is received from the API in the form of JSON that needs to be translated for use." }, { "code": null, "e": 30554, "s": 30505, "text": "5. Utilities: Function or logic used in the app." }, { "code": null, "e": 30877, "s": 30554, "text": "This directory will hold all the app logic or business logic of our entire application. Again a good example in the weather app would be when a user selects a different location the weather data should also change accordingly. Or in the case of the social media app when logins the app data should also change accordingly." }, { "code": null, "e": 30924, "s": 30877, "text": "6. Widgets: Widgets / Layouts used in the app." }, { "code": null, "e": 31396, "s": 30924, "text": "It becomes clear all by the name itself that this folder will hold all the static widgets or the widgets that are used multiple times in the application. For example, if it is a social media app like Instagram, the list view of all the suggested friends is always the same, the only thing that changes in the data. Or if it is a weather app the tile which shows a particular location is the same for all the location, the only thing that change is the name of the place." }, { "code": null, "e": 31427, "s": 31396, "text": "7. Models: Collection of data." }, { "code": null, "e": 31924, "s": 31427, "text": "Models are the collection of data that are usually sourced from the servers, users, or external APIs, these are used in combination with widgets to complete the user interface of the app. Again, taking an example of the weather app a model or a set of data could be the name of the location, temperature in both Celsius and Fahrenheit. If we take into consideration a social media app that is showing a user’s profile page then it may contain the username, age, a profile pic, a description, etc." }, { "code": null, "e": 32244, "s": 31924, "text": "To a beginner, it might seem absurd or useless to bifurcate a flutter application into so many portions, but if maintaining a good file structure becomes a habit it could be many benefits. And for big organizations working on production applications, maintaining a good file structure is not an option it’s a necessity." }, { "code": null, "e": 32261, "s": 32244, "text": "akshaysingh98088" }, { "code": null, "e": 32276, "s": 32261, "text": "mujmildafedaar" }, { "code": null, "e": 32290, "s": 32276, "text": "samitkapoor77" }, { "code": null, "e": 32298, "s": 32290, "text": "android" }, { "code": null, "e": 32306, "s": 32298, "text": "Flutter" }, { "code": null, "e": 32313, "s": 32306, "text": "Picked" }, { "code": null, "e": 32318, "s": 32313, "text": "Dart" }, { "code": null, "e": 32326, "s": 32318, "text": "Flutter" }, { "code": null, "e": 32424, "s": 32326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32456, "s": 32424, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 32495, "s": 32456, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32521, "s": 32495, "text": "ListView Class in Flutter" }, { "code": null, "e": 32547, "s": 32521, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 32573, "s": 32547, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 32605, "s": 32573, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 32644, "s": 32605, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32661, "s": 32644, "text": "Flutter Tutorial" }, { "code": null, "e": 32687, "s": 32661, "text": "Flutter - Checkbox Widget" } ]
How to install the ext-curl extension with PHP 7 ? - GeeksforGeeks
06 Oct, 2021 The ext-curl CURL stands for client user, In Linux cURL is a PHP extension, that allows us to receive and send information via the URL syntax. And ext-curl is the extension in the latest PHP-7 which is loaded with some of the advanced features of the basic curls. The following are the steps to add ext-curl extension in Ubuntu – 1. Update the Extension sudo apt-get update 2. Install PHP-curl sudo apt-get install php-curl OR sudo apt-get install php7.0-curl During this command the system while ask for your confirmation and if you have to install you have to press ‘y’ key 3. Restart the extension to avoid any problem in the future by the extension sudo service apache2 restart After, all the above steps your ext-curl PHP-7 is successfully installing and is ready to use. gabaa406 how-to-install PHP-Misc Picked How To Installation Guide PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Install Jupyter Notebook on MacOS? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 26431, "s": 26403, "text": "\n06 Oct, 2021" }, { "code": null, "e": 26695, "s": 26431, "text": "The ext-curl CURL stands for client user, In Linux cURL is a PHP extension, that allows us to receive and send information via the URL syntax. And ext-curl is the extension in the latest PHP-7 which is loaded with some of the advanced features of the basic curls." }, { "code": null, "e": 26761, "s": 26695, "text": "The following are the steps to add ext-curl extension in Ubuntu –" }, { "code": null, "e": 26785, "s": 26761, "text": "1. Update the Extension" }, { "code": null, "e": 26805, "s": 26785, "text": "sudo apt-get update" }, { "code": null, "e": 26825, "s": 26805, "text": "2. Install PHP-curl" }, { "code": null, "e": 26904, "s": 26825, "text": "sudo apt-get install php-curl\n OR\nsudo apt-get install php7.0-curl" }, { "code": null, "e": 27020, "s": 26904, "text": "During this command the system while ask for your confirmation and if you have to install you have to press ‘y’ key" }, { "code": null, "e": 27097, "s": 27020, "text": "3. Restart the extension to avoid any problem in the future by the extension" }, { "code": null, "e": 27126, "s": 27097, "text": "sudo service apache2 restart" }, { "code": null, "e": 27221, "s": 27126, "text": "After, all the above steps your ext-curl PHP-7 is successfully installing and is ready to use." }, { "code": null, "e": 27230, "s": 27221, "text": "gabaa406" }, { "code": null, "e": 27245, "s": 27230, "text": "how-to-install" }, { "code": null, "e": 27254, "s": 27245, "text": "PHP-Misc" }, { "code": null, "e": 27261, "s": 27254, "text": "Picked" }, { "code": null, "e": 27268, "s": 27261, "text": "How To" }, { "code": null, "e": 27287, "s": 27268, "text": "Installation Guide" }, { "code": null, "e": 27291, "s": 27287, "text": "PHP" }, { "code": null, "e": 27308, "s": 27291, "text": "Web Technologies" }, { "code": null, "e": 27312, "s": 27308, "text": "PHP" }, { "code": null, "e": 27410, "s": 27312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27444, "s": 27410, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27502, "s": 27444, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 27551, "s": 27502, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 27598, "s": 27551, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 27640, "s": 27598, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 27673, "s": 27640, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27707, "s": 27673, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27742, "s": 27707, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 27800, "s": 27742, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
GATE | GATE-CS-2001 | Question 41 - GeeksforGeeks
28 Jun, 2021 What is the minimum number of stacks of size n required to implement a queue of size n?(A) One(B) Two(C) Three(D) FourAnswer: (B)Explanation: A queue can be implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be stack1 and stack2. q can be implemented in two ways: Method 1 (By making enQueue operation costly)This method makes sure that newly entered element is always at the top of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used. enQueue(q, x) 1) While stack1 is not empty, push everything from satck1 to stack2. 2) Push x to stack1 (assuming size of stacks is unlimited). 3) Push everything back to stack1. dnQueue(q) 1) If stack1 is empty then error 2) Pop an item from stack1 and return it Method 2 (By making deQueue operation costly)In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned. enQueue(q, x) 1) Push x to stack1 (assuming size of stacks is unlimited). deQueue(q) 1) If both stacks are empty then error. 2) If stack2 is empty While stack1 is not empty, push everything from satck1 to stack2. 3) Pop the element from stack2 and return it. Source: https://www.geeksforgeeks.org/queue-using-stacks/Quiz of this Question GATE-CS-2001 GATE-GATE-CS-2001 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25695, "s": 25667, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26003, "s": 25695, "text": "What is the minimum number of stacks of size n required to implement a queue of size n?(A) One(B) Two(C) Three(D) FourAnswer: (B)Explanation: A queue can be implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be stack1 and stack2. q can be implemented in two ways: " }, { "code": null, "e": 26233, "s": 26003, "text": "Method 1 (By making enQueue operation costly)This method makes sure that newly entered element is always at the top of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used." }, { "code": null, "e": 26508, "s": 26233, "text": "enQueue(q, x)\n 1) While stack1 is not empty, push everything from satck1 to stack2.\n 2) Push x to stack1 (assuming size of stacks is unlimited).\n 3) Push everything back to stack1.\n\ndnQueue(q)\n 1) If stack1 is empty then error\n 2) Pop an item from stack1 and return it\n" }, { "code": null, "e": 26764, "s": 26508, "text": "Method 2 (By making deQueue operation costly)In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned." }, { "code": null, "e": 27041, "s": 26764, "text": "enQueue(q, x)\n 1) Push x to stack1 (assuming size of stacks is unlimited).\n\ndeQueue(q)\n 1) If both stacks are empty then error.\n 2) If stack2 is empty\n While stack1 is not empty, push everything from satck1 to stack2.\n 3) Pop the element from stack2 and return it.\n" }, { "code": null, "e": 27120, "s": 27041, "text": "Source: https://www.geeksforgeeks.org/queue-using-stacks/Quiz of this Question" }, { "code": null, "e": 27133, "s": 27120, "text": "GATE-CS-2001" }, { "code": null, "e": 27151, "s": 27133, "text": "GATE-GATE-CS-2001" }, { "code": null, "e": 27156, "s": 27151, "text": "GATE" }, { "code": null, "e": 27254, "s": 27156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27288, "s": 27254, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27322, "s": 27288, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27356, "s": 27322, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27389, "s": 27356, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27425, "s": 27389, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27459, "s": 27425, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27495, "s": 27459, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27529, "s": 27495, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27563, "s": 27529, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Retrieve Data From TextFields in Flutter - GeeksforGeeks
14 Aug, 2020 In this article, we’ll learn how to retrieve data from TextFields. TextField() widget is the most common widget used in flutter apps to take user input. We’ll talk about two major methods used to extract text from TextField. The TextField widget has various callback properties through which we can extract text. Majorly, onChanged is used as it takes input on every change incurred in the TextField. This callback doesn’t work when TextField’s text is changed programmatically. Basically, this kind of change is initiated by the app itself. Syntax: TextField( onChanged: (value) { print("The value entered is : $value"); } ) Various other callbacks are also available for TextFields like onTap, onSubmitted, onEditingComplete. onTap: It is called for each unique tap except for every second tap of double-tap. Internally, it builds a GestureDetector to handle this kind of event. You can use it whenever you want to trigger some property of TextField which is gesture-based. onSubmitted: It is called whenever the user indicates that they are done with editing the text. Primarily, whenever the done button is pressed on the keyboard, it will be called and the data entered would be stored. onEditingComplete: It is very similar to onSubmitted. The only difference is that it is called whenever the button in the bottom right corner of the keyboard is pressed. It might be ‘done’, ‘send’, ‘go’, or ‘search’. Example: Below is the example of onChanged in TextField. Here, we have used an anonymous function to receive a callback from onChanged. The value from callback is received in value, then we pass it to our variable title. Dart import "package:flutter/material.dart"; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Home(), ); }} class Home extends StatefulWidget { @override _HomeState createState() => _HomeState();} class _HomeState extends State<Home> { // var to store // onChanged callback String title; String text = "No Value Entered"; void _setText() { setState(() { text = title; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Column( children: [ Padding( padding: const EdgeInsets.all(15), child: TextField( decoration: InputDecoration(labelText: 'Title'), onChanged: (value) => title = value, ), ), SizedBox( height: 8, ), RaisedButton( onPressed: _setText, child: Text('Submit'), elevation: 8, ), SizedBox( height: 20, ), Text(text), // changes in text // are shown here ], ), ); }} Output Another way to retrieve text is by using the controller. It is a property that flutter provides with TextField. Below are the steps explaining the use of the controller. First, create an object of the class TextEditingController(). It is the default class that is provided by flutter. Connect the object created to the controller of the TextField. Now, you may create a function to get the latest value. It works almost the same way as onChanged. But, in certain scenarios, it is preferred to use controller as the retrieving process is managed by the flutter engine. Example: The below example, explains using the controller for retrieving values from TextField. Firstly, create an object of type TextEditingController. Then we assign this object to the controller property of TextField. Dart import "package:flutter/material.dart"; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Home(), ); }} class Home extends StatefulWidget { @override _HomeState createState() => _HomeState();} class _HomeState extends State<Home> { final titleController = TextEditingController(); String text = "No Value Entered"; void _setText() { setState(() { text = titleController.text; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Column( children: [ Padding( padding: const EdgeInsets.all(15), child: TextField( decoration: InputDecoration(labelText: 'Title'), controller: titleController, ), ), SizedBox( height: 8, ), RaisedButton( onPressed: _setText, child: Text('Submit'), elevation: 8, ), SizedBox( height: 20, ), Text(text), ], ), ); }} Output Both methods can be used for retrieving text, as the output of both are the same. Here, we had to re-run the build method to update text, hence we have used a stateful widget. If, in your program, you just want to store the value, a stateless widget can also be used. Flutter Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Android Studio Setup for Flutter Development Flutter - Positioned Widget Format Dates in Flutter Flutter - Managing the MediaQuery Object What is widgets in Flutter?
[ { "code": null, "e": 25287, "s": 25259, "text": "\n14 Aug, 2020" }, { "code": null, "e": 25512, "s": 25287, "text": "In this article, we’ll learn how to retrieve data from TextFields. TextField() widget is the most common widget used in flutter apps to take user input. We’ll talk about two major methods used to extract text from TextField." }, { "code": null, "e": 25829, "s": 25512, "text": "The TextField widget has various callback properties through which we can extract text. Majorly, onChanged is used as it takes input on every change incurred in the TextField. This callback doesn’t work when TextField’s text is changed programmatically. Basically, this kind of change is initiated by the app itself." }, { "code": null, "e": 25927, "s": 25829, "text": "Syntax:\nTextField(\n onChanged: (value) {\n print(\"The value entered is : $value\");\n }\n)\n" }, { "code": null, "e": 26029, "s": 25927, "text": "Various other callbacks are also available for TextFields like onTap, onSubmitted, onEditingComplete." }, { "code": null, "e": 26277, "s": 26029, "text": "onTap: It is called for each unique tap except for every second tap of double-tap. Internally, it builds a GestureDetector to handle this kind of event. You can use it whenever you want to trigger some property of TextField which is gesture-based." }, { "code": null, "e": 26493, "s": 26277, "text": "onSubmitted: It is called whenever the user indicates that they are done with editing the text. Primarily, whenever the done button is pressed on the keyboard, it will be called and the data entered would be stored." }, { "code": null, "e": 26710, "s": 26493, "text": "onEditingComplete: It is very similar to onSubmitted. The only difference is that it is called whenever the button in the bottom right corner of the keyboard is pressed. It might be ‘done’, ‘send’, ‘go’, or ‘search’." }, { "code": null, "e": 26719, "s": 26710, "text": "Example:" }, { "code": null, "e": 26931, "s": 26719, "text": "Below is the example of onChanged in TextField. Here, we have used an anonymous function to receive a callback from onChanged. The value from callback is received in value, then we pass it to our variable title." }, { "code": null, "e": 26936, "s": 26931, "text": "Dart" }, { "code": "import \"package:flutter/material.dart\"; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Home(), ); }} class Home extends StatefulWidget { @override _HomeState createState() => _HomeState();} class _HomeState extends State<Home> { // var to store // onChanged callback String title; String text = \"No Value Entered\"; void _setText() { setState(() { text = title; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Column( children: [ Padding( padding: const EdgeInsets.all(15), child: TextField( decoration: InputDecoration(labelText: 'Title'), onChanged: (value) => title = value, ), ), SizedBox( height: 8, ), RaisedButton( onPressed: _setText, child: Text('Submit'), elevation: 8, ), SizedBox( height: 20, ), Text(text), // changes in text // are shown here ], ), ); }}", "e": 28257, "s": 26936, "text": null }, { "code": null, "e": 28264, "s": 28257, "text": "Output" }, { "code": null, "e": 28434, "s": 28264, "text": "Another way to retrieve text is by using the controller. It is a property that flutter provides with TextField. Below are the steps explaining the use of the controller." }, { "code": null, "e": 28550, "s": 28434, "text": "First, create an object of the class TextEditingController(). It is the default class that is provided by flutter." }, { "code": null, "e": 28613, "s": 28550, "text": "Connect the object created to the controller of the TextField." }, { "code": null, "e": 28669, "s": 28613, "text": "Now, you may create a function to get the latest value." }, { "code": null, "e": 28833, "s": 28669, "text": "It works almost the same way as onChanged. But, in certain scenarios, it is preferred to use controller as the retrieving process is managed by the flutter engine." }, { "code": null, "e": 28842, "s": 28833, "text": "Example:" }, { "code": null, "e": 29054, "s": 28842, "text": "The below example, explains using the controller for retrieving values from TextField. Firstly, create an object of type TextEditingController. Then we assign this object to the controller property of TextField." }, { "code": null, "e": 29059, "s": 29054, "text": "Dart" }, { "code": "import \"package:flutter/material.dart\"; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Home(), ); }} class Home extends StatefulWidget { @override _HomeState createState() => _HomeState();} class _HomeState extends State<Home> { final titleController = TextEditingController(); String text = \"No Value Entered\"; void _setText() { setState(() { text = titleController.text; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Column( children: [ Padding( padding: const EdgeInsets.all(15), child: TextField( decoration: InputDecoration(labelText: 'Title'), controller: titleController, ), ), SizedBox( height: 8, ), RaisedButton( onPressed: _setText, child: Text('Submit'), elevation: 8, ), SizedBox( height: 20, ), Text(text), ], ), ); }}", "e": 30321, "s": 29059, "text": null }, { "code": null, "e": 30328, "s": 30321, "text": "Output" }, { "code": null, "e": 30596, "s": 30328, "text": "Both methods can be used for retrieving text, as the output of both are the same. Here, we had to re-run the build method to update text, hence we have used a stateful widget. If, in your program, you just want to store the value, a stateless widget can also be used." }, { "code": null, "e": 30604, "s": 30596, "text": "Flutter" }, { "code": null, "e": 30609, "s": 30604, "text": "Dart" }, { "code": null, "e": 30707, "s": 30609, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30746, "s": 30707, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30772, "s": 30746, "text": "ListView Class in Flutter" }, { "code": null, "e": 30798, "s": 30772, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 30821, "s": 30798, "text": "Flutter - Stack Widget" }, { "code": null, "e": 30839, "s": 30821, "text": "Flutter - Dialogs" }, { "code": null, "e": 30884, "s": 30839, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 30912, "s": 30884, "text": "Flutter - Positioned Widget" }, { "code": null, "e": 30936, "s": 30912, "text": "Format Dates in Flutter" }, { "code": null, "e": 30977, "s": 30936, "text": "Flutter - Managing the MediaQuery Object" } ]
How to include inline JavaScript inside an HTML page?
JavaScript is used in HTML using the <script>...</script> or using External JavaScript file. Well, there’s another way through which you can include inline JavaScript inside an HTML page. Generally, the HTML event attributes calls functions specified elsewhere in script tags. But, you can also add the JavaScript code directly to the onClick event tags. Note: Adding inline JavaScript isn’t considered a good practice according to coding standards and shouldn’t be followed. <p> <a href="#" onClick="alert('Hello World');"> Click </a> </p>
[ { "code": null, "e": 1250, "s": 1062, "text": "JavaScript is used in HTML using the <script>...</script> or using External JavaScript file. Well, there’s another way through which you can include inline JavaScript inside an HTML page." }, { "code": null, "e": 1417, "s": 1250, "text": "Generally, the HTML event attributes calls functions specified elsewhere in script tags. But, you can also add the JavaScript code directly to the onClick event tags." }, { "code": null, "e": 1538, "s": 1417, "text": "Note: Adding inline JavaScript isn’t considered a good practice according to coding standards and shouldn’t be followed." }, { "code": null, "e": 1615, "s": 1538, "text": "<p>\n <a href=\"#\" onClick=\"alert('Hello World');\">\n Click\n </a>\n</p>" } ]
C++ Program to Implement Stack Using Two Queues
The stack which is implemented as LIFO, where insertion and deletion are done from the same end, top. The last element that entered is deleted first. Stack operations are − push (int data) − Insertion at top int pop() − Deletion from top The queue which is implemented as FIFO where insertions are done at one end (rear) and deletions are done from another end (front). The first element that entered is deleted first. Queue operations are − EnQueue (int data) − Insertion at the rear end int DeQueue() − Deletion from front end This is a C++ Program to Implement Stack Using Two Queues Begin function enqueue1 to insert item a at qu1: Set, np1 = new qu1 np1->d1 = a np1->n1 = NULL if (f1 == NULL) Then set r1 = np1 r1->n1 = NULL f1 = r1 else r1->n1 = np1 r1 = np1 r1->n1 = NULL End Begin function dequeue1 to delete item from qu1. if queue is null Print no elements present in queue. Else q1 = f1 f1 = f1->n1 a = q1->d1 delete(q1) return a End Begin function enqueue2 to insert item a at qu2. np2 = new qu2; np2->d2 = a; np2->n2 = NULL; if queue is null Set r2 = np2 r2->n2 = NULL f2 = r2 Else Set r2->n2 = np2 r2 = np2 r2->n2 = NULL End Begin function dequeue2 to delete item from qu2: if queue is null Print no elements present in queue. Else q2 = f2 f2 = f2->n2 a = q2->d2 delete(q2) return a End #include<iostream> using namespace std; struct qu1// queue1 declaration { qu1 *n1; int d1; }*f1 = NULL, *r1 = NULL, *q1 = NULL, *p1 = NULL, *np1 = NULL; struct qu2// queue2 declaration { qu2 *n2; int d2; }*f2 = NULL, *r2 = NULL, *q2 = NULL, *p2 = NULL, *np2 = NULL; void enqueue1(int a) { np1 = new qu1; np1->d1 = a; np1->n1 = NULL; if (f1 == NULL) { r1 = np1; r1->n1 = NULL; f1 = r1; } else { r1->n1 = np1; r1 = np1; r1->n1 = NULL; } } int dequeue1() { int a; if (f1 == NULL) { cout<<"no elements present in queue\n"; } else { q1 = f1; f1 = f1->n1; a = q1->d1; delete(q1); return a; } } void enqueue2(int a) { np2 = new qu2; np2->d2 = a; np2->n2 = NULL; if (f2 == NULL) { r2 = np2; r2->n2 = NULL; f2 = r2; } else { r2->n2 = np2; r2 = np2; r2->n2 = NULL; } } int dequeue2() { int a; if (f2 == NULL) { cout<<"no elements present in queue\n"; } else { q2 = f2; f2 = f2->n2; a = q2->d2; delete(q2); return a; } } int main() { int n, a, i = 0; cout<<"Enter the number of elements to be entered into stack\n"; cin>>n; while (i < n) { cout<<"enter the element to be entered\n"; cin>>a; enqueue1(a); i++; } cout<<"\n\nElements popped\n\n"; while (f1 != NULL || f2 != NULL)// if both queues are not null { if (f2 == NULL)// if queue 2 is null { while (f1->n1 != NULL) { enqueue2(dequeue1()); } cout<<dequeue1()<<endl; } else if (f1 == NULL)//if queue 1 is null { while (f2->n2 != NULL) { enqueue1(dequeue2()); } cout<<dequeue2()<<endl; } } } Enter the number of elements to be entered into stack 5 enter the element to be entered 1 enter the element to be entered 2 enter the element to be entered 3 enter the element to be entered 4 enter the element to be entered 5 Elements popped 5 4 3 2 1
[ { "code": null, "e": 1212, "s": 1062, "text": "The stack which is implemented as LIFO, where insertion and deletion are done from the same end, top. The last element that entered is deleted first." }, { "code": null, "e": 1235, "s": 1212, "text": "Stack operations are −" }, { "code": null, "e": 1270, "s": 1235, "text": "push (int data) − Insertion at top" }, { "code": null, "e": 1300, "s": 1270, "text": "int pop() − Deletion from top" }, { "code": null, "e": 1481, "s": 1300, "text": "The queue which is implemented as FIFO where insertions are done at one end (rear) and deletions are done from another end (front). The first element that entered is deleted first." }, { "code": null, "e": 1504, "s": 1481, "text": "Queue operations are −" }, { "code": null, "e": 1551, "s": 1504, "text": "EnQueue (int data) − Insertion at the rear end" }, { "code": null, "e": 1591, "s": 1551, "text": "int DeQueue() − Deletion from front end" }, { "code": null, "e": 1649, "s": 1591, "text": "This is a C++ Program to Implement Stack Using Two Queues" }, { "code": null, "e": 2564, "s": 1649, "text": "Begin\n function enqueue1 to insert item a at qu1:\n Set, np1 = new qu1\n np1->d1 = a\n np1->n1 = NULL\n if (f1 == NULL)\n Then set\n r1 = np1\n r1->n1 = NULL\n f1 = r1\n else\n r1->n1 = np1\n r1 = np1\n r1->n1 = NULL\nEnd\n\nBegin\n function dequeue1 to delete item from qu1.\n if queue is null\n Print no elements present in queue.\n Else\n q1 = f1\n f1 = f1->n1\n a = q1->d1\n delete(q1)\n return a\nEnd\n\nBegin\n function enqueue2 to insert item a at qu2.\n np2 = new qu2;\n np2->d2 = a;\n np2->n2 = NULL;\n if queue is null\n Set r2 = np2\n r2->n2 = NULL\n f2 = r2\n Else\n Set r2->n2 = np2\n r2 = np2\n r2->n2 = NULL\nEnd\n\nBegin\n function dequeue2 to delete item from qu2:\n if queue is null\n Print no elements present in queue.\n Else\n q2 = f2\n f2 = f2->n2\n a = q2->d2\n delete(q2)\n return a\nEnd" }, { "code": null, "e": 4365, "s": 2564, "text": "#include<iostream>\nusing namespace std;\n\nstruct qu1// queue1 declaration {\n qu1 *n1;\n int d1;\n}*f1 = NULL, *r1 = NULL, *q1 = NULL, *p1 = NULL, *np1 = NULL;\n\nstruct qu2// queue2 declaration {\n qu2 *n2;\n int d2;\n}*f2 = NULL, *r2 = NULL, *q2 = NULL, *p2 = NULL, *np2 = NULL;\n\nvoid enqueue1(int a) {\n np1 = new qu1;\n np1->d1 = a;\n np1->n1 = NULL;\n if (f1 == NULL) {\n r1 = np1;\n r1->n1 = NULL;\n f1 = r1;\n } else {\n r1->n1 = np1;\n r1 = np1;\n r1->n1 = NULL;\n }\n}\n\nint dequeue1() {\n int a;\n if (f1 == NULL) {\n cout<<\"no elements present in queue\\n\";\n } else {\n q1 = f1;\n f1 = f1->n1;\n a = q1->d1;\n delete(q1);\n return a;\n }\n}\n\nvoid enqueue2(int a) {\n np2 = new qu2;\n np2->d2 = a;\n np2->n2 = NULL;\n if (f2 == NULL) {\n r2 = np2;\n r2->n2 = NULL;\n f2 = r2;\n } else {\n r2->n2 = np2;\n r2 = np2;\n r2->n2 = NULL;\n }\n}\n\nint dequeue2() {\n int a;\n if (f2 == NULL) {\n cout<<\"no elements present in queue\\n\";\n } else {\n q2 = f2;\n f2 = f2->n2;\n a = q2->d2;\n delete(q2);\n return a;\n }\n}\n\nint main() {\n int n, a, i = 0;\n cout<<\"Enter the number of elements to be entered into stack\\n\";\n cin>>n;\n while (i < n) {\n cout<<\"enter the element to be entered\\n\";\n cin>>a;\n enqueue1(a);\n i++;\n }\n cout<<\"\\n\\nElements popped\\n\\n\";\n while (f1 != NULL || f2 != NULL)// if both queues are not null {\n if (f2 == NULL)// if queue 2 is null {\n while (f1->n1 != NULL) {\n enqueue2(dequeue1());\n }\n cout<<dequeue1()<<endl;\n } else if (f1 == NULL)//if queue 1 is null {\n while (f2->n2 != NULL) {\n enqueue1(dequeue2());\n }\n cout<<dequeue2()<<endl;\n }\n }\n}" }, { "code": null, "e": 4618, "s": 4365, "text": "Enter the number of elements to be entered into stack\n5\nenter the element to be entered\n1\nenter the element to be entered\n2\nenter the element to be entered\n3\nenter the element to be entered\n4\nenter the element to be entered\n5\n\nElements popped\n5\n4\n3\n2\n1" } ]
How to put the origin in the center of the figure with Matplotlib ? - GeeksforGeeks
08 Oct, 2021 In this article, we are going to discuss how to put the origin in the center of the figure using the matplotlib module. To put the origin at the center of the figure we use the spines module from the matplotlib module. Basically, spines are the lines connecting the axis tick marks and noting the boundaries of the data area. Under this module, we use set_position() method which sets the position of the spine which helps to set the origin in the center. However, we can put the origin in the center of the figure without using set_position() method. The below graph is made without using set_position() method. Example 1: Python3 # import required modulesimport numpy as npimport matplotlib.pyplot as plt # assign coordinatesx = np.linspace(-np.pi, np.pi, 100)y = 2*np.sin(x) # depict illustrationplt.xlim(-np.pi, np.pi)plt.plot(x, y)plt.grid(True)plt.show() Output: The below graph is made with using set_position() method which helped to bring origin to the center. Example 2: Python3 # import required modulesimport numpy as npimport matplotlib.pyplot as plt # assign coordinatesx = np.linspace(-np.pi, np.pi, 100)y = 2*np.sin(x) # use set_positionax = plt.gca()ax.spines['top'].set_color('none')ax.spines['left'].set_position('zero')ax.spines['right'].set_color('none')ax.spines['bottom'].set_position('zero') # depict illustrationplt.xlim(-np.pi, np.pi)plt.plot(x, y)plt.grid(True)plt.show() Output: saurabh1990aror Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24748, "s": 24292, "text": "In this article, we are going to discuss how to put the origin in the center of the figure using the matplotlib module. To put the origin at the center of the figure we use the spines module from the matplotlib module. Basically, spines are the lines connecting the axis tick marks and noting the boundaries of the data area. Under this module, we use set_position() method which sets the position of the spine which helps to set the origin in the center." }, { "code": null, "e": 24905, "s": 24748, "text": "However, we can put the origin in the center of the figure without using set_position() method. The below graph is made without using set_position() method." }, { "code": null, "e": 24916, "s": 24905, "text": "Example 1:" }, { "code": null, "e": 24924, "s": 24916, "text": "Python3" }, { "code": "# import required modulesimport numpy as npimport matplotlib.pyplot as plt # assign coordinatesx = np.linspace(-np.pi, np.pi, 100)y = 2*np.sin(x) # depict illustrationplt.xlim(-np.pi, np.pi)plt.plot(x, y)plt.grid(True)plt.show()", "e": 25153, "s": 24924, "text": null }, { "code": null, "e": 25161, "s": 25153, "text": "Output:" }, { "code": null, "e": 25262, "s": 25161, "text": "The below graph is made with using set_position() method which helped to bring origin to the center." }, { "code": null, "e": 25273, "s": 25262, "text": "Example 2:" }, { "code": null, "e": 25281, "s": 25273, "text": "Python3" }, { "code": "# import required modulesimport numpy as npimport matplotlib.pyplot as plt # assign coordinatesx = np.linspace(-np.pi, np.pi, 100)y = 2*np.sin(x) # use set_positionax = plt.gca()ax.spines['top'].set_color('none')ax.spines['left'].set_position('zero')ax.spines['right'].set_color('none')ax.spines['bottom'].set_position('zero') # depict illustrationplt.xlim(-np.pi, np.pi)plt.plot(x, y)plt.grid(True)plt.show()", "e": 25691, "s": 25281, "text": null }, { "code": null, "e": 25699, "s": 25691, "text": "Output:" }, { "code": null, "e": 25715, "s": 25699, "text": "saurabh1990aror" }, { "code": null, "e": 25722, "s": 25715, "text": "Picked" }, { "code": null, "e": 25740, "s": 25722, "text": "Python-matplotlib" }, { "code": null, "e": 25747, "s": 25740, "text": "Python" }, { "code": null, "e": 25845, "s": 25747, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25854, "s": 25845, "text": "Comments" }, { "code": null, "e": 25867, "s": 25854, "text": "Old Comments" }, { "code": null, "e": 25899, "s": 25867, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25954, "s": 25899, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26010, "s": 25954, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26052, "s": 26010, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26094, "s": 26052, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26133, "s": 26094, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26155, "s": 26133, "text": "Defaultdict in Python" }, { "code": null, "e": 26176, "s": 26155, "text": "Python OOPs Concepts" }, { "code": null, "e": 26207, "s": 26176, "text": "Python | os.path.join() method" } ]
TreeSet with Customizable Sorting in Java - 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 tutorials, we are going to learn what is TreeSet in Java and how to apply customized sorting on TreeSet. TreeSet in java is the implementation of the NavigableSet. The underlying data structure for TreeSet is Balanced Tree. Since it is a Set, it doesn’t allow the duplicate values and insertion order is not preserved. But all Objects which are inserted in the tree set are stored according to the some default sorting order, that is in the case of numbers ascending and in the case of strings alphabetical orders. TreeSet(); It creates an empty TreeSet, where elements will be inserted according to default sorting order. TreeSet(Comparator c); It Creates an empty TreeSet, where the elements will be inserted according to the customized sorting Order. TreeSet(Collection c); It creates an empty TreeSet, containing the elements with the given collection. TreeSet(SortedSet c); It creates an empty TreeSet, containing the elements with sorting order with the given SortedSet. The underlying data structure for TreeSet is Balanced Tree. Since it is a Set implementation, duplicates are not allowed. Tree Set doesn’t maintain Insertion order. Tree Set allows the default sorting order. When we deal with the customize Sorting using TreeSet(Comparator c) constructor, the class should be implements Comparator interface. Though the Java collection framework allows the heterogeneous objects, but the TreeSet doesn’t allow heterogeneous elements. We can not insert null values into TreeSet. The underlying data structure for TreeSet is Balanced Tree. Since it is a Set implementation, duplicates are not allowed. Tree Set doesn’t maintain Insertion order. Tree Set allows the default sorting order. When we deal with the customize Sorting using TreeSet(Comparator c) constructor, the class should be implements Comparator interface. Though the Java collection framework allows the heterogeneous objects, but the TreeSet doesn’t allow heterogeneous elements. We can not insert null values into TreeSet. import java.util.Set; import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { Set set = new TreeSet(); set.add("A"); set.add("M"); set.add("b"); set.add("Q"); set.add("P"); set.add("a"); System.out.println("Tree : " + set); } } Output Tree : [A, M, P, Q, a, b] On the above, we can see the output with the default sorting order. import java.util.Set; import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { Set set = new TreeSet(); set.add("A"); set.add("M"); set.add("b"); set.add(4); set.add(1); set.add(9); System.out.println("Tree : "+set); } } Output: Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer. If we try to insert the different objects on single Tree Set, we can get the ClassCastException Here is the example for Customized sorting on TreeSet. import java.util.Comparator; import java.util.Set; import java.util.TreeSet; /** * * @author chandrashekhar */ public class TreeComparatorDemo { public static void main(String[] args) { Set set = new TreeSet(new CityComparator()); set.add(new City(1, "Vijayawada")); set.add(new City(5, "Mumbai")); set.add(new City(4, "Visakhapatnam")); set.add(new City(2, "Delhi")); System.out.println("Tree : " + set); } } class City { int id; String city; public City(int id, String city) { this.id = id; this.city = city; } @Override public String toString() { return "City{" + "id=" + id + ", city=" + city + '}'; } } class CityComparator implements Comparator < City > { @Override public int compare(City o1, City o2) { if (o1.id == o2.id) { return 0; } else if (o1.id > o2.id) { return 1; } else { return -1; } } } Output: Tree : [City{id=1, city=Vijayawada}, City{id=2, city=Delhi}, City{id=4, city=Visakhapatnam}, City{id=5, city=Mumbai}] Happy Learning 🙂 Comparator in Java Java 8 how to remove duplicates from list Bubble Sort In Java Difference between HashSet vs TreeSet in Java Comparator vs Comparable in Java How to Sort ArrayList in Java Ascending Order Comparable in Java How to Sort ArrayList in Java Descending Order String sorting in Java Java Program for String Sorting Example User defined sorting with Java 8 Comparator HashSet In Java in Java Example How HashMap Works In Java LinkedHashSet in Java ArrayList in Java Comparator in Java Java 8 how to remove duplicates from list Bubble Sort In Java Difference between HashSet vs TreeSet in Java Comparator vs Comparable in Java How to Sort ArrayList in Java Ascending Order Comparable in Java How to Sort ArrayList in Java Descending Order String sorting in Java Java Program for String Sorting Example User defined sorting with Java 8 Comparator HashSet In Java in Java Example How HashMap Works In Java LinkedHashSet in Java ArrayList in Java Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "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": 630, "s": 398, "text": "In this tutorials, we are going to learn what is TreeSet in Java and how to apply customized sorting on TreeSet. TreeSet in java is the implementation of the NavigableSet. The underlying data structure for TreeSet is Balanced Tree." }, { "code": null, "e": 922, "s": 630, "text": "Since it is a Set, it doesn’t allow the duplicate values and insertion order is not preserved. But all Objects which are inserted in the tree set are stored according to the some default sorting order, that is in the case of numbers ascending and in the case of strings alphabetical orders." }, { "code": null, "e": 933, "s": 922, "text": "TreeSet();" }, { "code": null, "e": 1030, "s": 933, "text": "It creates an empty TreeSet, where elements will be inserted according to default sorting order." }, { "code": null, "e": 1053, "s": 1030, "text": "TreeSet(Comparator c);" }, { "code": null, "e": 1161, "s": 1053, "text": "It Creates an empty TreeSet, where the elements will be inserted according to the customized sorting Order." }, { "code": null, "e": 1184, "s": 1161, "text": "TreeSet(Collection c);" }, { "code": null, "e": 1264, "s": 1184, "text": "It creates an empty TreeSet, containing the elements with the given collection." }, { "code": null, "e": 1286, "s": 1264, "text": "TreeSet(SortedSet c);" }, { "code": null, "e": 1384, "s": 1286, "text": "It creates an empty TreeSet, containing the elements with sorting order with the given SortedSet." }, { "code": null, "e": 1898, "s": 1384, "text": "\nThe underlying data structure for TreeSet is Balanced Tree.\nSince it is a Set implementation, duplicates are not allowed.\nTree Set doesn’t maintain Insertion order.\nTree Set allows the default sorting order.\nWhen we deal with the customize Sorting using TreeSet(Comparator c) constructor, the class should be implements Comparator interface.\nThough the Java collection framework allows the heterogeneous objects, but the TreeSet doesn’t allow heterogeneous elements.\nWe can not insert null values into TreeSet.\n" }, { "code": null, "e": 1958, "s": 1898, "text": "The underlying data structure for TreeSet is Balanced Tree." }, { "code": null, "e": 2020, "s": 1958, "text": "Since it is a Set implementation, duplicates are not allowed." }, { "code": null, "e": 2063, "s": 2020, "text": "Tree Set doesn’t maintain Insertion order." }, { "code": null, "e": 2106, "s": 2063, "text": "Tree Set allows the default sorting order." }, { "code": null, "e": 2240, "s": 2106, "text": "When we deal with the customize Sorting using TreeSet(Comparator c) constructor, the class should be implements Comparator interface." }, { "code": null, "e": 2366, "s": 2240, "text": "Though the Java collection framework allows the heterogeneous objects, but the TreeSet doesn’t allow heterogeneous elements." }, { "code": null, "e": 2410, "s": 2366, "text": "We can not insert null values into TreeSet." }, { "code": null, "e": 2811, "s": 2410, "text": "import java.util.Set;\nimport java.util.TreeSet;\n\npublic class TreeSetDemo { \n public static void main(String[] args) { \n Set set = new TreeSet(); \n set.add(\"A\"); \n set.add(\"M\"); \n set.add(\"b\"); \n set.add(\"Q\"); \n set.add(\"P\"); \n set.add(\"a\"); \n System.out.println(\"Tree : \" + set); \n }\n}" }, { "code": null, "e": 2818, "s": 2811, "text": "Output" }, { "code": null, "e": 2844, "s": 2818, "text": "Tree : [A, M, P, Q, a, b]" }, { "code": null, "e": 2914, "s": 2846, "text": "On the above, we can see the output with the default sorting order." }, { "code": null, "e": 3245, "s": 2914, "text": "import java.util.Set;\nimport java.util.TreeSet;\n\npublic class TreeSetDemo {\n public static void main(String[] args) {\n Set set = new TreeSet();\n set.add(\"A\");\n set.add(\"M\");\n set.add(\"b\");\n set.add(4);\n set.add(1);\n set.add(9);\n System.out.println(\"Tree : \"+set);\n }\n}" }, { "code": null, "e": 3253, "s": 3245, "text": "Output:" }, { "code": null, "e": 3461, "s": 3253, "text": "Exception in thread \"main\" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer.\n\nIf we try to insert the different objects on single Tree Set, we can get the ClassCastException" }, { "code": null, "e": 3516, "s": 3461, "text": "Here is the example for Customized sorting on TreeSet." }, { "code": null, "e": 4688, "s": 3516, "text": "import java.util.Comparator;\nimport java.util.Set;\nimport java.util.TreeSet;\n\n/**\n *\n * @author chandrashekhar\n */\npublic class TreeComparatorDemo {\n\n \n public static void main(String[] args) { \n Set set = new TreeSet(new CityComparator()); \n set.add(new City(1, \"Vijayawada\")); \n set.add(new City(5, \"Mumbai\")); \n set.add(new City(4, \"Visakhapatnam\")); \n set.add(new City(2, \"Delhi\")); \n System.out.println(\"Tree : \" + set); \n }\n}\n\nclass City {\n \n int id; \n String city;\n \n public City(int id, String city) { \n this.id = id; \n this.city = city; \n }\n \n @Override public String toString() { \n return \"City{\" + \"id=\" + id + \", city=\" + city + '}'; \n }\n}\n\nclass CityComparator implements Comparator < City > {\n\n @Override public int compare(City o1, City o2) { \n if (o1.id == o2.id) { \n return 0; \n } else if (o1.id > o2.id) { \n return 1; \n } else { \n return -1; \n } \n }\n}" }, { "code": null, "e": 4696, "s": 4688, "text": "Output:" }, { "code": null, "e": 4814, "s": 4696, "text": "Tree : [City{id=1, city=Vijayawada}, City{id=2, city=Delhi}, City{id=4, city=Visakhapatnam}, City{id=5, city=Mumbai}]" }, { "code": null, "e": 4831, "s": 4814, "text": "Happy Learning 🙂" }, { "code": null, "e": 5310, "s": 4831, "text": "\nComparator in Java\nJava 8 how to remove duplicates from list\nBubble Sort In Java\nDifference between HashSet vs TreeSet in Java\nComparator vs Comparable in Java\nHow to Sort ArrayList in Java Ascending Order\nComparable in Java\nHow to Sort ArrayList in Java Descending Order\nString sorting in Java\nJava Program for String Sorting Example\nUser defined sorting with Java 8 Comparator\nHashSet In Java in Java Example\nHow HashMap Works In Java\nLinkedHashSet in Java\nArrayList in Java\n" }, { "code": null, "e": 5329, "s": 5310, "text": "Comparator in Java" }, { "code": null, "e": 5371, "s": 5329, "text": "Java 8 how to remove duplicates from list" }, { "code": null, "e": 5391, "s": 5371, "text": "Bubble Sort In Java" }, { "code": null, "e": 5437, "s": 5391, "text": "Difference between HashSet vs TreeSet in Java" }, { "code": null, "e": 5470, "s": 5437, "text": "Comparator vs Comparable in Java" }, { "code": null, "e": 5516, "s": 5470, "text": "How to Sort ArrayList in Java Ascending Order" }, { "code": null, "e": 5535, "s": 5516, "text": "Comparable in Java" }, { "code": null, "e": 5582, "s": 5535, "text": "How to Sort ArrayList in Java Descending Order" }, { "code": null, "e": 5605, "s": 5582, "text": "String sorting in Java" }, { "code": null, "e": 5645, "s": 5605, "text": "Java Program for String Sorting Example" }, { "code": null, "e": 5689, "s": 5645, "text": "User defined sorting with Java 8 Comparator" }, { "code": null, "e": 5721, "s": 5689, "text": "HashSet In Java in Java Example" }, { "code": null, "e": 5747, "s": 5721, "text": "How HashMap Works In Java" }, { "code": null, "e": 5769, "s": 5747, "text": "LinkedHashSet in Java" }, { "code": null, "e": 5787, "s": 5769, "text": "ArrayList in Java" }, { "code": null, "e": 5793, "s": 5791, "text": "Δ" }, { "code": null, "e": 5817, "s": 5793, "text": " Install Java on Mac OS" }, { "code": null, "e": 5845, "s": 5817, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 5874, "s": 5845, "text": " Install Minikube on Windows" }, { "code": null, "e": 5909, "s": 5874, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 5936, "s": 5909, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 5963, "s": 5936, "text": " Install Gradle on Windows" }, { "code": null, "e": 5992, "s": 5963, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 6018, "s": 5992, "text": " Install PuTTY on windows" }, { "code": null, "e": 6044, "s": 6018, "text": " Install Mysql on Windows" }, { "code": null, "e": 6080, "s": 6044, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 6114, "s": 6080, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 6140, "s": 6114, "text": " Install Maven on Windows" }, { "code": null, "e": 6165, "s": 6140, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 6199, "s": 6165, "text": " Install Maven on Windows Command" }, { "code": null, "e": 6234, "s": 6199, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 6258, "s": 6234, "text": " Install Ant on Windows" }, { "code": null, "e": 6287, "s": 6258, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 6319, "s": 6287, "text": " Install Apache Kafka on Ubuntu" }, { "code": null, "e": 6352, "s": 6319, "text": " Install Apache Kafka on Windows" }, { "code": null, "e": 6377, "s": 6352, "text": " Java8 – Install Windows" }, { "code": null, "e": 6394, "s": 6377, "text": " Java8 – foreach" }, { "code": null, "e": 6422, "s": 6394, "text": " Java8 – forEach with index" }, { "code": null, "e": 6453, "s": 6422, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 6485, "s": 6453, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 6505, "s": 6485, "text": " Java8 – GroupingBy" }, { "code": null, "e": 6525, "s": 6505, "text": " Java8 – SummingInt" }, { "code": null, "e": 6549, "s": 6525, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 6579, "s": 6549, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 6611, "s": 6579, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 6647, "s": 6611, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 6691, "s": 6647, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 6723, "s": 6691, "text": " Howto – Convert List to String" }, { "code": null, "e": 6764, "s": 6723, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 6801, "s": 6764, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 6841, "s": 6801, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 6870, "s": 6841, "text": " Howto – Convert List to Map" }, { "code": null, "e": 6902, "s": 6870, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 6922, "s": 6902, "text": " Howto – Sort a Map" }, { "code": null, "e": 6944, "s": 6922, "text": " Howto – Filter a Map" }, { "code": null, "e": 6974, "s": 6944, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 7025, "s": 6974, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 7061, "s": 7025, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 7093, "s": 7061, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 7128, "s": 7093, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 7151, "s": 7128, "text": " Howto – Merge Streams" }, { "code": null, "e": 7198, "s": 7151, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 7223, "s": 7198, "text": " Howto -Get Stream count" }, { "code": null, "e": 7267, "s": 7223, "text": " Howto – Get Min and Max values in a Stream" } ]
Dart - Concept of Inheritance - GeeksforGeeks
20 Jul, 2020 In Dart, one class can inherit another class i.e dart can create a new class from an existing class. We make use of extend keyword to do so. Terminology: Parent Class: It is the class whose properties are inherited by the child class. It is also known as a base class or superclass. Child Class: It is the class that inherits the properties of the other classes. It is also known as a deprived class or subclass. class parent_class{ ... } class child_class extends parent_class{ ... } Example 1: Example of Single Inheritance in the dart. Dart // Dart program to show the single inheritance // Creating parent classclass Gfg{ // Creating a function void output(){ print("Welcome to gfg!!\nYou are inside output function."); }} // Creating Child classclass GfgChild extends Gfg{ // We are not defining // any thing inside it...}void main() { // Creating object of GfgChild class var geek = new GfgChild(); // Calling function // inside Gfg(Parent class) geek.output();} Output: Welcome to gfg!! You are inside output function. Types of Inheritance: Single Inheritance: When a class inherits a single parent class than this inheritance occurs.Multiple Inheritance: When a class inherits more than one parent class than this inheritance occurs. Dart doesn’t support this.Multi-Level Inheritance: When a class inherits another child class than this inheritance occurs. Hierarchical Inheritance: More than one classes have the same parent class. Single Inheritance: When a class inherits a single parent class than this inheritance occurs. Multiple Inheritance: When a class inherits more than one parent class than this inheritance occurs. Dart doesn’t support this. Multi-Level Inheritance: When a class inherits another child class than this inheritance occurs. Hierarchical Inheritance: More than one classes have the same parent class. Important Points: Child classes inherit all properties and methods except constructors of the parent class.Unlike Java, Dart also doesn’t support multiple inheritance. Child classes inherit all properties and methods except constructors of the parent class. Unlike Java, Dart also doesn’t support multiple inheritance. Example 2: Dart // Dart program for multilevel interitance // Creating parent classclass Gfg{ // Creating a function void output1(){ print("Welcome to gfg!!\nYou are inside the output function of Gfg class."); }} // Creating Child1 classclass GfgChild1 extends Gfg{ // Creating a function void output2(){ print("Welcome to gfg!!\nYou are inside the output function of GfgChild1 class."); }} // Creating Child2 classclass GfgChild2 extends GfgChild1{ // We are not defining // any thing inside it...} void main() { // Creating object // of GfgChild class var geek = new GfgChild2(); // Calling function // inside Gfg //(Parent class of Parent class) geek.output1(); // Calling function // inside GfgChild // (Parent class) geek.output2();} Output: Welcome to gfg!! You are inside the output function of Gfg class. Welcome to gfg!! You are inside the output function of GfgChild1 class. Example 3: Hierarchical inheritance. Dart // Dart program for Hierarchical inheritance // Creating parent classclass Gfg{ // Creating a function void output1(){ print("Welcome to gfg!!\nYou are inside output function of Gfg class."); }} // Creating Child1 classclass GfgChild1 extends Gfg{ // We are not defining // any thing inside it...} // Creating Child2 classclass GfgChild2 extends Gfg{ // We are not defining // any thing inside it...} void main() { // Creating object // of GfgChild1 class var geek1 = new GfgChild1(); // Calling function // inside Gfg(Parent class) geek1.output1(); // Creating object of // GfgChild1 class var geek2 = new GfgChild2(); // Calling function // inside Gfg(Parent class) geek2.output1();} Output: Welcome to gfg!! You are inside output function of Gfg class. Welcome to gfg!! You are inside output function of Gfg class. Dart-OOPs Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Checkbox Widget Flutter - Flexible Widget Flutter - BoxShadow Widget How to Append or Concatenate Strings in Dart? Flutter - Stack Widget Dart Tutorial Operators in Dart
[ { "code": null, "e": 25407, "s": 25379, "text": "\n20 Jul, 2020" }, { "code": null, "e": 25548, "s": 25407, "text": "In Dart, one class can inherit another class i.e dart can create a new class from an existing class. We make use of extend keyword to do so." }, { "code": null, "e": 25563, "s": 25548, "text": "Terminology: " }, { "code": null, "e": 25692, "s": 25563, "text": "Parent Class: It is the class whose properties are inherited by the child class. It is also known as a base class or superclass." }, { "code": null, "e": 25822, "s": 25692, "text": "Child Class: It is the class that inherits the properties of the other classes. It is also known as a deprived class or subclass." }, { "code": null, "e": 25896, "s": 25822, "text": "class parent_class{\n...\n}\n\nclass child_class extends parent_class{\n...\n}\n" }, { "code": null, "e": 25951, "s": 25896, "text": "Example 1: Example of Single Inheritance in the dart. " }, { "code": null, "e": 25956, "s": 25951, "text": "Dart" }, { "code": "// Dart program to show the single inheritance // Creating parent classclass Gfg{ // Creating a function void output(){ print(\"Welcome to gfg!!\\nYou are inside output function.\"); }} // Creating Child classclass GfgChild extends Gfg{ // We are not defining // any thing inside it...}void main() { // Creating object of GfgChild class var geek = new GfgChild(); // Calling function // inside Gfg(Parent class) geek.output();}", "e": 26404, "s": 25956, "text": null }, { "code": null, "e": 26415, "s": 26406, "text": "Output: " }, { "code": null, "e": 26465, "s": 26415, "text": "Welcome to gfg!!\nYou are inside output function.\n" }, { "code": null, "e": 26488, "s": 26465, "text": "Types of Inheritance: " }, { "code": null, "e": 26881, "s": 26488, "text": "Single Inheritance: When a class inherits a single parent class than this inheritance occurs.Multiple Inheritance: When a class inherits more than one parent class than this inheritance occurs. Dart doesn’t support this.Multi-Level Inheritance: When a class inherits another child class than this inheritance occurs. Hierarchical Inheritance: More than one classes have the same parent class." }, { "code": null, "e": 26975, "s": 26881, "text": "Single Inheritance: When a class inherits a single parent class than this inheritance occurs." }, { "code": null, "e": 27103, "s": 26975, "text": "Multiple Inheritance: When a class inherits more than one parent class than this inheritance occurs. Dart doesn’t support this." }, { "code": null, "e": 27200, "s": 27103, "text": "Multi-Level Inheritance: When a class inherits another child class than this inheritance occurs." }, { "code": null, "e": 27277, "s": 27200, "text": " Hierarchical Inheritance: More than one classes have the same parent class." }, { "code": null, "e": 27296, "s": 27277, "text": "Important Points: " }, { "code": null, "e": 27446, "s": 27296, "text": "Child classes inherit all properties and methods except constructors of the parent class.Unlike Java, Dart also doesn’t support multiple inheritance." }, { "code": null, "e": 27536, "s": 27446, "text": "Child classes inherit all properties and methods except constructors of the parent class." }, { "code": null, "e": 27597, "s": 27536, "text": "Unlike Java, Dart also doesn’t support multiple inheritance." }, { "code": null, "e": 27608, "s": 27597, "text": "Example 2:" }, { "code": null, "e": 27613, "s": 27608, "text": "Dart" }, { "code": "// Dart program for multilevel interitance // Creating parent classclass Gfg{ // Creating a function void output1(){ print(\"Welcome to gfg!!\\nYou are inside the output function of Gfg class.\"); }} // Creating Child1 classclass GfgChild1 extends Gfg{ // Creating a function void output2(){ print(\"Welcome to gfg!!\\nYou are inside the output function of GfgChild1 class.\"); }} // Creating Child2 classclass GfgChild2 extends GfgChild1{ // We are not defining // any thing inside it...} void main() { // Creating object // of GfgChild class var geek = new GfgChild2(); // Calling function // inside Gfg //(Parent class of Parent class) geek.output1(); // Calling function // inside GfgChild // (Parent class) geek.output2();}", "e": 28381, "s": 27613, "text": null }, { "code": null, "e": 28393, "s": 28383, "text": "Output: " }, { "code": null, "e": 28532, "s": 28393, "text": "Welcome to gfg!!\nYou are inside the output function of Gfg class.\nWelcome to gfg!!\nYou are inside the output function of GfgChild1 class.\n" }, { "code": null, "e": 28571, "s": 28532, "text": "Example 3: Hierarchical inheritance. " }, { "code": null, "e": 28576, "s": 28571, "text": "Dart" }, { "code": "// Dart program for Hierarchical inheritance // Creating parent classclass Gfg{ // Creating a function void output1(){ print(\"Welcome to gfg!!\\nYou are inside output function of Gfg class.\"); }} // Creating Child1 classclass GfgChild1 extends Gfg{ // We are not defining // any thing inside it...} // Creating Child2 classclass GfgChild2 extends Gfg{ // We are not defining // any thing inside it...} void main() { // Creating object // of GfgChild1 class var geek1 = new GfgChild1(); // Calling function // inside Gfg(Parent class) geek1.output1(); // Creating object of // GfgChild1 class var geek2 = new GfgChild2(); // Calling function // inside Gfg(Parent class) geek2.output1();}", "e": 29308, "s": 28576, "text": null }, { "code": null, "e": 29319, "s": 29310, "text": "Output: " }, { "code": null, "e": 29444, "s": 29319, "text": "Welcome to gfg!!\nYou are inside output function of Gfg class.\nWelcome to gfg!!\nYou are inside output function of Gfg class.\n" }, { "code": null, "e": 29454, "s": 29444, "text": "Dart-OOPs" }, { "code": null, "e": 29459, "s": 29454, "text": "Dart" }, { "code": null, "e": 29557, "s": 29459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29589, "s": 29557, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 29628, "s": 29589, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29654, "s": 29628, "text": "ListView Class in Flutter" }, { "code": null, "e": 29680, "s": 29654, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 29706, "s": 29680, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 29733, "s": 29706, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 29779, "s": 29733, "text": "How to Append or Concatenate Strings in Dart?" }, { "code": null, "e": 29802, "s": 29779, "text": "Flutter - Stack Widget" }, { "code": null, "e": 29816, "s": 29802, "text": "Dart Tutorial" } ]
Python | Construct Cartesian Product Tuple list - GeeksforGeeks
03 Nov, 2019 Sometimes, while working with data, we need to create data as all possible pairs of containers. This type of application comes from web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehensionThis is one-liner way to perform this particular task. In this, we just shorten the task of loop in one line to generate all possible pairs of tuple with list elements. # Python3 code to demonstrate working of# Construct Cartesian Product Tuple list# using list comprehension # initialize list and tuple test_list = [1, 4, 6, 7]test_tup = (1, 3) # printing original list and tuple print("The original list : " + str(test_list))print("The original tuple : " + str(test_tup)) # Construct Cartesian Product Tuple list# using list comprehensionres = [(a, b) for a in test_tup for b in test_list] # printing resultprint("The Cartesian Product is : " + str(res)) The original list : [1, 4, 6, 7]The original tuple : (1, 3)The Cartesian Product is : [(1, 1), (1, 4), (1, 6), (1, 7), (3, 1), (3, 4), (3, 6), (3, 7)] Method #2 : Using itertools.product()This task can also be performed using the single function which internally performs the task of returning the required Cartesian Product. # Python3 code to demonstrate working of# Construct Cartesian Product Tuple list# using itertools.product()from itertools import product # initialize list and tuple test_list = [1, 4, 6, 7]test_tup = (1, 3) # printing original list and tuple print("The original list : " + str(test_list))print("The original tuple : " + str(test_tup)) # Construct Cartesian Product Tuple list# using itertools.product()res = list(product(test_tup, test_list)) # printing resultprint("The Cartesian Product is : " + str(res)) The original list : [1, 4, 6, 7]The original tuple : (1, 3)The Cartesian Product is : [(1, 1), (1, 4), (1, 6), (1, 7), (3, 1), (3, 4), (3, 6), (3, 7)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 24608, "s": 24580, "text": "\n03 Nov, 2019" }, { "code": null, "e": 24828, "s": 24608, "text": "Sometimes, while working with data, we need to create data as all possible pairs of containers. This type of application comes from web development domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 25033, "s": 24828, "text": "Method #1 : Using list comprehensionThis is one-liner way to perform this particular task. In this, we just shorten the task of loop in one line to generate all possible pairs of tuple with list elements." }, { "code": "# Python3 code to demonstrate working of# Construct Cartesian Product Tuple list# using list comprehension # initialize list and tuple test_list = [1, 4, 6, 7]test_tup = (1, 3) # printing original list and tuple print(\"The original list : \" + str(test_list))print(\"The original tuple : \" + str(test_tup)) # Construct Cartesian Product Tuple list# using list comprehensionres = [(a, b) for a in test_tup for b in test_list] # printing resultprint(\"The Cartesian Product is : \" + str(res))", "e": 25525, "s": 25033, "text": null }, { "code": null, "e": 25676, "s": 25525, "text": "The original list : [1, 4, 6, 7]The original tuple : (1, 3)The Cartesian Product is : [(1, 1), (1, 4), (1, 6), (1, 7), (3, 1), (3, 4), (3, 6), (3, 7)]" }, { "code": null, "e": 25853, "s": 25678, "text": "Method #2 : Using itertools.product()This task can also be performed using the single function which internally performs the task of returning the required Cartesian Product." }, { "code": "# Python3 code to demonstrate working of# Construct Cartesian Product Tuple list# using itertools.product()from itertools import product # initialize list and tuple test_list = [1, 4, 6, 7]test_tup = (1, 3) # printing original list and tuple print(\"The original list : \" + str(test_list))print(\"The original tuple : \" + str(test_tup)) # Construct Cartesian Product Tuple list# using itertools.product()res = list(product(test_tup, test_list)) # printing resultprint(\"The Cartesian Product is : \" + str(res))", "e": 26365, "s": 25853, "text": null }, { "code": null, "e": 26516, "s": 26365, "text": "The original list : [1, 4, 6, 7]The original tuple : (1, 3)The Cartesian Product is : [(1, 1), (1, 4), (1, 6), (1, 7), (3, 1), (3, 4), (3, 6), (3, 7)]" }, { "code": null, "e": 26537, "s": 26516, "text": "Python list-programs" }, { "code": null, "e": 26544, "s": 26537, "text": "Python" }, { "code": null, "e": 26560, "s": 26544, "text": "Python Programs" }, { "code": null, "e": 26658, "s": 26560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26676, "s": 26658, "text": "Python Dictionary" }, { "code": null, "e": 26711, "s": 26676, "text": "Read a file line by line in Python" }, { "code": null, "e": 26743, "s": 26711, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26785, "s": 26743, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26811, "s": 26785, "text": "Python String | replace()" }, { "code": null, "e": 26854, "s": 26811, "text": "Python program to convert a list to string" }, { "code": null, "e": 26876, "s": 26854, "text": "Defaultdict in Python" }, { "code": null, "e": 26915, "s": 26876, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26961, "s": 26915, "text": "Python | Split string into list of characters" } ]
How to convert an array of objects to an array of their primitive types in java?
Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add the library to your project. <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> </dependencies> This package provides a class named ArrayUtils. Using the toPrimitive() method of this class you can convert An object array to an array of primitive types: import java.util.Arrays; import org.apache.commons.lang3.ArrayUtils; public class ArraysToPrimitives { public static void main(String args[]) { Integer[] myArray = {234, 76, 890, 27, 10, 63}; int[] primitiveArray = ArrayUtils.toPrimitive(myArray); System.out.println(Arrays.toString(primitiveArray)); } } [234, 76, 890, 27, 10, 63]
[ { "code": null, "e": 1202, "s": 1062, "text": "Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add the library to your project." }, { "code": null, "e": 1384, "s": 1202, "text": "<dependencies>\n <dependency>\n <groupId>org.apache.commons</groupId>\n <artifactId>commons-lang3</artifactId>\n <version>3.0</version>\n </dependency>\n</dependencies>" }, { "code": null, "e": 1541, "s": 1384, "text": "This package provides a class named ArrayUtils. Using the toPrimitive() method of this class you can convert An object array to an array of primitive types:" }, { "code": null, "e": 1871, "s": 1541, "text": "import java.util.Arrays;\nimport org.apache.commons.lang3.ArrayUtils;\n\npublic class ArraysToPrimitives {\n public static void main(String args[]) {\n Integer[] myArray = {234, 76, 890, 27, 10, 63};\n int[] primitiveArray = ArrayUtils.toPrimitive(myArray);\n System.out.println(Arrays.toString(primitiveArray));\n }\n}" }, { "code": null, "e": 1898, "s": 1871, "text": "[234, 76, 890, 27, 10, 63]" } ]
Docker - USER Instruction - GeeksforGeeks
28 Oct, 2020 By default, a Docker Container runs as a Root user. This poses a great security threat if you deploy your applications on a large scale inside Docker Containers. You can change or switch to a different user inside a Docker Container using the USER Instruction. For this, you first need to create a user and a group inside the Container. In this article, we are going to use the USER instruction to switch the user inside the Container from Root to the one which we will create. To do so follow the below steps: You can specify the instructions to create a new user and group and to switch the user both in the Dockerfile. For this example, we will simply create an Ubuntu Image and use the bash with a different user other than the Root user. FROM ubuntu:latest RUN apt-get -y update RUN groupadd -r user && useradd -r -g user user USER user In the above dockerfile, we have pulled the base Image Ubuntu and updated it. We have created a new group called user and a new user inside the group with the same name. Using the USER option, we have then switched the user. After creating the Dockerfile, we can now create the Docker Image using the Build command. sudo docker build -t user-demo . Use the Docker Run command to run the Container. sudo docker run -it user-demo bash You can now check that the default user and the group have now changed to the one we created in the Dockerfile using the id command. id To conclude, in this article we discussed how to use the USER instruction inside the Dockerfile to switch the Docker Container’s default user from Root to another user that we can create using the useradd and grouadd commands. Docker Container linux Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Decision Tree ML | Linear Regression Python | Decision tree implementation System Design Tutorial Copying Files to and from Docker Containers Decision Tree Introduction with example Reinforcement learning ML | Underfitting and Overfitting KDD Process in Data Mining ML | Label Encoding of datasets in Python
[ { "code": null, "e": 24430, "s": 24402, "text": "\n28 Oct, 2020" }, { "code": null, "e": 24767, "s": 24430, "text": "By default, a Docker Container runs as a Root user. This poses a great security threat if you deploy your applications on a large scale inside Docker Containers. You can change or switch to a different user inside a Docker Container using the USER Instruction. For this, you first need to create a user and a group inside the Container." }, { "code": null, "e": 24941, "s": 24767, "text": "In this article, we are going to use the USER instruction to switch the user inside the Container from Root to the one which we will create. To do so follow the below steps:" }, { "code": null, "e": 25173, "s": 24941, "text": "You can specify the instructions to create a new user and group and to switch the user both in the Dockerfile. For this example, we will simply create an Ubuntu Image and use the bash with a different user other than the Root user." }, { "code": null, "e": 25274, "s": 25173, "text": "FROM ubuntu:latest\nRUN apt-get -y update\nRUN groupadd -r user && useradd -r -g user user\nUSER user\n\n" }, { "code": null, "e": 25499, "s": 25274, "text": "In the above dockerfile, we have pulled the base Image Ubuntu and updated it. We have created a new group called user and a new user inside the group with the same name. Using the USER option, we have then switched the user." }, { "code": null, "e": 25590, "s": 25499, "text": "After creating the Dockerfile, we can now create the Docker Image using the Build command." }, { "code": null, "e": 25625, "s": 25590, "text": "sudo docker build -t user-demo .\n\n" }, { "code": null, "e": 25674, "s": 25625, "text": "Use the Docker Run command to run the Container." }, { "code": null, "e": 25710, "s": 25674, "text": "sudo docker run -it user-demo bash\n" }, { "code": null, "e": 25843, "s": 25710, "text": "You can now check that the default user and the group have now changed to the one we created in the Dockerfile using the id command." }, { "code": null, "e": 25847, "s": 25843, "text": "id\n" }, { "code": null, "e": 26074, "s": 25847, "text": "To conclude, in this article we discussed how to use the USER instruction inside the Dockerfile to switch the Docker Container’s default user from Root to another user that we can create using the useradd and grouadd commands." }, { "code": null, "e": 26091, "s": 26074, "text": "Docker Container" }, { "code": null, "e": 26097, "s": 26091, "text": "linux" }, { "code": null, "e": 26123, "s": 26097, "text": "Advanced Computer Subject" }, { "code": null, "e": 26221, "s": 26123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26230, "s": 26221, "text": "Comments" }, { "code": null, "e": 26243, "s": 26230, "text": "Old Comments" }, { "code": null, "e": 26257, "s": 26243, "text": "Decision Tree" }, { "code": null, "e": 26280, "s": 26257, "text": "ML | Linear Regression" }, { "code": null, "e": 26318, "s": 26280, "text": "Python | Decision tree implementation" }, { "code": null, "e": 26341, "s": 26318, "text": "System Design Tutorial" }, { "code": null, "e": 26385, "s": 26341, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 26425, "s": 26385, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 26448, "s": 26425, "text": "Reinforcement learning" }, { "code": null, "e": 26482, "s": 26448, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 26509, "s": 26482, "text": "KDD Process in Data Mining" } ]
Maximum Bipartite Matching
The bipartite matching is a set of edges in a graph is chosen in such a way, that no two edges in that set will share an endpoint. The maximum matching is matching the maximum number of edges. When the maximum match is found, we cannot add another edge. If one edge is added to the maximum matched graph, it is no longer a matching. For a bipartite graph, there can be more than one maximum matching is possible. Input: The adjacency matrix. 0 1 1 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 Output: Maximum number of applicants matching for job: 5 bipartiteMatch(u, visited, assign) Input: Starting node, visited list to keep track, assign the list to assign node with another node. Output − Returns true when a matching for vertex u is possible. Begin for all vertex v, which are adjacent with u, do if v is not visited, then mark v as visited if v is not assigned, or bipartiteMatch(assign[v], visited, assign) is true, then assign[v] := u return true done return false End maxMatch(graph) Input − The given graph. Output − The maximum number of the match. Begin initially no vertex is assigned count := 0 for all applicant u in M, do make all node as unvisited if bipartiteMatch(u, visited, assign), then increase count by 1 done End #include <iostream> #define M 6 #define N 6 using namespace std; bool bipartiteGraph[M][N] = { //A graph with M applicant and N jobs {0, 1, 1, 0, 0, 0}, {1, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 1, 1, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1} }; bool bipartiteMatch(int u, bool visited[], int assign[]) { for (int v = 0; v < N; v++) { //for all jobs 0 to N-1 if (bipartiteGraph[u][v] && !visited[v]) { //when job v is not visited and u is interested visited[v] = true; //mark as job v is visited //when v is not assigned or previously assigned if (assign[v] < 0 || bipartiteMatch(assign[v], visited, assign)) { assign[v] = u; //assign job v to applicant u return true; } } } return false; } int maxMatch() { int assign[N]; //an array to track which job is assigned to which applicant for(int i = 0; i<N; i++) assign[i] = -1; //initially set all jobs are available int jobCount = 0; for (int u = 0; u < M; u++) { //for all applicants bool visited[N]; for(int i = 0; i<N; i++) visited[i] = false; //initially no jobs are visited if (bipartiteMatch(u, visited, assign)) //when u get a job jobCount++; } return jobCount; } int main() { cout << "Maximum number of applicants matching for job: " << maxMatch(); } Maximum number of applicants matching for job: 5
[ { "code": null, "e": 1255, "s": 1062, "text": "The bipartite matching is a set of edges in a graph is chosen in such a way, that no two edges in that set will share an endpoint. The maximum matching is matching the maximum number of edges." }, { "code": null, "e": 1475, "s": 1255, "text": "When the maximum match is found, we cannot add another edge. If one edge is added to the maximum matched graph, it is no longer a matching. For a bipartite graph, there can be more than one maximum matching is possible." }, { "code": null, "e": 1634, "s": 1475, "text": "Input:\nThe adjacency matrix.\n0 1 1 0 0 0\n1 0 0 1 0 0\n0 0 1 0 0 0\n0 0 1 1 0 0\n0 0 0 0 0 0\n0 0 0 0 0 1\n\nOutput:\nMaximum number of applicants matching for job: 5" }, { "code": null, "e": 1669, "s": 1634, "text": "bipartiteMatch(u, visited, assign)" }, { "code": null, "e": 1769, "s": 1669, "text": "Input: Starting node, visited list to keep track, assign the list to assign node with another node." }, { "code": null, "e": 1833, "s": 1769, "text": "Output − Returns true when a matching for vertex u is possible." }, { "code": null, "e": 2119, "s": 1833, "text": "Begin\n for all vertex v, which are adjacent with u, do\n if v is not visited, then\n mark v as visited\n if v is not assigned, or bipartiteMatch(assign[v], visited, assign) is true, then\n assign[v] := u\n return true\n done\n return false\nEnd" }, { "code": null, "e": 2135, "s": 2119, "text": "maxMatch(graph)" }, { "code": null, "e": 2160, "s": 2135, "text": "Input − The given graph." }, { "code": null, "e": 2202, "s": 2160, "text": "Output − The maximum number of the match." }, { "code": null, "e": 2413, "s": 2202, "text": "Begin\n initially no vertex is assigned\n count := 0\n for all applicant u in M, do\n make all node as unvisited\n if bipartiteMatch(u, visited, assign), then\n increase count by 1\n done\nEnd" }, { "code": null, "e": 3826, "s": 2413, "text": "#include <iostream>\n#define M 6\n#define N 6\nusing namespace std;\n\nbool bipartiteGraph[M][N] = { //A graph with M applicant and N jobs\n {0, 1, 1, 0, 0, 0},\n {1, 0, 0, 1, 0, 0},\n {0, 0, 1, 0, 0, 0},\n {0, 0, 1, 1, 0, 0},\n {0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 1}\n};\n\nbool bipartiteMatch(int u, bool visited[], int assign[]) {\n for (int v = 0; v < N; v++) { //for all jobs 0 to N-1\n if (bipartiteGraph[u][v] && !visited[v]) { //when job v is not visited and u is interested\n visited[v] = true; //mark as job v is visited\n //when v is not assigned or previously assigned\n if (assign[v] < 0 || bipartiteMatch(assign[v], visited, assign)) {\n assign[v] = u; //assign job v to applicant u\n return true;\n }\n }\n }\n return false;\n}\n\nint maxMatch() {\n int assign[N]; //an array to track which job is assigned to which applicant\n for(int i = 0; i<N; i++)\n assign[i] = -1; //initially set all jobs are available\n int jobCount = 0;\n\n for (int u = 0; u < M; u++) { //for all applicants\n bool visited[N];\n for(int i = 0; i<N; i++)\n visited[i] = false; //initially no jobs are visited\n if (bipartiteMatch(u, visited, assign)) //when u get a job\n jobCount++;\n }\n return jobCount;\n}\n\nint main() {\n cout << \"Maximum number of applicants matching for job: \" << maxMatch();\n}" }, { "code": null, "e": 3875, "s": 3826, "text": "Maximum number of applicants matching for job: 5" } ]
Python - Implementation of Polynomial Regression
Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modeled as an nth degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y |x) # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset datas = pd.read_csv('data.csv') datas # divide the dataset into two components X = datas.iloc[:, 1:2].values y = datas.iloc[:, 2].values # Fitting Linear Regression to the dataset from sklearn.linear_model import LinearRegression lin = LinearRegression() lin.fit(X, y) # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree = 4) X_poly = poly.fit_transform(X) poly.fit(X_poly, y) lin2 = LinearRegression() lin2.fit(X_poly, y) # Visualising the Linear Regression results plt.scatter(X, y, color = 'blue') plt.plot(X, lin.predict(X), color = 'red') plt.title('Linear Regression') plt.xlabel('Temperature') plt.ylabel('Pressure') plt.show() # Visualising the Polynomial Regression results plt.scatter(X, y, color = 'blue') plt.plot(X, lin2.predict(poly.fit_transform(X)), color = 'red') plt.title('Polynomial Regression') plt.xlabel('Temperature') plt.ylabel('Pressure') plt.show() # Predicting a new result with Linear Regression lin.predict(110.0) # Predicting a new result with Polynomial Regression lin2.predict(poly.fit_transform(110.0))
[ { "code": null, "e": 1377, "s": 1062, "text": "Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y is modeled as an nth degree polynomial. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y |x)" }, { "code": null, "e": 2616, "s": 1377, "text": "# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n# Importing the dataset\ndatas = pd.read_csv('data.csv')\ndatas\n# divide the dataset into two components\nX = datas.iloc[:, 1:2].values\ny = datas.iloc[:, 2].values\n# Fitting Linear Regression to the dataset\nfrom sklearn.linear_model import LinearRegression\nlin = LinearRegression()\nlin.fit(X, y)\n# Fitting Polynomial Regression to the dataset\nfrom sklearn.preprocessing import PolynomialFeatures\npoly = PolynomialFeatures(degree = 4)\nX_poly = poly.fit_transform(X)\npoly.fit(X_poly, y)\nlin2 = LinearRegression()\nlin2.fit(X_poly, y)\n# Visualising the Linear Regression results\nplt.scatter(X, y, color = 'blue')\nplt.plot(X, lin.predict(X), color = 'red')\nplt.title('Linear Regression')\nplt.xlabel('Temperature')\nplt.ylabel('Pressure')\nplt.show()\n# Visualising the Polynomial Regression results\nplt.scatter(X, y, color = 'blue')\nplt.plot(X, lin2.predict(poly.fit_transform(X)), color = 'red')\nplt.title('Polynomial Regression')\nplt.xlabel('Temperature')\nplt.ylabel('Pressure')\nplt.show()\n# Predicting a new result with Linear Regression\nlin.predict(110.0)\n# Predicting a new result with Polynomial Regression\nlin2.predict(poly.fit_transform(110.0))" } ]
How to read an input value from a JTextField and add to a JList in Java?
A JList is a subclass of JComponent class that allows the user to choose either a single selection or multiple selections. A JList class itself does not support scrollbar. In order to add scrollbar, we have to use JScrollPane class together with the JList class. The JScrollPane then manages a scrollbar automatically. A DefaultListModel class provides a simple implementation of a list model, which can be used to manage items displayed by a JList control. We can add items or elements to a JList by using addElement() method of DefaultListModel class. We can also add items or elements to a JList by reading an input value from a text field. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTextfieldToJListTest extends JFrame { private DefaultListModel model; private JList list; private JTextField jtf; public JTextfieldToJListTest() { setTitle("JTextfieldToJList Test"); model = new DefaultListModel(); jtf = new JTextField("Type something and Hit Enter"); jtf.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { jtf.setText(""); } }); list = new JList(model); list.setBackground(Color.lightGray); jtf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { model.addElement(jtf.getText()); JOptionPane.showMessageDialog(null, jtf.getText()); jtf.setText("Type something and Hit Enter"); } }); add(jtf,BorderLayout.NORTH); add(new JScrollPane(list),BorderLayout.CENTER); setSize(375, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JTextfieldToJListTest(); } }
[ { "code": null, "e": 1706, "s": 1062, "text": "A JList is a subclass of JComponent class that allows the user to choose either a single selection or multiple selections. A JList class itself does not support scrollbar. In order to add scrollbar, we have to use JScrollPane class together with the JList class. The JScrollPane then manages a scrollbar automatically. A DefaultListModel class provides a simple implementation of a list model, which can be used to manage items displayed by a JList control. We can add items or elements to a JList by using addElement() method of DefaultListModel class. We can also add items or elements to a JList by reading an input value from a text field." }, { "code": null, "e": 2922, "s": 1706, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class JTextfieldToJListTest extends JFrame {\n private DefaultListModel model;\n private JList list;\n private JTextField jtf;\n public JTextfieldToJListTest() {\n setTitle(\"JTextfieldToJList Test\");\n model = new DefaultListModel();\n jtf = new JTextField(\"Type something and Hit Enter\");\n jtf.addMouseListener(new MouseAdapter() {\n public void mouseClicked(MouseEvent me) {\n jtf.setText(\"\");\n }\n });\n list = new JList(model);\n list.setBackground(Color.lightGray);\n jtf.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent event) {\n model.addElement(jtf.getText());\n JOptionPane.showMessageDialog(null, jtf.getText());\n jtf.setText(\"Type something and Hit Enter\");\n }\n });\n add(jtf,BorderLayout.NORTH);\n add(new JScrollPane(list),BorderLayout.CENTER);\n setSize(375, 250);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JTextfieldToJListTest();\n }\n}" } ]
Information Search & Visualization
A database query is the principal mechanism to retrieve information from a database. It consists of predefined format of database questions. Many database management systems use the Structured Query Language (SQL) standard query format. SELECT DOCUMENT# FROM JOURNAL-DB WHERE (DATE >= 2004 AND DATE <= 2008) AND (LANGUAGE = ENGLISH OR FRENCH) AND (PUBLISHER = ASIST OR HFES OR ACM) Users perform better and have better contentment when they can view and control the search. The database query has thus provided substantial amount of help in the human computer interface. The following points are the five-phase frameworks that clarifies user interfaces for textual search − Formulation − expressing the search Formulation − expressing the search Initiation of action − launching the search Initiation of action − launching the search Review of results − reading messages and outcomes Review of results − reading messages and outcomes Refinement − formulating the next step Refinement − formulating the next step Use − compiling or disseminating insight Use − compiling or disseminating insight Following are the major multimedia document search categories. Preforming an image search in common search engines is not an easy thing to do. However there are sites where image search can be done by entering the image of your choice. Mostly, simple drawing tools are used to build templates to search with. For complex searches such as fingerprint matching, special softwares are developed where the user can search the machine for the predefined data of distinct features. Map search is another form of multimedia search where the online maps are retrieved through mobile devices and search engines. Though a structured database solution is required for complex searches such as searches with longitude/latitude. With the advanced database options, we can retrieve maps for every possible aspect such as cities, states, countries, world maps, weather sheets, directions, etc. Some design packages support the search of designs or diagrams as well. E.g., diagrams, blueprints, newspapers, etc. Sound search can also be done easily through audio search of the database. Though user should clearly speak the words or phrases for search. New projects such as Infomedia helps in retrieving video searches. They provide an overview of the videos or segmentations of frames from the video. The frequency of animation search has increased with the popularity of Flash. Now it is possible to search for specific animations such as a moving boat. Information visualization is the interactive visual illustrations of conceptual data that strengthen human understanding. It has emerged from the research in human-computer interaction and is applied as a critical component in varied fields. It allows users to see, discover, and understand huge amounts of information at once. Information visualization is also an assumption structure, which is typically followed by formal examination such as statistical hypothesis testing. Following are the advanced filtering procedures − Filtering with complex Boolean queries Automatic filtering Dynamic queries Faceted metadata search Query by example Implicit search Collaborative filtering Multilingual searches Visual field specification Hypertext can be defined as the text that has references to hyperlinks with immediate access. Any text that provides a reference to another text can be understood as two nodes of information with the reference forming the link. In hypertext, all the links are active and when clicked, opens something new. Hypermedia on the other hand, is an information medium that holds different types of media, such as, video, CD, and so forth, as well as hyperlinks. Hence, both hypertext and hypermedia refers to a system of linked information. A text may refer to links, which may also have visuals or media. So hypertext can be used as a generic term to denote a document, which may in fact be distributed across several media. Object Action Interface (OAI), can be considered as the next step of the Graphical User Interface (GUI). This model focusses on the priority of the object over the actions. The OAI model allows the user to perform action on the object. First the object is selected and then the action is performed on the object. Finally, the outcome is shown to the user. In this model, the user does not have to worry about the complexity of any syntactical actions. The object–action model provides an advantage to the user as they gain a sense of control due to the direct involvement in the design process. The computer serves as a medium to signify different tools. 81 Lectures 9.5 hours Abhishek And Pukhraj 30 Lectures 1.5 hours Brad Merrill 63 Lectures 4 hours Akaaro Consulting And Training 14 Lectures 7 hours Adrian 10 Lectures 2 hours Dr Swati Chakraborty 6 Lectures 1 hours Prabh Kirpa Classes Print Add Notes Bookmark this page
[ { "code": null, "e": 2009, "s": 1772, "text": "A database query is the principal mechanism to retrieve information from a database. It consists of predefined format of database questions. Many database management systems use the Structured Query Language (SQL) standard query format." }, { "code": null, "e": 2155, "s": 2009, "text": "SELECT DOCUMENT#\nFROM JOURNAL-DB\nWHERE (DATE >= 2004 AND DATE <= 2008)\nAND (LANGUAGE = ENGLISH OR FRENCH)\nAND (PUBLISHER = ASIST OR HFES OR ACM)\n" }, { "code": null, "e": 2344, "s": 2155, "text": "Users perform better and have better contentment when they can view and control the search. The database query has thus provided substantial amount of help in the human computer interface." }, { "code": null, "e": 2447, "s": 2344, "text": "The following points are the five-phase frameworks that clarifies user interfaces for textual search −" }, { "code": null, "e": 2483, "s": 2447, "text": "Formulation − expressing the search" }, { "code": null, "e": 2519, "s": 2483, "text": "Formulation − expressing the search" }, { "code": null, "e": 2563, "s": 2519, "text": "Initiation of action − launching the search" }, { "code": null, "e": 2607, "s": 2563, "text": "Initiation of action − launching the search" }, { "code": null, "e": 2657, "s": 2607, "text": "Review of results − reading messages and outcomes" }, { "code": null, "e": 2707, "s": 2657, "text": "Review of results − reading messages and outcomes" }, { "code": null, "e": 2746, "s": 2707, "text": "Refinement − formulating the next step" }, { "code": null, "e": 2785, "s": 2746, "text": "Refinement − formulating the next step" }, { "code": null, "e": 2826, "s": 2785, "text": "Use − compiling or disseminating insight" }, { "code": null, "e": 2867, "s": 2826, "text": "Use − compiling or disseminating insight" }, { "code": null, "e": 2930, "s": 2867, "text": "Following are the major multimedia document search categories." }, { "code": null, "e": 3343, "s": 2930, "text": "Preforming an image search in common search engines is not an easy thing to do. However there are sites where image search can be done by entering the image of your choice. Mostly, simple drawing tools are used to build templates to search with. For complex searches such as fingerprint matching, special softwares are developed where the user can search the machine for the predefined data of distinct features." }, { "code": null, "e": 3746, "s": 3343, "text": "Map search is another form of multimedia search where the online maps are retrieved through mobile devices and search engines. Though a structured database solution is required for complex searches such as searches with longitude/latitude. With the advanced database options, we can retrieve maps for every possible aspect such as cities, states, countries, world maps, weather sheets, directions, etc." }, { "code": null, "e": 3863, "s": 3746, "text": "Some design packages support the search of designs or diagrams as well. E.g., diagrams, blueprints, newspapers, etc." }, { "code": null, "e": 4004, "s": 3863, "text": "Sound search can also be done easily through audio search of the database. Though user should clearly speak the words or phrases for search." }, { "code": null, "e": 4153, "s": 4004, "text": "New projects such as Infomedia helps in retrieving video searches. They provide an overview of the videos or segmentations of frames from the video." }, { "code": null, "e": 4307, "s": 4153, "text": "The frequency of animation search has increased with the popularity of Flash. Now it is possible to search for specific animations such as a moving boat." }, { "code": null, "e": 4635, "s": 4307, "text": "Information visualization is the interactive visual illustrations of conceptual data that strengthen human understanding. It has emerged from the research in human-computer interaction and is applied as a critical component in varied fields. It allows users to see, discover, and understand huge amounts of information at once." }, { "code": null, "e": 4784, "s": 4635, "text": "Information visualization is also an assumption structure, which is typically followed by formal examination such as statistical hypothesis testing." }, { "code": null, "e": 4834, "s": 4784, "text": "Following are the advanced filtering procedures −" }, { "code": null, "e": 4873, "s": 4834, "text": "Filtering with complex Boolean queries" }, { "code": null, "e": 4893, "s": 4873, "text": "Automatic filtering" }, { "code": null, "e": 4909, "s": 4893, "text": "Dynamic queries" }, { "code": null, "e": 4933, "s": 4909, "text": "Faceted metadata search" }, { "code": null, "e": 4950, "s": 4933, "text": "Query by example" }, { "code": null, "e": 4966, "s": 4950, "text": "Implicit search" }, { "code": null, "e": 4990, "s": 4966, "text": "Collaborative filtering" }, { "code": null, "e": 5012, "s": 4990, "text": "Multilingual searches" }, { "code": null, "e": 5039, "s": 5012, "text": "Visual field specification" }, { "code": null, "e": 5345, "s": 5039, "text": "Hypertext can be defined as the text that has references to hyperlinks with immediate access. Any text that provides a reference to another text can be understood as two nodes of information with the reference forming the link. In hypertext, all the links are active and when clicked, opens something new." }, { "code": null, "e": 5494, "s": 5345, "text": "Hypermedia on the other hand, is an information medium that holds different types of media, such as, video, CD, and so forth, as well as hyperlinks." }, { "code": null, "e": 5758, "s": 5494, "text": "Hence, both hypertext and hypermedia refers to a system of linked information. A text may refer to links, which may also have visuals or media. So hypertext can be used as a generic term to denote a document, which may in fact be distributed across several media." }, { "code": null, "e": 5931, "s": 5758, "text": "Object Action Interface (OAI), can be considered as the next step of the Graphical User Interface (GUI). This model focusses on the priority of the object over the actions." }, { "code": null, "e": 6210, "s": 5931, "text": "The OAI model allows the user to perform action on the object. First the object is selected and then the action is performed on the object. Finally, the outcome is shown to the user. In this model, the user does not have to worry about the complexity of any syntactical actions." }, { "code": null, "e": 6413, "s": 6210, "text": "The object–action model provides an advantage to the user as they gain a sense of control due to the direct involvement in the design process. The computer serves as a medium to signify different tools." }, { "code": null, "e": 6448, "s": 6413, "text": "\n 81 Lectures \n 9.5 hours \n" }, { "code": null, "e": 6470, "s": 6448, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 6505, "s": 6470, "text": "\n 30 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6519, "s": 6505, "text": " Brad Merrill" }, { "code": null, "e": 6552, "s": 6519, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 6584, "s": 6552, "text": " Akaaro Consulting And Training" }, { "code": null, "e": 6617, "s": 6584, "text": "\n 14 Lectures \n 7 hours \n" }, { "code": null, "e": 6625, "s": 6617, "text": " Adrian" }, { "code": null, "e": 6658, "s": 6625, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 6680, "s": 6658, "text": " Dr Swati Chakraborty" }, { "code": null, "e": 6712, "s": 6680, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 6733, "s": 6712, "text": " Prabh Kirpa Classes" }, { "code": null, "e": 6740, "s": 6733, "text": " Print" }, { "code": null, "e": 6751, "s": 6740, "text": " Add Notes" } ]
Pandas - Plotting Histogram from pandas Dataframes - 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 learn about how to plot Histograms using the Pandas library. Pandas library provides us with a way to plot different kinds of charts out of the data frames that are easy to understand and get insights about the data. Pandas library uses the matplotlib as default backend which is the most popular plotting module in python. Histograms are a way to visualize the distribution of the data. This further tells us about how we can perform specific operations to get better and accurate insights from the data. The first step is to import the required libraries and load the data that we will be working upon. For this tutorial, we will be using the popular Pima Indians Diabetes Database. See the code below to execute these steps. All the steps are performed in Jupyter Notebooks. import pandas as pd data = pd.read_csv("diabetes.csv") data.head() Output: Below is the code to get the histograms of all columns of data as subplots of a single plot. We can achieve this by using the hist() method on a pandas data-frame. Also, We have set the total figure size as 10×10 and bins=10 which will divide the scale of a plot into the specified number of bins for better visualization. data.hist(figsize=(10,10),bins=10) Output: We have the flexibility to set some label size and rotation attributes for the plot that we are plotting which are described below. xlabelsize – The size of the x-axis labels in integer. ylabelsize – The size of the y-axis labels in integer. xrot – The clockwise rotation that is to be done on the labels on the x-axis. yrot – The clockwise rotation that is to be done on the labels on the y-axis. color = The colour of the plot. See the code below to see the implementation of attributes defined above data.hist(column="Glucose", figsize=(8,8), xlabelsize=20, ylabelsize=20, xrot=45, bins=5, color='orange') Output: We can also plot histograms of multiple columns inside a single plot by using the plot wrapper around the hist() method. Look at the code below to achieve this. data1 = data[['BloodPressure','BMI']] ax = data1.plot.hist(alpha=0.5, figsize=(10,10),bins=10, title = "BP VS BMI") Output: So, We have learned how to plot histograms out of data-frames by using only the Pandas library and matplotlib as backend. If you have any doubt, feel free to ask in the comment section below. Pandas to_csv – Pandas Save Dataframe to CSV file How to draw shapes using Graphics Pandas read_excel – Read Excel files in Pandas Happy Learning 🙂 Pandas to_excel – Pandas Save Dataframe to Excel File Pandas read_excel – Read Excel files in Pandas Pandas to_csv – Pandas Save Dataframe to CSV file Pandas read_csv – Read CSV file in Pandas and prepare Dataframe How to split Numpy Arrays ? Different ways to use Lambdas in Python How to push docker image to docker hub ? What are Python default function parameters ? Implementing Stack in Python Python raw_input read input from keyboard Indexing in NumPy Arrays How to sort python dictionary by key ? How to do Multiprocessing in Python How to access for loop index in Python Python Decorators – Classes and Functions Pandas to_excel – Pandas Save Dataframe to Excel File Pandas read_excel – Read Excel files in Pandas Pandas to_csv – Pandas Save Dataframe to CSV file Pandas read_csv – Read CSV file in Pandas and prepare Dataframe How to split Numpy Arrays ? Different ways to use Lambdas in Python How to push docker image to docker hub ? What are Python default function parameters ? Implementing Stack in Python Python raw_input read input from keyboard Indexing in NumPy Arrays How to sort python dictionary by key ? How to do Multiprocessing in Python How to access for loop index in Python Python Decorators – Classes and Functions Δ 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": 485, "s": 398, "text": "In this tutorial, we will learn about how to plot Histograms using the Pandas library." }, { "code": null, "e": 748, "s": 485, "text": "Pandas library provides us with a way to plot different kinds of charts out of the data frames that are easy to understand and get insights about the data. Pandas library uses the matplotlib as default backend which is the most popular plotting module in python." }, { "code": null, "e": 930, "s": 748, "text": "Histograms are a way to visualize the distribution of the data. This further tells us about how we can perform specific operations to get better and accurate insights from the data." }, { "code": null, "e": 1202, "s": 930, "text": "The first step is to import the required libraries and load the data that we will be working upon. For this tutorial, we will be using the popular Pima Indians Diabetes Database. See the code below to execute these steps. All the steps are performed in Jupyter Notebooks." }, { "code": null, "e": 1269, "s": 1202, "text": "import pandas as pd\ndata = pd.read_csv(\"diabetes.csv\")\ndata.head()" }, { "code": null, "e": 1277, "s": 1269, "text": "Output:" }, { "code": null, "e": 1600, "s": 1277, "text": "Below is the code to get the histograms of all columns of data as subplots of a single plot. We can achieve this by using the hist() method on a pandas data-frame. Also, We have set the total figure size as 10×10 and bins=10 which will divide the scale of a plot into the specified number of bins for better visualization." }, { "code": null, "e": 1635, "s": 1600, "text": "data.hist(figsize=(10,10),bins=10)" }, { "code": null, "e": 1643, "s": 1635, "text": "Output:" }, { "code": null, "e": 1775, "s": 1643, "text": "We have the flexibility to set some label size and rotation attributes for the plot that we are plotting which are described below." }, { "code": null, "e": 1830, "s": 1775, "text": "xlabelsize – The size of the x-axis labels in integer." }, { "code": null, "e": 1885, "s": 1830, "text": "ylabelsize – The size of the y-axis labels in integer." }, { "code": null, "e": 1963, "s": 1885, "text": "xrot – The clockwise rotation that is to be done on the labels on the x-axis." }, { "code": null, "e": 2041, "s": 1963, "text": "yrot – The clockwise rotation that is to be done on the labels on the y-axis." }, { "code": null, "e": 2073, "s": 2041, "text": "color = The colour of the plot." }, { "code": null, "e": 2147, "s": 2073, "text": "See the code below to see the implementation of attributes defined above" }, { "code": null, "e": 2256, "s": 2147, "text": "data.hist(column=\"Glucose\", figsize=(8,8), \n xlabelsize=20, ylabelsize=20,\n xrot=45, bins=5, color='orange')" }, { "code": null, "e": 2264, "s": 2256, "text": "Output:" }, { "code": null, "e": 2425, "s": 2264, "text": "We can also plot histograms of multiple columns inside a single plot by using the plot wrapper around the hist() method. Look at the code below to achieve this." }, { "code": null, "e": 2541, "s": 2425, "text": "data1 = data[['BloodPressure','BMI']]\nax = data1.plot.hist(alpha=0.5, figsize=(10,10),bins=10, title = \"BP VS BMI\")" }, { "code": null, "e": 2549, "s": 2541, "text": "Output:" }, { "code": null, "e": 2741, "s": 2549, "text": "So, We have learned how to plot histograms out of data-frames by using only the Pandas library and matplotlib as backend. If you have any doubt, feel free to ask in the comment section below." }, { "code": null, "e": 2791, "s": 2741, "text": "Pandas to_csv – Pandas Save Dataframe to CSV file" }, { "code": null, "e": 2825, "s": 2791, "text": "How to draw shapes using Graphics" }, { "code": null, "e": 2872, "s": 2825, "text": "Pandas read_excel – Read Excel files in Pandas" }, { "code": null, "e": 2889, "s": 2872, "text": "Happy Learning 🙂" }, { "code": null, "e": 3513, "s": 2889, "text": "\nPandas to_excel – Pandas Save Dataframe to Excel File\nPandas read_excel – Read Excel files in Pandas\nPandas to_csv – Pandas Save Dataframe to CSV file\nPandas read_csv – Read CSV file in Pandas and prepare Dataframe\nHow to split Numpy Arrays ?\nDifferent ways to use Lambdas in Python\nHow to push docker image to docker hub ?\nWhat are Python default function parameters ?\nImplementing Stack in Python\nPython raw_input read input from keyboard\nIndexing in NumPy Arrays\nHow to sort python dictionary by key ?\nHow to do Multiprocessing in Python\nHow to access for loop index in Python\nPython Decorators – Classes and Functions\n" }, { "code": null, "e": 3567, "s": 3513, "text": "Pandas to_excel – Pandas Save Dataframe to Excel File" }, { "code": null, "e": 3614, "s": 3567, "text": "Pandas read_excel – Read Excel files in Pandas" }, { "code": null, "e": 3664, "s": 3614, "text": "Pandas to_csv – Pandas Save Dataframe to CSV file" }, { "code": null, "e": 3728, "s": 3664, "text": "Pandas read_csv – Read CSV file in Pandas and prepare Dataframe" }, { "code": null, "e": 3756, "s": 3728, "text": "How to split Numpy Arrays ?" }, { "code": null, "e": 3796, "s": 3756, "text": "Different ways to use Lambdas in Python" }, { "code": null, "e": 3837, "s": 3796, "text": "How to push docker image to docker hub ?" }, { "code": null, "e": 3883, "s": 3837, "text": "What are Python default function parameters ?" }, { "code": null, "e": 3912, "s": 3883, "text": "Implementing Stack in Python" }, { "code": null, "e": 3954, "s": 3912, "text": "Python raw_input read input from keyboard" }, { "code": null, "e": 3979, "s": 3954, "text": "Indexing in NumPy Arrays" }, { "code": null, "e": 4018, "s": 3979, "text": "How to sort python dictionary by key ?" }, { "code": null, "e": 4054, "s": 4018, "text": "How to do Multiprocessing in Python" }, { "code": null, "e": 4093, "s": 4054, "text": "How to access for loop index in Python" }, { "code": null, "e": 4135, "s": 4093, "text": "Python Decorators – Classes and Functions" }, { "code": null, "e": 4141, "s": 4139, "text": "Δ" }, { "code": null, "e": 4164, "s": 4141, "text": " Python – Introduction" }, { "code": null, "e": 4183, "s": 4164, "text": " Python – Features" }, { "code": null, "e": 4212, "s": 4183, "text": " Python – Install on Windows" }, { "code": null, "e": 4239, "s": 4212, "text": " Python – Modes of Program" }, { "code": null, "e": 4263, "s": 4239, "text": " Python – Number System" }, { "code": null, "e": 4285, "s": 4263, "text": " Python – Identifiers" }, { "code": null, "e": 4305, "s": 4285, "text": " Python – Operators" }, { "code": null, "e": 4332, "s": 4305, "text": " Python – Ternary Operator" }, { "code": null, "e": 4365, "s": 4332, "text": " Python – Command Line Arguments" }, { "code": null, "e": 4384, "s": 4365, "text": " Python – Keywords" }, { "code": null, "e": 4405, "s": 4384, "text": " Python – Data Types" }, { "code": null, "e": 4434, "s": 4405, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 4464, "s": 4434, "text": " Python – Virtual Environment" }, { "code": null, "e": 4487, "s": 4464, "text": " Pyhton – Type Casting" }, { "code": null, "e": 4511, "s": 4487, "text": " Python – String to Int" }, { "code": null, "e": 4544, "s": 4511, "text": " Python – Conditional Statements" }, { "code": null, "e": 4567, "s": 4544, "text": " Python – if statement" }, { "code": null, "e": 4596, "s": 4567, "text": " Python – *args and **kwargs" }, { "code": null, "e": 4622, "s": 4596, "text": " Python – Date Formatting" }, { "code": null, "e": 4657, "s": 4622, "text": " Python – Read input from keyboard" }, { "code": null, "e": 4677, "s": 4657, "text": " Python – raw_input" }, { "code": null, "e": 4701, "s": 4677, "text": " Python – List In Depth" }, { "code": null, "e": 4730, "s": 4701, "text": " Python – List Comprehension" }, { "code": null, "e": 4753, "s": 4730, "text": " Python – Set in Depth" }, { "code": null, "e": 4783, "s": 4753, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 4808, "s": 4783, "text": " Python – Tuple in Depth" }, { "code": null, "e": 4838, "s": 4808, "text": " Python – Stack Datastructure" }, { "code": null, "e": 4868, "s": 4838, "text": " Python – Classes and Objects" }, { "code": null, "e": 4891, "s": 4868, "text": " Python – Constructors" }, { "code": null, "e": 4922, "s": 4891, "text": " Python – Object Introspection" }, { "code": null, "e": 4944, "s": 4922, "text": " Python – Inheritance" }, { "code": null, "e": 4965, "s": 4944, "text": " Python – Decorators" }, { "code": null, "e": 5001, "s": 4965, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 5031, "s": 5001, "text": " Python – Exceptions Handling" }, { "code": null, "e": 5065, "s": 5031, "text": " Python – User defined Exceptions" }, { "code": null, "e": 5091, "s": 5065, "text": " Python – Multiprocessing" }, { "code": null, "e": 5129, "s": 5091, "text": " Python – Default function parameters" }, { "code": null, "e": 5157, "s": 5129, "text": " Python – Lambdas Functions" }, { "code": null, "e": 5181, "s": 5157, "text": " Python – NumPy Library" }, { "code": null, "e": 5207, "s": 5181, "text": " Python – MySQL Connector" }, { "code": null, "e": 5239, "s": 5207, "text": " Python – MySQL Create Database" }, { "code": null, "e": 5265, "s": 5239, "text": " Python – MySQL Read Data" }, { "code": null, "e": 5293, "s": 5265, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 5324, "s": 5293, "text": " Python – MySQL Update Records" }, { "code": null, "e": 5355, "s": 5324, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 5388, "s": 5355, "text": " Python – String Case Conversion" }, { "code": null, "e": 5423, "s": 5388, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 5460, "s": 5423, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 5498, "s": 5460, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 5524, "s": 5498, "text": " Howto – Merge two Lists" }, { "code": null, "e": 5549, "s": 5524, "text": " Howto – Merge two dicts" }, { "code": null, "e": 5589, "s": 5549, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 5624, "s": 5589, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 5659, "s": 5624, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 5688, "s": 5659, "text": " Howto – Read Env variables" }, { "code": null, "e": 5714, "s": 5688, "text": " Howto – Read a text File" }, { "code": null, "e": 5740, "s": 5714, "text": " Howto – Read a JSON File" }, { "code": null, "e": 5772, "s": 5740, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 5800, "s": 5772, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 5840, "s": 5800, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 5874, "s": 5840, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 5899, "s": 5874, "text": " Howto – create Zip File" }, { "code": null, "e": 5920, "s": 5899, "text": " Howto – Get OS info" }, { "code": null, "e": 5951, "s": 5920, "text": " Howto – Get size of Directory" }, { "code": null, "e": 5988, "s": 5951, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 6025, "s": 5988, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 6047, "s": 6025, "text": " Howto – Sort Objects" }, { "code": null, "e": 6085, "s": 6047, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 6108, "s": 6085, "text": " Howto – Read CSV File" }, { "code": null, "e": 6146, "s": 6108, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 6177, "s": 6146, "text": " Howto – Access for loop index" }, { "code": null, "e": 6215, "s": 6177, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 6255, "s": 6215, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 6302, "s": 6255, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 6334, "s": 6302, "text": " Howto – Sort dictionary by key" } ]
Fragmentation at Network Layer - GeeksforGeeks
26 Oct, 2021 Prerequisite – IPv4 Datagram Fragmentation and Delays Fragmentation is done by the network layer when the maximum size of datagram is greater than maximum size of data that can be held in a frame i.e., its Maximum Transmission Unit (MTU). The network layer divides the datagram received from the transport layer into fragments so that data flow is not disrupted. Since there are 16 bits for total length in IP header so, the maximum size of IP datagram = 216 – 1 = 65, 535 bytes. It is done by the network layer at the destination side and is usually done at routers. Source side does not require fragmentation due to wise (good) segmentation by transport layer i.e. instead of doing segmentation at the transport layer and fragmentation at the network layer, the transport layer looks at datagram data limit and frame data limit and does segmentation in such a way that resulting data can easily fit in a frame without the need of fragmentation. Receiver identifies the frame with the identification (16 bits) field in the IP header. Each fragment of a frame has the same identification number. Receiver identifies the sequence of frames using the fragment offset(13 bits) field in the IP header Overhead at the network layer is present due to the extra header introduced due to fragmentation. Identification (16 bits) – use to identify fragments of the same frame. Fragment offset (13 bits) – use to identify the sequence of fragments in the frame. It generally indicates a number of data bytes preceding or ahead of the fragment. Maximum fragment offset possible = (65535 – 20) = 65515 {where 65535 is the maximum size of datagram and 20 is the minimum size of IP header} So, we need ceil(log265515) = 16 bits for a fragment offset but the fragment offset field has only 13 bits. So, to represent efficiently we need to scale down the fragment offset field by 216/213 = 8 which acts as a scaling factor. Hence, all fragments except the last fragment should have data in multiples of 8 so that fragment offset ∈ N. More fragments (MF = 1 bit) – tells if more fragments are ahead of this fragment i.e. if MF = 1, more fragments are ahead of this fragment and if MF = 0, it is the last fragment. Don’t fragment (DF = 1 bit) – if we don’t want the packet to be fragmented then DF is set i.e. DF = 1. It takes place only at the destination and not at routers since packets take an independent path(datagram packet switching), so all may not meet at a router and hence a need of fragmentation may arise again. The fragments may arrive out of order also. Destination should identify that datagram is fragmented from MF, Fragment offset field.Destination should identify all fragments belonging to same datagram from Identification field.Identify the 1st fragment(offset = 0).Identify subsequent fragments using header length, fragment offset.Repeat until MF = 0. Destination should identify that datagram is fragmented from MF, Fragment offset field. Destination should identify all fragments belonging to same datagram from Identification field. Identify the 1st fragment(offset = 0). Identify subsequent fragments using header length, fragment offset. Repeat until MF = 0. Efficiency (e) = useful/total = (Data without header)/(Data with header) Throughput = e * B { where B is bottleneck bandwidth } Example – An IP router with a Maximum Transmission Unit (MTU) of 200 bytes has received an IP packet of size 520 bytes with an IP header of length 20 bytes. The values of the relevant fields in the IP header. Explanation – Since MTU is 200 bytes and 20 bytes is header size so, the maximum length of data = 180 bytes but it can’t be represented in fragment offset since it is not divisible by 8 so, the maximum length of data feasible = 176 bytes. Number of fragments = (520/200) = 3. Header length = 5 (since scaling factor is 4 therefore, 20/4 = 5) Efficiency, e = (Data without header)/(Data with header) = 500/560 = 89.2 % GATE Practice question – GATE CS 2013 | Question 65GATE-CS-2014-(Set-3) | Question 38GATE-CS-2015 (Set 2) | Question 65GATE-CS-2016 (Set 1) | Question 63GATE CS 2018 | Question 37 GATE CS 2013 | Question 65 GATE-CS-2014-(Set-3) | Question 38 GATE-CS-2015 (Set 2) | Question 65 GATE-CS-2016 (Set 1) | Question 63 GATE CS 2018 | Question 37 coder45g pavanpal25878543 anurag219tiwari Pushpender007 Computer Networks GATE CS Technical Scripter Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Caesar Cipher in Cryptography Socket Programming in Python UDP Server-Client implementation in C Socket Programming in Java Differences between IPv4 and IPv6 ACID Properties in DBMS Types of Operating Systems Page Replacement Algorithms in Operating Systems Normal Forms in DBMS Difference between Process and Thread
[ { "code": null, "e": 36594, "s": 36566, "text": "\n26 Oct, 2021" }, { "code": null, "e": 36649, "s": 36594, "text": "Prerequisite – IPv4 Datagram Fragmentation and Delays " }, { "code": null, "e": 36960, "s": 36649, "text": "Fragmentation is done by the network layer when the maximum size of datagram is greater than maximum size of data that can be held in a frame i.e., its Maximum Transmission Unit (MTU). The network layer divides the datagram received from the transport layer into fragments so that data flow is not disrupted. " }, { "code": null, "e": 37079, "s": 36960, "text": "Since there are 16 bits for total length in IP header so, the maximum size of IP datagram = 216 – 1 = 65, 535 bytes. " }, { "code": null, "e": 37167, "s": 37079, "text": "It is done by the network layer at the destination side and is usually done at routers." }, { "code": null, "e": 37546, "s": 37167, "text": "Source side does not require fragmentation due to wise (good) segmentation by transport layer i.e. instead of doing segmentation at the transport layer and fragmentation at the network layer, the transport layer looks at datagram data limit and frame data limit and does segmentation in such a way that resulting data can easily fit in a frame without the need of fragmentation." }, { "code": null, "e": 37695, "s": 37546, "text": "Receiver identifies the frame with the identification (16 bits) field in the IP header. Each fragment of a frame has the same identification number." }, { "code": null, "e": 37796, "s": 37695, "text": "Receiver identifies the sequence of frames using the fragment offset(13 bits) field in the IP header" }, { "code": null, "e": 37894, "s": 37796, "text": "Overhead at the network layer is present due to the extra header introduced due to fragmentation." }, { "code": null, "e": 37966, "s": 37894, "text": "Identification (16 bits) – use to identify fragments of the same frame." }, { "code": null, "e": 38617, "s": 37966, "text": "Fragment offset (13 bits) – use to identify the sequence of fragments in the frame. It generally indicates a number of data bytes preceding or ahead of the fragment. Maximum fragment offset possible = (65535 – 20) = 65515 {where 65535 is the maximum size of datagram and 20 is the minimum size of IP header} So, we need ceil(log265515) = 16 bits for a fragment offset but the fragment offset field has only 13 bits. So, to represent efficiently we need to scale down the fragment offset field by 216/213 = 8 which acts as a scaling factor. Hence, all fragments except the last fragment should have data in multiples of 8 so that fragment offset ∈ N." }, { "code": null, "e": 38796, "s": 38617, "text": "More fragments (MF = 1 bit) – tells if more fragments are ahead of this fragment i.e. if MF = 1, more fragments are ahead of this fragment and if MF = 0, it is the last fragment." }, { "code": null, "e": 38899, "s": 38796, "text": "Don’t fragment (DF = 1 bit) – if we don’t want the packet to be fragmented then DF is set i.e. DF = 1." }, { "code": null, "e": 39152, "s": 38899, "text": "It takes place only at the destination and not at routers since packets take an independent path(datagram packet switching), so all may not meet at a router and hence a need of fragmentation may arise again. The fragments may arrive out of order also. " }, { "code": null, "e": 39464, "s": 39156, "text": "Destination should identify that datagram is fragmented from MF, Fragment offset field.Destination should identify all fragments belonging to same datagram from Identification field.Identify the 1st fragment(offset = 0).Identify subsequent fragments using header length, fragment offset.Repeat until MF = 0." }, { "code": null, "e": 39552, "s": 39464, "text": "Destination should identify that datagram is fragmented from MF, Fragment offset field." }, { "code": null, "e": 39648, "s": 39552, "text": "Destination should identify all fragments belonging to same datagram from Identification field." }, { "code": null, "e": 39687, "s": 39648, "text": "Identify the 1st fragment(offset = 0)." }, { "code": null, "e": 39755, "s": 39687, "text": "Identify subsequent fragments using header length, fragment offset." }, { "code": null, "e": 39776, "s": 39755, "text": "Repeat until MF = 0." }, { "code": null, "e": 39907, "s": 39776, "text": "Efficiency (e) = useful/total = (Data without header)/(Data with header) \n\nThroughput = e * B { where B is bottleneck bandwidth } " }, { "code": null, "e": 40119, "s": 39907, "text": " Example – An IP router with a Maximum Transmission Unit (MTU) of 200 bytes has received an IP packet of size 520 bytes with an IP header of length 20 bytes. The values of the relevant fields in the IP header. " }, { "code": null, "e": 40538, "s": 40119, "text": "Explanation – Since MTU is 200 bytes and 20 bytes is header size so, the maximum length of data = 180 bytes but it can’t be represented in fragment offset since it is not divisible by 8 so, the maximum length of data feasible = 176 bytes. Number of fragments = (520/200) = 3. Header length = 5 (since scaling factor is 4 therefore, 20/4 = 5) Efficiency, e = (Data without header)/(Data with header) = 500/560 = 89.2 % " }, { "code": null, "e": 40569, "s": 40543, "text": "GATE Practice question – " }, { "code": null, "e": 40726, "s": 40569, "text": "GATE CS 2013 | Question 65GATE-CS-2014-(Set-3) | Question 38GATE-CS-2015 (Set 2) | Question 65GATE-CS-2016 (Set 1) | Question 63GATE CS 2018 | Question 37 " }, { "code": null, "e": 40753, "s": 40726, "text": "GATE CS 2013 | Question 65" }, { "code": null, "e": 40788, "s": 40753, "text": "GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 40823, "s": 40788, "text": "GATE-CS-2015 (Set 2) | Question 65" }, { "code": null, "e": 40858, "s": 40823, "text": "GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 40887, "s": 40858, "text": "GATE CS 2018 | Question 37 " }, { "code": null, "e": 40896, "s": 40887, "text": "coder45g" }, { "code": null, "e": 40913, "s": 40896, "text": "pavanpal25878543" }, { "code": null, "e": 40929, "s": 40913, "text": "anurag219tiwari" }, { "code": null, "e": 40943, "s": 40929, "text": "Pushpender007" }, { "code": null, "e": 40961, "s": 40943, "text": "Computer Networks" }, { "code": null, "e": 40969, "s": 40961, "text": "GATE CS" }, { "code": null, "e": 40988, "s": 40969, "text": "Technical Scripter" }, { "code": null, "e": 41006, "s": 40988, "text": "Computer Networks" }, { "code": null, "e": 41104, "s": 41006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41134, "s": 41104, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 41163, "s": 41134, "text": "Socket Programming in Python" }, { "code": null, "e": 41201, "s": 41163, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 41228, "s": 41201, "text": "Socket Programming in Java" }, { "code": null, "e": 41262, "s": 41228, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 41286, "s": 41262, "text": "ACID Properties in DBMS" }, { "code": null, "e": 41313, "s": 41286, "text": "Types of Operating Systems" }, { "code": null, "e": 41362, "s": 41313, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 41383, "s": 41362, "text": "Normal Forms in DBMS" } ]
How to implement JavaFX event handling using lambda in Java?
JavaFX Button class provides the setOnAction() method that can be used to set an action for the button click event. An EventHandler is a functional interface and holds only one method is the handle() method. @FunctionalInterface public interface EventHandler<T extends Event> extends EventListener In the below example, we can able to implement event handling of JavaFX by using a lambda expression. import javafx.application.*; import javafx.beans.property.*; import javafx.event.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; public class LambdaWithJavaFxTest extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) throws Exception { BorderPane root = new BorderPane(); ToggleButton button = new ToggleButton("Click"); final StringProperty btnText = button.textProperty(); button.setOnAction((event) -> { // lambda expression ToggleButton source = (ToggleButton) event.getSource(); if(source.isSelected()) { btnText.set("Clicked!"); } else { btnText.set("Click!"); } }); root.setCenter(button); Scene scene = new Scene(root); stage.setScene(scene); stage.setWidth(300); stage.setHeight(250); stage.show(); } }
[ { "code": null, "e": 1270, "s": 1062, "text": "JavaFX Button class provides the setOnAction() method that can be used to set an action for the button click event. An EventHandler is a functional interface and holds only one method is the handle() method." }, { "code": null, "e": 1360, "s": 1270, "text": "@FunctionalInterface\npublic interface EventHandler<T extends Event> extends EventListener" }, { "code": null, "e": 1462, "s": 1360, "text": "In the below example, we can able to implement event handling of JavaFX by using a lambda expression." }, { "code": null, "e": 2468, "s": 1462, "text": "import javafx.application.*;\nimport javafx.beans.property.*;\nimport javafx.event.*;\nimport javafx.scene.*;\nimport javafx.scene.control.*;\nimport javafx.scene.layout.*;\nimport javafx.stage.*;\n\npublic class LambdaWithJavaFxTest extends Application {\n public static void main(String[] args) {\n Application.launch(args);\n }\n @Override\n public void start(Stage stage) throws Exception {\n BorderPane root = new BorderPane();\n ToggleButton button = new ToggleButton(\"Click\");\n\n final StringProperty btnText = button.textProperty();\n button.setOnAction((event) -> { // lambda expression\n ToggleButton source = (ToggleButton) event.getSource();\n if(source.isSelected()) {\n btnText.set(\"Clicked!\");\n } else {\n btnText.set(\"Click!\");\n }\n });\n root.setCenter(button); \n Scene scene = new Scene(root);\n stage.setScene(scene);\n stage.setWidth(300);\n stage.setHeight(250);\n stage.show();\n }\n}" } ]
logout - Unix, Linux Command
logout - session-logout. session-logout[options] session-logout[options] logout command allows you to programmatically logout from your session. causes the session manager to take the requested action immediately. Example-1: To logout from current user session: $ logout output: no output on screen, current user session will be logged out. 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10602, "s": 10577, "text": "logout - session-logout." }, { "code": null, "e": 10628, "s": 10602, "text": "session-logout[options] " }, { "code": null, "e": 10653, "s": 10628, "text": "session-logout[options] " }, { "code": null, "e": 10795, "s": 10653, "text": "logout command allows you to programmatically logout from your session. \ncauses the session manager to take the requested action immediately." }, { "code": null, "e": 10806, "s": 10795, "text": "Example-1:" }, { "code": null, "e": 10843, "s": 10806, "text": "To logout from current user session:" }, { "code": null, "e": 10852, "s": 10843, "text": "$ logout" }, { "code": null, "e": 10860, "s": 10852, "text": "output:" }, { "code": null, "e": 10922, "s": 10860, "text": "no output on screen, current user session will be logged out." }, { "code": null, "e": 10957, "s": 10922, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 10985, "s": 10957, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11019, "s": 10985, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11036, "s": 11019, "text": " Frahaan Hussain" }, { "code": null, "e": 11069, "s": 11036, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11080, "s": 11069, "text": " Pradeep D" }, { "code": null, "e": 11115, "s": 11080, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11131, "s": 11115, "text": " Musab Zayadneh" }, { "code": null, "e": 11164, "s": 11131, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11176, "s": 11164, "text": " GUHARAJANM" }, { "code": null, "e": 11208, "s": 11176, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11216, "s": 11208, "text": " Uplatz" }, { "code": null, "e": 11223, "s": 11216, "text": " Print" }, { "code": null, "e": 11234, "s": 11223, "text": " Add Notes" } ]
Python program to find start and end indices of all Words in a String - GeeksforGeeks
11 Oct, 2020 Given a String, return all the start indices and end indices of each word. Examples: Input : test_str = ‘ Geekforgeeks is Best’ Output : [(1, 12), (16, 17), (19, 22)] Explanation : “Best” Starts at 19th index, and ends at 22nd index. Input : test_str = ‘ Geekforgeeks is Best’ Output : [(1, 12), (17, 18), (20, 23)] Explanation : “Best” Starts at 20th index, and ends at 23rd index. Method : Using list comprehension + regex + finditer() In this, we extract all the words using finditer() and regex, to get initial and end index, we use start() and end() and encapsulate using list comprehension in form of tuple list. Python3 # Python3 code to demonstrate working of# Word Ranges in String# Using list comprehension + regex + finditer()import re # initializing stringtest_str = ' Geekforgeeks is Best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # regex to get words, loop to get each start and end indexres = [(ele.start(), ele.end() - 1) for ele in re.finditer(r'\S+', test_str)] # printing resultprint("Word Ranges are : " + str(res)) The original string is : Geekforgeeks is Best for geeks Word Ranges are : [(1, 12), (16, 17), (19, 22), (27, 29), (32, 36)] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 24694, "s": 24666, "text": "\n11 Oct, 2020" }, { "code": null, "e": 24769, "s": 24694, "text": "Given a String, return all the start indices and end indices of each word." }, { "code": null, "e": 24779, "s": 24769, "text": "Examples:" }, { "code": null, "e": 24928, "s": 24779, "text": "Input : test_str = ‘ Geekforgeeks is Best’ Output : [(1, 12), (16, 17), (19, 22)] Explanation : “Best” Starts at 19th index, and ends at 22nd index." }, { "code": null, "e": 25078, "s": 24928, "text": "Input : test_str = ‘ Geekforgeeks is Best’ Output : [(1, 12), (17, 18), (20, 23)] Explanation : “Best” Starts at 20th index, and ends at 23rd index. " }, { "code": null, "e": 25133, "s": 25078, "text": "Method : Using list comprehension + regex + finditer()" }, { "code": null, "e": 25314, "s": 25133, "text": "In this, we extract all the words using finditer() and regex, to get initial and end index, we use start() and end() and encapsulate using list comprehension in form of tuple list." }, { "code": null, "e": 25322, "s": 25314, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Word Ranges in String# Using list comprehension + regex + finditer()import re # initializing stringtest_str = ' Geekforgeeks is Best for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # regex to get words, loop to get each start and end indexres = [(ele.start(), ele.end() - 1) for ele in re.finditer(r'\\S+', test_str)] # printing resultprint(\"Word Ranges are : \" + str(res))", "e": 25787, "s": 25322, "text": null }, { "code": null, "e": 25919, "s": 25787, "text": "The original string is : Geekforgeeks is Best for geeks\nWord Ranges are : [(1, 12), (16, 17), (19, 22), (27, 29), (32, 36)]\n" }, { "code": null, "e": 25942, "s": 25919, "text": "Python string-programs" }, { "code": null, "e": 25949, "s": 25942, "text": "Python" }, { "code": null, "e": 25965, "s": 25949, "text": "Python Programs" }, { "code": null, "e": 26063, "s": 25965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26081, "s": 26063, "text": "Python Dictionary" }, { "code": null, "e": 26116, "s": 26081, "text": "Read a file line by line in Python" }, { "code": null, "e": 26138, "s": 26116, "text": "Enumerate() in Python" }, { "code": null, "e": 26170, "s": 26138, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26200, "s": 26170, "text": "Iterate over a list in Python" }, { "code": null, "e": 26243, "s": 26200, "text": "Python program to convert a list to string" }, { "code": null, "e": 26265, "s": 26243, "text": "Defaultdict in Python" }, { "code": null, "e": 26311, "s": 26265, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26350, "s": 26311, "text": "Python | Get dictionary keys as a list" } ]
Expanding binomial expression using JavaScript
We are required to write a JavaScript function that takes in an expression in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any single character variable, and n is a natural number. If a = 1, no coefficient will be placed in front of the variable. Our function should return the expanded form as a string in the form ax^b+cx^d+ex^f... where a, c, and e are the coefficients of the term, x is the original one-character variable that was passed in the original expression and b, d, and f, are the powers that x is being raised to in each term and are in decreasing order Following is the code − Live Demo const str = '(8a+6)^4'; const trim = value => value === 1 ? '' : value === -1 ? '-' : value const factorial = (value, total = 1) => value <= 1 ? total : factorial(value - 1, total * value) const find = (str = '') => { let [op1, coefficient, variable, op2, constant, power] = str .match(/(\W)(\d*)(\w)(\W)(\d+)..(\d+)/) .slice(1) power = +power if (!power) { return '1' } if (power === 1) { return str.match(/\((.*)\)/)[1] } coefficient = op1 === '-' ? coefficient ? -coefficient : -1 : coefficient ? +coefficient : 1 constant = op2 === '-' ? -constant : +constant const factorials = Array.from({ length: power + 1 }, (_,i) => factorial(i)) let result = '' for (let i = 0, p = power; i <= power; ++i, p = power - i) { let judge = factorials[power] / (factorials[i] * factorials[p]) * (coefficient * p * constant * i) if (!judge) { continue } result += p ? trim(judge) + variable + (p === 1 ? '' : `^${p}`) : judge result += '+' } return result.replace(/\+\-/g, '-').replace(/\+$/, '') }; console.log(find(str)); 576a^3+1152a^2+576a
[ { "code": null, "e": 1349, "s": 1062, "text": "We are required to write a JavaScript function that takes in an expression in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any single character variable, and n is a natural number. If a = 1, no coefficient will be placed in front of the variable." }, { "code": null, "e": 1671, "s": 1349, "text": "Our function should return the expanded form as a string in the form ax^b+cx^d+ex^f... where a, c, and e are the coefficients of the term, x is the original one-character variable that was passed in the original expression and b, d, and f, are the powers that x is being raised to in each term and are in decreasing order" }, { "code": null, "e": 1695, "s": 1671, "text": "Following is the code −" }, { "code": null, "e": 1706, "s": 1695, "text": " Live Demo" }, { "code": null, "e": 2858, "s": 1706, "text": "const str = '(8a+6)^4';\nconst trim = value => value === 1 ? '' : value === -1 ? '-' : value\nconst factorial = (value, total = 1) =>\nvalue <= 1 ? total : factorial(value - 1, total * value)\nconst find = (str = '') => {\n let [op1, coefficient, variable, op2, constant, power] = str\n .match(/(\\W)(\\d*)(\\w)(\\W)(\\d+)..(\\d+)/)\n .slice(1)\n power = +power\n if (!power) {\n return '1'\n }\n if (power === 1) {\n return str.match(/\\((.*)\\)/)[1]\n }\n coefficient =\n op1 === '-'\n ? coefficient\n ? -coefficient\n : -1\n : coefficient\n ? +coefficient\n : 1\n constant = op2 === '-' ? -constant : +constant\n const factorials = Array.from({ length: power + 1 }, (_,i) => factorial(i))\n let result = ''\n for (let i = 0, p = power; i <= power; ++i, p = power - i) {\n let judge =\n factorials[power] / (factorials[i] * factorials[p]) *\n (coefficient * p * constant * i)\n if (!judge) {\n continue\n }\n result += p\n ? trim(judge) + variable + (p === 1 ? '' : `^${p}`)\n : judge\n result += '+'\n }\n return result.replace(/\\+\\-/g, '-').replace(/\\+$/, '')\n};\nconsole.log(find(str));" }, { "code": null, "e": 2878, "s": 2858, "text": "576a^3+1152a^2+576a" } ]
Go - Array of pointers
Before we understand the concept of arrays of pointers, let us consider the following example, which makes use of an array of 3 integers − package main import "fmt" const MAX int = 3 func main() { a := []int{10,100,200} var i int for i = 0; i < MAX; i++ { fmt.Printf("Value of a[%d] = %d\n", i, a[i] ) } } When the above code is compiled and executed, it produces the following result − Value of a[0] = 10 Value of a[1] = 100 Value of a2] = 200 There may be a situation when we want to maintain an array, which can store pointers to an int or string or any other data type available. The following statement declares an array of pointers to an integer − var ptr [MAX]*int; This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. The following example makes use of three integers, which will be stored in an array of pointers as follows − package main import "fmt" const MAX int = 3 func main() { a := []int{10,100,200} var i int var ptr [MAX]*int; for i = 0; i < MAX; i++ { ptr[i] = &a[i] /* assign the address of integer. */ } for i = 0; i < MAX; i++ { fmt.Printf("Value of a[%d] = %d\n", i,*ptr[i] ) } } When the above code is compiled and executed, it produces the following result − Value of a[0] = 10 Value of a[1] = 100 Value of a[2] = 200 64 Lectures 6.5 hours Ridhi Arora 20 Lectures 2.5 hours Asif Hussain 22 Lectures 4 hours Dilip Padmanabhan 48 Lectures 6 hours Arnab Chakraborty 7 Lectures 1 hours Aditya Kulkarni 44 Lectures 3 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2076, "s": 1937, "text": "Before we understand the concept of arrays of pointers, let us consider the following example, which makes use of an array of 3 integers −" }, { "code": null, "e": 2267, "s": 2076, "text": "package main\n\nimport \"fmt\"\n \nconst MAX int = 3\n \nfunc main() {\n a := []int{10,100,200}\n var i int\n\n for i = 0; i < MAX; i++ {\n fmt.Printf(\"Value of a[%d] = %d\\n\", i, a[i] )\n }\n}" }, { "code": null, "e": 2348, "s": 2267, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 2407, "s": 2348, "text": "Value of a[0] = 10\nValue of a[1] = 100\nValue of a2] = 200\n" }, { "code": null, "e": 2616, "s": 2407, "text": "There may be a situation when we want to maintain an array, which can store pointers to an int or string or any other data type available. The following statement declares an array of pointers to an integer −" }, { "code": null, "e": 2636, "s": 2616, "text": "var ptr [MAX]*int;\n" }, { "code": null, "e": 2864, "s": 2636, "text": "This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. The following example makes use of three integers, which will be stored in an array of pointers as follows −" }, { "code": null, "e": 3173, "s": 2864, "text": "package main\n\nimport \"fmt\"\n \nconst MAX int = 3\n \nfunc main() {\n a := []int{10,100,200}\n var i int\n var ptr [MAX]*int;\n\n for i = 0; i < MAX; i++ {\n ptr[i] = &a[i] /* assign the address of integer. */\n }\n for i = 0; i < MAX; i++ {\n fmt.Printf(\"Value of a[%d] = %d\\n\", i,*ptr[i] )\n }\n}" }, { "code": null, "e": 3254, "s": 3173, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3314, "s": 3254, "text": "Value of a[0] = 10\nValue of a[1] = 100\nValue of a[2] = 200\n" }, { "code": null, "e": 3349, "s": 3314, "text": "\n 64 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3362, "s": 3349, "text": " Ridhi Arora" }, { "code": null, "e": 3397, "s": 3362, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3411, "s": 3397, "text": " Asif Hussain" }, { "code": null, "e": 3444, "s": 3411, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 3463, "s": 3444, "text": " Dilip Padmanabhan" }, { "code": null, "e": 3496, "s": 3463, "text": "\n 48 Lectures \n 6 hours \n" }, { "code": null, "e": 3515, "s": 3496, "text": " Arnab Chakraborty" }, { "code": null, "e": 3547, "s": 3515, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 3564, "s": 3547, "text": " Aditya Kulkarni" }, { "code": null, "e": 3597, "s": 3564, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 3616, "s": 3597, "text": " Arnab Chakraborty" }, { "code": null, "e": 3623, "s": 3616, "text": " Print" }, { "code": null, "e": 3634, "s": 3623, "text": " Add Notes" } ]
C++ program to read file word by word?
In this section we will see how we can read file content word by word using C++. The task is very simple. we have to use the file input stream to read file contents. The file stream will open the file by using file name, then using FileStream, load each word and store it into a variable called word. Then print each word one by one. begin file = open file using filename while file has new word, do print the word into the console done end This is a test file. There are many words. The program will read this file word by word #include<iostream> #include<fstream> using namespace std; void read_word_by_word(string filename) { fstream file; string word; file.open(filename.c_str()); while(file > word) { //take word and print cout << word << endl; } file.close(); } main() { string name; cout << "Enter filename: "; cin >> name; read_word_by_word(name); } Enter filename: test_file.txt This is a test file. There are many words. The program will read this file word by word
[ { "code": null, "e": 1396, "s": 1062, "text": "In this section we will see how we can read file content word by word using C++. The task is very simple. we have to use the file input stream to read file contents. The file stream will open the file by using file name, then using FileStream, load each word and store it into a variable called word. Then print each word one by one." }, { "code": null, "e": 1518, "s": 1396, "text": "begin\n file = open file using filename\n while file has new word, do\n print the word into the console\n done\nend" }, { "code": null, "e": 1606, "s": 1518, "text": "This is a test file. There are many words. The program will read this file word by word" }, { "code": null, "e": 1971, "s": 1606, "text": "#include<iostream>\n#include<fstream>\nusing namespace std;\nvoid read_word_by_word(string filename) {\n fstream file;\n string word;\n file.open(filename.c_str());\n while(file > word) { //take word and print\n cout << word << endl;\n }\n file.close();\n}\nmain() {\n string name;\n cout << \"Enter filename: \";\n cin >> name;\n read_word_by_word(name);\n}" }, { "code": null, "e": 2089, "s": 1971, "text": "Enter filename: test_file.txt\nThis\nis\na\ntest\nfile.\nThere\nare\nmany\nwords.\nThe\nprogram\nwill\nread\nthis\nfile\nword\nby\nword" } ]
Real-time Twitter Sentiment Analysis for Brand Improvement and Topic Tracking (Chapter 1/3) | by Chulong Li | Towards Data Science
This is a comprehensive step-by-step tutorial to teach you how to build an end-to-end real-time Twitter monitoring system to track customer behaviors towards brands by identifying sentiments fluctuation, analyzing trending topics and geographic segmentation, and detecting anomaly on scandals, with consideration of improving brands’ customer engagement and retention. You could try this awesome web app and find the full code! Tech Stack: Python, Tweepy, Numpy, Pandas, Seaborn, Plotly, Dash, Scala Kafka, Spark, MySQL, RE, TextBlob, NLTK, HTML, CSS, Flask, JavaScript, React.js and Git Since it’s a comprehensive end-to-end Twitter monitoring system, I’ll break it down into 3 chapters to explain the details under the hood and intuition behind the action. Chapter 1 (You’re here!): Collecting Twitter Data using Streaming Twitter API with Tweepy, MySQL, & Python Chapter 2: Twitter Sentiment Analysis and Interactive Data Visualization using RE, TextBlob, NLTK, and Plotly Chapter 3: Deploy a Real-time Twitter Analytical Web App on Heroku using Dash & Plotly in Python Chapter 4 (Optional): Parallelize Streaming Twitter Sentiment Analysis using Scala, Kafka and Spark Streaming Why this system? This real-time end-to-end Twitter monitoring system is designed for the enterprise to evaluate Twitter data to inform business decisions. As we know twitter is a great place for the real-time high-throughput data source with 6000 tweets per seconds on average, we could use it to uncover the breaking news stories, identify industry-wide trends, and take actions on time. In practice, keep tracking all relevant Twitter content about a brand in real-time, perform analysis as topics or issues emerge, and detect anomaly with alerting. By monitoring brand mentions on Twitter, brands could inform enagement and deliver better experiences for their customers across the world. To get started with Twitter APIs, we need to apply for a developer account first. It’ll allow you yo access Twitter APIs and other tools. Then we create an app to generate two API keys and two access tokens. That’s the most important part to call Twitter APIs. The whole process may take a few minutes but should be done easily. Now click on Details button on the right of your app in APPs under your Twitter Name on the top right (That’s NOT Dashboard button). Then click on Keys and tokens in the subtitle. Create a file called credentials.py, and copy & paste your Consumer API keys and Access token & access token secret into that file. #credentials.pyAPI_KEY = 'XXXXXXXXXX'API_SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXX'ACCESS_TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXX'ACCESS_TOKEN_SECRET = 'XXXXXXXXXXXXXXXXXXX' We’ll use a python library called Tweepy to listen to streaming Twitter data. Create a new file called Main.ipynb and let’s get started. Note: I use Jupyter Notebook for better dev exploration, and you can use .py instead. You could check this Streaming With Tweepy online doc from Tweepy if you’re interested. You could check my full-code version here. First, we need to create a Tweepy’s StreamListener with on_status method for receiving tweets and on_error method for stopping grabbing data due to rate limits. Tweets are known as “status updates”. So the Status class in Tweepy has properties describing the tweet. # Part of MyStreamListener in Main.ipynb# Streaming With Tweepy # Override tweepy.StreamListener to add logic to on_statusclass MyStreamListener(tweepy.StreamListener): def on_status(self, status): # Extract info from tweets id_str = status.id_str created_at = status.created_at user_created_at = status.user.created_at # ...... and more! # I'll talk about it below! (Or check full-code link above) def on_error(self, status_code): ''' Since Twitter API has rate limits, stop srcraping data as it exceed to the thresold. ''' if status_code == 420: # return False to disconnect the stream return False Then, use Oauth in Tweepy for authentication to register our application with Twitter. # Oauth part in Main.ipynb# Import api/access_token keys from credentials.pyimport credentials.pyauth = tweepy.OAuthHandler(credentials.API_KEY, \ credentials.API_SECRET_KEY)auth.set_access_token(credentials.ACCESS_TOEKN, \ credentials.ACCESS_TOKEN_SECRET)api = tweepy.API(auth) Now, start StreamListener with Oauth. In filter method, set tweet language preference and tracking words which is a list of words (e.g. [‘Facebook’ ]). Currently, we use Twitter’s free Standard Stream. Check Twitter Streaming API Documentation to see different streams with different capabilities and limitations. myStreamListener = MyStreamListener()myStream = tweepy.Stream(auth = api.auth, listener = myStreamListener)myStream.filter(languages=["en"], track = settings.TRACK_WORDS)# However, this part won't be reached as the stream listener won't stop automatically. Press STOP button to finish the process. Then, create and connect with MySQL local database for further analysis and storage. You could download the latest version here. The version we use is MySQL Community Edition, a very popular open source database. Set up the MySQL database according to the built-in guide, with database information provided below. mydb = mysql.connector.connect( host="localhost", user="root", passwd="password", database="TwitterDB", charset = 'utf8') Then we need to create a new table if the table doesn’t exit. Of course, it should not exist during the first time. So we create it with following automatic-checking code. if mydb.is_connected(): mycursor = mydb.cursor() mycursor.execute(""" SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '{0}' """.format(TABLE_NAME)) if mycursor.fetchone()[0] != 1: mycursor.execute("CREATE TABLE {} ({})" \ .format(TABLE_NAME, TABLE_ATTRIBUTES)) mydb.commit() mycursor.close() Specify the details for receiving and preprocessing Twitter Data in on_status method. The attributes in status is the same in Tweet Object. id_str is Tweets Id in String format created_at is the time when the tweet was created text is the content of the tweet polarity & subjectivity is the sentiment value by using TextBlob NLP library to perform core sentiment analysis Attributes like user_created_at, user_location, user_description, and user_followers_count are in User Object, which is part of Tweet Object. In addition, coordinates including longitude and latitude is another object called Geo Object in JSON format. # Extract info from tweetsdef on_status(self, status): if status.retweeted: # Avoid retweeted info, and only original tweets will # be received return True # Extract attributes from each tweet id_str = status.id_str created_at = status.created_at text = deEmojify(status.text) # Pre-processing the text sentiment = TextBlob(text).sentiment polarity = sentiment.polarity subjectivity = sentiment.subjectivity user_created_at = status.user.created_at user_location = deEmojify(status.user.location) user_description = deEmojify(status.user.description) user_followers_count =status.user.followers_count longitude = None latitude = None if status.coordinates: longitude = status.coordinates['coordinates'][0] latitude = status.coordinates['coordinates'][1] retweet_count = status.retweet_count favorite_count = status.favorite_count # Quick check contents in tweets print(status.text) print("Long: {}, Lati: {}".format(longitude, latitude)) # Store all data in MySQL if mydb.is_connected(): mycursor = mydb.cursor() sql = "INSERT INTO {} (id_str,created_at,text,polarity,\ subjectivity, user_created_at, user_location,\ user_description, user_followers_count, longitude,\ latitude, retweet_count, favorite_count) VALUES \ (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" \ .format(TABLE_NAME) val = (id_str, created_at, text, polarity, subjectivity,\ user_created_at, user_location, user_description,\ user_followers_count, longitude, latitude,\ retweet_count, favorite_count) mycursor.execute(sql, val) mydb.commit() mycursor.close() Last, in order to allow tweet texts to store in MySQL, we need to do a little bit processing to remove emoji characters through striping all non-ASCII characters, even though the charset of database is utf8. def deEmojify(text): if text: return text.encode('ascii', 'ignore').decode('ascii') else: return None It’s my first technical article, and I appreciate for any feedback!
[ { "code": null, "e": 541, "s": 172, "text": "This is a comprehensive step-by-step tutorial to teach you how to build an end-to-end real-time Twitter monitoring system to track customer behaviors towards brands by identifying sentiments fluctuation, analyzing trending topics and geographic segmentation, and detecting anomaly on scandals, with consideration of improving brands’ customer engagement and retention." }, { "code": null, "e": 600, "s": 541, "text": "You could try this awesome web app and find the full code!" }, { "code": null, "e": 760, "s": 600, "text": "Tech Stack: Python, Tweepy, Numpy, Pandas, Seaborn, Plotly, Dash, Scala Kafka, Spark, MySQL, RE, TextBlob, NLTK, HTML, CSS, Flask, JavaScript, React.js and Git" }, { "code": null, "e": 931, "s": 760, "text": "Since it’s a comprehensive end-to-end Twitter monitoring system, I’ll break it down into 3 chapters to explain the details under the hood and intuition behind the action." }, { "code": null, "e": 1038, "s": 931, "text": "Chapter 1 (You’re here!): Collecting Twitter Data using Streaming Twitter API with Tweepy, MySQL, & Python" }, { "code": null, "e": 1148, "s": 1038, "text": "Chapter 2: Twitter Sentiment Analysis and Interactive Data Visualization using RE, TextBlob, NLTK, and Plotly" }, { "code": null, "e": 1245, "s": 1148, "text": "Chapter 3: Deploy a Real-time Twitter Analytical Web App on Heroku using Dash & Plotly in Python" }, { "code": null, "e": 1355, "s": 1245, "text": "Chapter 4 (Optional): Parallelize Streaming Twitter Sentiment Analysis using Scala, Kafka and Spark Streaming" }, { "code": null, "e": 2047, "s": 1355, "text": "Why this system? This real-time end-to-end Twitter monitoring system is designed for the enterprise to evaluate Twitter data to inform business decisions. As we know twitter is a great place for the real-time high-throughput data source with 6000 tweets per seconds on average, we could use it to uncover the breaking news stories, identify industry-wide trends, and take actions on time. In practice, keep tracking all relevant Twitter content about a brand in real-time, perform analysis as topics or issues emerge, and detect anomaly with alerting. By monitoring brand mentions on Twitter, brands could inform enagement and deliver better experiences for their customers across the world." }, { "code": null, "e": 2185, "s": 2047, "text": "To get started with Twitter APIs, we need to apply for a developer account first. It’ll allow you yo access Twitter APIs and other tools." }, { "code": null, "e": 2376, "s": 2185, "text": "Then we create an app to generate two API keys and two access tokens. That’s the most important part to call Twitter APIs. The whole process may take a few minutes but should be done easily." }, { "code": null, "e": 2688, "s": 2376, "text": "Now click on Details button on the right of your app in APPs under your Twitter Name on the top right (That’s NOT Dashboard button). Then click on Keys and tokens in the subtitle. Create a file called credentials.py, and copy & paste your Consumer API keys and Access token & access token secret into that file." }, { "code": null, "e": 2848, "s": 2688, "text": "#credentials.pyAPI_KEY = 'XXXXXXXXXX'API_SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXX'ACCESS_TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXX'ACCESS_TOKEN_SECRET = 'XXXXXXXXXXXXXXXXXXX'" }, { "code": null, "e": 3202, "s": 2848, "text": "We’ll use a python library called Tweepy to listen to streaming Twitter data. Create a new file called Main.ipynb and let’s get started. Note: I use Jupyter Notebook for better dev exploration, and you can use .py instead. You could check this Streaming With Tweepy online doc from Tweepy if you’re interested. You could check my full-code version here." }, { "code": null, "e": 3469, "s": 3202, "text": "First, we need to create a Tweepy’s StreamListener with on_status method for receiving tweets and on_error method for stopping grabbing data due to rate limits. Tweets are known as “status updates”. So the Status class in Tweepy has properties describing the tweet." }, { "code": null, "e": 4177, "s": 3469, "text": "# Part of MyStreamListener in Main.ipynb# Streaming With Tweepy # Override tweepy.StreamListener to add logic to on_statusclass MyStreamListener(tweepy.StreamListener): def on_status(self, status): # Extract info from tweets id_str = status.id_str created_at = status.created_at user_created_at = status.user.created_at # ...... and more! # I'll talk about it below! (Or check full-code link above) def on_error(self, status_code): ''' Since Twitter API has rate limits, stop srcraping data as it exceed to the thresold. ''' if status_code == 420: # return False to disconnect the stream return False" }, { "code": null, "e": 4264, "s": 4177, "text": "Then, use Oauth in Tweepy for authentication to register our application with Twitter." }, { "code": null, "e": 4593, "s": 4264, "text": "# Oauth part in Main.ipynb# Import api/access_token keys from credentials.pyimport credentials.pyauth = tweepy.OAuthHandler(credentials.API_KEY, \\ credentials.API_SECRET_KEY)auth.set_access_token(credentials.ACCESS_TOEKN, \\ credentials.ACCESS_TOKEN_SECRET)api = tweepy.API(auth)" }, { "code": null, "e": 4907, "s": 4593, "text": "Now, start StreamListener with Oauth. In filter method, set tweet language preference and tracking words which is a list of words (e.g. [‘Facebook’ ]). Currently, we use Twitter’s free Standard Stream. Check Twitter Streaming API Documentation to see different streams with different capabilities and limitations." }, { "code": null, "e": 5205, "s": 4907, "text": "myStreamListener = MyStreamListener()myStream = tweepy.Stream(auth = api.auth, listener = myStreamListener)myStream.filter(languages=[\"en\"], track = settings.TRACK_WORDS)# However, this part won't be reached as the stream listener won't stop automatically. Press STOP button to finish the process." }, { "code": null, "e": 5519, "s": 5205, "text": "Then, create and connect with MySQL local database for further analysis and storage. You could download the latest version here. The version we use is MySQL Community Edition, a very popular open source database. Set up the MySQL database according to the built-in guide, with database information provided below." }, { "code": null, "e": 5656, "s": 5519, "text": "mydb = mysql.connector.connect( host=\"localhost\", user=\"root\", passwd=\"password\", database=\"TwitterDB\", charset = 'utf8')" }, { "code": null, "e": 5828, "s": 5656, "text": "Then we need to create a new table if the table doesn’t exit. Of course, it should not exist during the first time. So we create it with following automatic-checking code." }, { "code": null, "e": 6203, "s": 5828, "text": "if mydb.is_connected(): mycursor = mydb.cursor() mycursor.execute(\"\"\" SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '{0}' \"\"\".format(TABLE_NAME)) if mycursor.fetchone()[0] != 1: mycursor.execute(\"CREATE TABLE {} ({})\" \\ .format(TABLE_NAME, TABLE_ATTRIBUTES)) mydb.commit() mycursor.close()" }, { "code": null, "e": 6343, "s": 6203, "text": "Specify the details for receiving and preprocessing Twitter Data in on_status method. The attributes in status is the same in Tweet Object." }, { "code": null, "e": 6380, "s": 6343, "text": "id_str is Tweets Id in String format" }, { "code": null, "e": 6430, "s": 6380, "text": "created_at is the time when the tweet was created" }, { "code": null, "e": 6463, "s": 6430, "text": "text is the content of the tweet" }, { "code": null, "e": 6575, "s": 6463, "text": "polarity & subjectivity is the sentiment value by using TextBlob NLP library to perform core sentiment analysis" }, { "code": null, "e": 6827, "s": 6575, "text": "Attributes like user_created_at, user_location, user_description, and user_followers_count are in User Object, which is part of Tweet Object. In addition, coordinates including longitude and latitude is another object called Geo Object in JSON format." }, { "code": null, "e": 8652, "s": 6827, "text": "# Extract info from tweetsdef on_status(self, status): if status.retweeted: # Avoid retweeted info, and only original tweets will # be received return True # Extract attributes from each tweet id_str = status.id_str created_at = status.created_at text = deEmojify(status.text) # Pre-processing the text sentiment = TextBlob(text).sentiment polarity = sentiment.polarity subjectivity = sentiment.subjectivity user_created_at = status.user.created_at user_location = deEmojify(status.user.location) user_description = deEmojify(status.user.description) user_followers_count =status.user.followers_count longitude = None latitude = None if status.coordinates: longitude = status.coordinates['coordinates'][0] latitude = status.coordinates['coordinates'][1] retweet_count = status.retweet_count favorite_count = status.favorite_count # Quick check contents in tweets print(status.text) print(\"Long: {}, Lati: {}\".format(longitude, latitude)) # Store all data in MySQL if mydb.is_connected(): mycursor = mydb.cursor() sql = \"INSERT INTO {} (id_str,created_at,text,polarity,\\ subjectivity, user_created_at, user_location,\\ user_description, user_followers_count, longitude,\\ latitude, retweet_count, favorite_count) VALUES \\ (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\" \\ .format(TABLE_NAME) val = (id_str, created_at, text, polarity, subjectivity,\\ user_created_at, user_location, user_description,\\ user_followers_count, longitude, latitude,\\ retweet_count, favorite_count) mycursor.execute(sql, val) mydb.commit() mycursor.close()" }, { "code": null, "e": 8860, "s": 8652, "text": "Last, in order to allow tweet texts to store in MySQL, we need to do a little bit processing to remove emoji characters through striping all non-ASCII characters, even though the charset of database is utf8." }, { "code": null, "e": 8982, "s": 8860, "text": "def deEmojify(text): if text: return text.encode('ascii', 'ignore').decode('ascii') else: return None" } ]
Chef - Data Bags
Chef data bags can be defined as an arbitrary collection of data which one can use with cookbooks. Using data bags is very helpful when one does not wish to hardcode attributes in recipes nor to store attributes in cookbooks. In the following setup, we are trying to communicate to http endpoint URL. For this, we need to create a data bag, which will hold the endpoint URL detail and use it in our recipe. Step 1 − Create a directory for our data bag. mma@laptop:~/chef-repo $ mkdir data_bags/hooks Step 2 − Create a data bag item for request bin. One needs to make sure one is using a defined requestBin URL. vipi@laptop:~/chef-repo $ subl data_bags/hooks/request_bin.json { "id": "request_bin", "url": "http://requestb.in/1abd0kf1" } Step 3 − Create a data bag on the Chef server vipin@laptop:~/chef-repo $ knife data bag create hooks Created data_bag[hooks] Step 4 − Upload the data bag to the Chef server. vipin@laptop:~/chef-repo $ knife data bag from file hooks requestbin.json Updated data_bag_item[hooks::RequestBin] Step 5 − Update the default recipe of the cookbook to receive the required cookbook from a data bag. vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb hook = data_bag_item('hooks', 'request_bin') http_request 'callback' do url hook['url'] end Step 6 − Upload the modified cookbook to the Chef server. vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook Uploading my_cookbook [0.1.0] Step 7 − Run the Chef client on the node to check if the http request bin gets executed. user@server:~$ sudo chef-client ...TRUNCATED OUTPUT... [2013-02-22T20:37:35+00:00] INFO: http_request[callback] GET to http://requestb.in/1abd0kf1 successful ...TRUNCATED OUTPUT... Data bag is a named collection of structure data entries. One needs to define data entry and call the data bag item in JSON file. One can also search for data bag item from within the recipes to use the data stored in the data bags. We created a data bag called hooks. A data bag is a directory within Chef repository. We used knife to create it on the server. Print Add Notes Bookmark this page
[ { "code": null, "e": 2606, "s": 2380, "text": "Chef data bags can be defined as an arbitrary collection of data which one can use with cookbooks. Using data bags is very helpful when one does not wish to hardcode attributes in recipes nor to store attributes in cookbooks." }, { "code": null, "e": 2787, "s": 2606, "text": "In the following setup, we are trying to communicate to http endpoint URL. For this, we need to create a data bag, which will hold the endpoint URL detail and use it in our recipe." }, { "code": null, "e": 2833, "s": 2787, "text": "Step 1 − Create a directory for our data bag." }, { "code": null, "e": 2881, "s": 2833, "text": "mma@laptop:~/chef-repo $ mkdir data_bags/hooks\n" }, { "code": null, "e": 2992, "s": 2881, "text": "Step 2 − Create a data bag item for request bin. One needs to make sure one is using a defined requestBin URL." }, { "code": null, "e": 3127, "s": 2992, "text": "vipi@laptop:~/chef-repo $ subl data_bags/hooks/request_bin.json { \n \"id\": \"request_bin\", \n \"url\": \"http://requestb.in/1abd0kf1\" \n}" }, { "code": null, "e": 3173, "s": 3127, "text": "Step 3 − Create a data bag on the Chef server" }, { "code": null, "e": 3255, "s": 3173, "text": "vipin@laptop:~/chef-repo $ knife data bag create hooks \nCreated data_bag[hooks] \n" }, { "code": null, "e": 3304, "s": 3255, "text": "Step 4 − Upload the data bag to the Chef server." }, { "code": null, "e": 3421, "s": 3304, "text": "vipin@laptop:~/chef-repo $ knife data bag from file hooks requestbin.json \nUpdated data_bag_item[hooks::RequestBin]\n" }, { "code": null, "e": 3522, "s": 3421, "text": "Step 5 − Update the default recipe of the cookbook to receive the required cookbook from a data bag." }, { "code": null, "e": 3695, "s": 3522, "text": "vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb \nhook = data_bag_item('hooks', 'request_bin') \nhttp_request 'callback' do \n url hook['url'] \nend " }, { "code": null, "e": 3753, "s": 3695, "text": "Step 6 − Upload the modified cookbook to the Chef server." }, { "code": null, "e": 3847, "s": 3753, "text": "vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook \nUploading my_cookbook [0.1.0] \n" }, { "code": null, "e": 3936, "s": 3847, "text": "Step 7 − Run the Chef client on the node to check if the http request bin gets executed." }, { "code": null, "e": 4122, "s": 3936, "text": "user@server:~$ sudo chef-client \n...TRUNCATED OUTPUT... \n[2013-02-22T20:37:35+00:00] INFO: http_request[callback] \nGET to http://requestb.in/1abd0kf1 successful \n...TRUNCATED OUTPUT...\n" }, { "code": null, "e": 4355, "s": 4122, "text": "Data bag is a named collection of structure data entries. One needs to define data entry and call the data bag item in JSON file. One can also search for data bag item from within the recipes to use the data stored in the data bags." }, { "code": null, "e": 4483, "s": 4355, "text": "We created a data bag called hooks. A data bag is a directory within Chef repository. We used knife to create it on the server." }, { "code": null, "e": 4490, "s": 4483, "text": " Print" }, { "code": null, "e": 4501, "s": 4490, "text": " Add Notes" } ]
Fun Valentine’s Day “Gift” Ideas For Python Programmers | by Yong Cui | Towards Data Science
Valentine’s Day is just around the corner. I’ve not decided what gift I’ll give to my wife. Picking the right gift is usually a very challenging task for me, as I’m just not a creative person in the romance domain. Most of the time, I just send her some flowers with a gift card, because I just didn’t want to make the mistake again by sending her a weight scale, which made her really mad, although I thought a digital stainless steel smart scale supporting Bluetooth was really cool. This year, I guess that I’ll do something different. In the last couple of years, I’ve started to use Python a lot more than before, and found some interesting projects that can be done with just a few lines of code. In this article, I would like to share three cool mini-projects that can potentially be gift ideas. However, just a quick disclaimer, use them at your own risk, as it’s a recommendation from a so-called “nerd” or “geek”:) The first easy thing for you to do is to draw a heart shape using the numpy and mtaplotlib libraries. Thus, please first make sure you have both installed on your computer, such as by installing them using the pip tool. Copy and paste the following code in your own Python IDE. As you can tell, we use the formula (x**2+y**2–1)**3-x**2*y**3=0, in which ** means exponentiation to the power of the number following the symbol, to generate a series of points contributing to the heart shape. Run the above code, and you’ll see a red heart as below. You can play with the code to change the size, resolution, and even color! I’ll leave these tasks to you if you’re bold enough to use this gift idea :) Another interesting thing to do is to create animated images using the imageio library, which can generate animated images from individual static images. As above, your computer needs to have the imageio library installed. In your photo album, find 10 or more images that are appropriate for the Valentine’s Day, and drop them in a folder called “source_images”, for example. Run the following code in your IDE. Actually, you can also create animated images from a video clip. You can refer to my previous article for further detailed instruction. The last idea that I’d like to share is that you can create a word cloud for your loved one. To do that, we’ll use the wordcloud, imageio, and matplotlib libraries. I wrote a function that takes in a string, an image file that provides the mask for the word cloud, and the destination image file for the created word cloud. In addition, I wrote another function that generates random red colors with the same hue, saturation, but different lightness. I chose the red color as that’s the theme color for the Valentine’s Day. The full code is provided below. Personally, for the string, I just listed a bunch of cities and countries that we have visited or plan to visit in the near future, and I created a variable called words to store these names. For a proof of concept, I just chose the heart image that we created from the first idea by saving the image calling plt.savefig(‘heart.png’). >>> words = 'Paris, France, Houston, Vegas, Italy, America, Rome, Austin, Seattle, Miami, London, Boston, Beijing, Shanghai, Macau, Moscow, Venice, Germany, Australia, Netherlands, Detroit'>>> generate_word_cloud(words, 'heart.png', 'word_cloud.png') After running the above code, a figure like below was created. The above mini-projects just showed you some fun ideas that can potentially be used for your Valentine’s Day. Please feel free to explore these options by trying different combinations of parameters. In addition, you could combine these ideas together, like I did in the third idea. For example, you can make multiple word clouds and mix them with some real images to create some more personalized animated images. Happy Valentine’s Day!
[ { "code": null, "e": 658, "s": 172, "text": "Valentine’s Day is just around the corner. I’ve not decided what gift I’ll give to my wife. Picking the right gift is usually a very challenging task for me, as I’m just not a creative person in the romance domain. Most of the time, I just send her some flowers with a gift card, because I just didn’t want to make the mistake again by sending her a weight scale, which made her really mad, although I thought a digital stainless steel smart scale supporting Bluetooth was really cool." }, { "code": null, "e": 1097, "s": 658, "text": "This year, I guess that I’ll do something different. In the last couple of years, I’ve started to use Python a lot more than before, and found some interesting projects that can be done with just a few lines of code. In this article, I would like to share three cool mini-projects that can potentially be gift ideas. However, just a quick disclaimer, use them at your own risk, as it’s a recommendation from a so-called “nerd” or “geek”:)" }, { "code": null, "e": 1375, "s": 1097, "text": "The first easy thing for you to do is to draw a heart shape using the numpy and mtaplotlib libraries. Thus, please first make sure you have both installed on your computer, such as by installing them using the pip tool. Copy and paste the following code in your own Python IDE." }, { "code": null, "e": 1587, "s": 1375, "text": "As you can tell, we use the formula (x**2+y**2–1)**3-x**2*y**3=0, in which ** means exponentiation to the power of the number following the symbol, to generate a series of points contributing to the heart shape." }, { "code": null, "e": 1796, "s": 1587, "text": "Run the above code, and you’ll see a red heart as below. You can play with the code to change the size, resolution, and even color! I’ll leave these tasks to you if you’re bold enough to use this gift idea :)" }, { "code": null, "e": 2019, "s": 1796, "text": "Another interesting thing to do is to create animated images using the imageio library, which can generate animated images from individual static images. As above, your computer needs to have the imageio library installed." }, { "code": null, "e": 2208, "s": 2019, "text": "In your photo album, find 10 or more images that are appropriate for the Valentine’s Day, and drop them in a folder called “source_images”, for example. Run the following code in your IDE." }, { "code": null, "e": 2344, "s": 2208, "text": "Actually, you can also create animated images from a video clip. You can refer to my previous article for further detailed instruction." }, { "code": null, "e": 2509, "s": 2344, "text": "The last idea that I’d like to share is that you can create a word cloud for your loved one. To do that, we’ll use the wordcloud, imageio, and matplotlib libraries." }, { "code": null, "e": 2868, "s": 2509, "text": "I wrote a function that takes in a string, an image file that provides the mask for the word cloud, and the destination image file for the created word cloud. In addition, I wrote another function that generates random red colors with the same hue, saturation, but different lightness. I chose the red color as that’s the theme color for the Valentine’s Day." }, { "code": null, "e": 2901, "s": 2868, "text": "The full code is provided below." }, { "code": null, "e": 3236, "s": 2901, "text": "Personally, for the string, I just listed a bunch of cities and countries that we have visited or plan to visit in the near future, and I created a variable called words to store these names. For a proof of concept, I just chose the heart image that we created from the first idea by saving the image calling plt.savefig(‘heart.png’)." }, { "code": null, "e": 3487, "s": 3236, "text": ">>> words = 'Paris, France, Houston, Vegas, Italy, America, Rome, Austin, Seattle, Miami, London, Boston, Beijing, Shanghai, Macau, Moscow, Venice, Germany, Australia, Netherlands, Detroit'>>> generate_word_cloud(words, 'heart.png', 'word_cloud.png')" }, { "code": null, "e": 3550, "s": 3487, "text": "After running the above code, a figure like below was created." }, { "code": null, "e": 3965, "s": 3550, "text": "The above mini-projects just showed you some fun ideas that can potentially be used for your Valentine’s Day. Please feel free to explore these options by trying different combinations of parameters. In addition, you could combine these ideas together, like I did in the third idea. For example, you can make multiple word clouds and mix them with some real images to create some more personalized animated images." } ]
CustomThreadPoolExecutor in Java Executor Framework - GeeksforGeeks
28 Mar, 2022 Executors Manage thread execution. At the top of the executor, hierarchy is the Executor interface, which is used to initiate a thread. ExecutorService Extends Executor and provides methods that manage execution. There are three implementations of ExecutorService: ThreadPoolExecutor, ScheduledThreadPoolExecutor, and ForkJoinPool. java.util.concurrent also defines the Executors utility class, which includes some static methods that simplify the creation of various executors. Related to executors are the Future and Callable interfaces. A Future contains a value that is returned by a thread after it executes. Thus, its value becomes defined “in the future,” when the thread terminates. Callable defines a thread that returns a value. In this article, we are going to learn about Custom ThreadPoolExecutor in java. First, let us discuss two concepts been aggressively used here namely thread pool and blocking queue. ThreadPool is a container in which contains some numbers of threads. These threads are given some tasks. When one thread completes its task next task is given to it. While working in a multi-threading environment it’s not practical to create new individual threads for each new task, because creating a new thread is overhead for the operating system.A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, If you try to enqueue items to t and the queue is already full. All operations in the blocking queue are thread-safe. ThreadPool is a container in which contains some numbers of threads. These threads are given some tasks. When one thread completes its task next task is given to it. While working in a multi-threading environment it’s not practical to create new individual threads for each new task, because creating a new thread is overhead for the operating system. A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, If you try to enqueue items to t and the queue is already full. All operations in the blocking queue are thread-safe. Also, the important specific methods that are to be implemented are as follows: Method 1: execute() This method is contained in the Executor interface. This function executes the given task at some time in the future. It returns nothing hence the return type of this method is void. Method 2: myNewFixedThreadPool() This is a factory method of Executors class. It is used to create a fixed number of threads in the thread pool. Parameter: int number of threads Return type: ExecutorService Procedure: Create an interface in which we will create a execute method. This method will execute the task given to it.In the code above generated, we have implemented a runnable interface. We are printing the current name of the thread with a delay of 1000 milliseconds. These are the tasks which we are going to execute.MyExecutor class provides a static method myNewFixedThreadPool in which we will pass the number of threads we want to create. This method tells the thread pool that how many threads are going to be there in the thread pool. These threads will execute tasks till all tasks get completed.This is the custom thread pool class. This class is the heart of the whole mechanism. It uses two important concepts LinkedBlockingQueue and Execution class. The execution class is explained further. This class receives the thread count from the myNewFixedThreadPool method. All the tasks we submit are stored in the queue. All the threads will fetch the tasks from the queue. We submit the task by using the execute method of the MyExecuorService.Execution class performs the very important task of adding creating the number of threads that we want in our thread pool. This class is where we are defining how to fetch the task from LinkedBlockingQueue.Finally, in this class, we are gathering all the pieces together and our custom thread pool is ready. Create an interface in which we will create a execute method. This method will execute the task given to it. In the code above generated, we have implemented a runnable interface. We are printing the current name of the thread with a delay of 1000 milliseconds. These are the tasks which we are going to execute. MyExecutor class provides a static method myNewFixedThreadPool in which we will pass the number of threads we want to create. This method tells the thread pool that how many threads are going to be there in the thread pool. These threads will execute tasks till all tasks get completed. This is the custom thread pool class. This class is the heart of the whole mechanism. It uses two important concepts LinkedBlockingQueue and Execution class. The execution class is explained further. This class receives the thread count from the myNewFixedThreadPool method. All the tasks we submit are stored in the queue. All the threads will fetch the tasks from the queue. We submit the task by using the execute method of the MyExecuorService. Execution class performs the very important task of adding creating the number of threads that we want in our thread pool. This class is where we are defining how to fetch the task from LinkedBlockingQueue. Finally, in this class, we are gathering all the pieces together and our custom thread pool is ready. Implementation: Here we are passing some threads as 3. The number of tasks is 20 and executing them by using execute method. Java // Java Program to illustrate Concept of// CustomThreadPoolExecutor Executor Framework // Importing LinkedBlockingQueue class from java.util// packageimport java.util.concurrent.LinkedBlockingQueue; // Interface// Custom interface for which contains execute methodinterface MyExecutorService { // Method void execute(Runnable r);} // Class 1// Helper classclass MyExecutors { // Member variables of this class int capacity; // Passing the number of threads that // will be in the thread pool static MyExecutorService myNewFixedThreadPool(int capacity) { return new MyThreadPool(capacity); }} // Class 2// Helper class extending to MyExecutorService interfaceclass MyThreadPool implements MyExecutorService { // Member variables of this class static int capacity; static int currentCapacity; // Creating object of LinkedBlockingQueue class // Declaring object of type Runnable static LinkedBlockingQueue<Runnable> linkedTaskBlockingQueue; // Member variables of this class Execution e; // Method 1 public MyThreadPool(int capacity) { // Member variables of this class // this keyword refers to current instance itself this.capacity = capacity; currentCapacity = 0; // Creating a linked blocking queue which will block // if its empty // and it will perform thread safe operation. linkedTaskBlockingQueue = new LinkedBlockingQueue<Runnable>(); // Creating the object of execution class e = new Execution(); } // Method 2 // @Override public void execute(Runnable r) { // Declaring and adding tasks to // blocking queue using add() method linkedTaskBlockingQueue.add(r); // executeMyMethod() method of Execution class // which will execute the tasks e.executeMyMethod(); }} // Class 3// Helper class extending Runnable interfaceclass Execution implements Runnable { // Method 1 of this class void executeMyMethod() { // At start the current capacity will be 0 // The another capacity is the number of threads we // want to create so we will increase the current // capacity count after creating each thread it // means that we will create the threads if the // current capacity is less than capacity passed by // us i.e number of threads we want to create. // In this case 3 threads will get created if (MyThreadPool.currentCapacity < MyThreadPool.capacity) { MyThreadPool.currentCapacity++; // Creating object of Thread class Thread t = new Thread(new Execution()); // Starting the thread t.start(); } } // Method 2 of this class // @Override public void run() { // Till it is true while (true) { // Here we are fetching the tasks from the // linkedblocking queue // which we have submitted using execute method // and executing them if (MyThreadPool.linkedTaskBlockingQueue.size() != 0) { MyThreadPool.linkedTaskBlockingQueue.poll() .run(); } } }} // Class 4// Helper class// Here we are creating a simple task// which is printing current thread nameclass Mytask implements Runnable { // Method 1 of this class // @Override public void run() { // Try block to check for exceptions try { // Making thread to pause fo a second // using sleep() method Thread.sleep(1000); } // Catch block to check for exceptions catch (InterruptedException e) { // Print the exception scaling ith line number // using printStackTrace() method e.printStackTrace(); } // Print and display the current thread using // currentThread() method by getting thread name // using getName() method System.out.println( "Current Thread :-> " + Thread.currentThread().getName()); }} // Class 5// Main Classpublic class ExecutorServiceCustom { // Main driver method public static void main(String[] args) { // Getting the object of MyExcutorService by using // the factory method myNewFixedThreadPool // Passing number of threads as 3 MyExecutorService service = MyExecutors.myNewFixedThreadPool(3); for (int i = 0; i < 20; i++) { // Creating 20 tasks and passing them to execute service.execute(new Mytask()); } Runnable runnableTask = null; }} Output: Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Note: In the above output, we have printed the thread name as defined in the runnable 20 times as we have submitted 20 tasks which is visually described through a video below sweetyty anikakapoor adnanirshad158 anikaseth98 surindertarika1234 sagar0719kumar Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24376, "s": 23557, "text": "Executors Manage thread execution. At the top of the executor, hierarchy is the Executor interface, which is used to initiate a thread. ExecutorService Extends Executor and provides methods that manage execution. There are three implementations of ExecutorService: ThreadPoolExecutor, ScheduledThreadPoolExecutor, and ForkJoinPool. java.util.concurrent also defines the Executors utility class, which includes some static methods that simplify the creation of various executors. Related to executors are the Future and Callable interfaces. A Future contains a value that is returned by a thread after it executes. Thus, its value becomes defined “in the future,” when the thread terminates. Callable defines a thread that returns a value. In this article, we are going to learn about Custom ThreadPoolExecutor in java." }, { "code": null, "e": 24480, "s": 24376, "text": "First, let us discuss two concepts been aggressively used here namely thread pool and blocking queue. " }, { "code": null, "e": 25045, "s": 24480, "text": "ThreadPool is a container in which contains some numbers of threads. These threads are given some tasks. When one thread completes its task next task is given to it. While working in a multi-threading environment it’s not practical to create new individual threads for each new task, because creating a new thread is overhead for the operating system.A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, If you try to enqueue items to t and the queue is already full. All operations in the blocking queue are thread-safe." }, { "code": null, "e": 25397, "s": 25045, "text": "ThreadPool is a container in which contains some numbers of threads. These threads are given some tasks. When one thread completes its task next task is given to it. While working in a multi-threading environment it’s not practical to create new individual threads for each new task, because creating a new thread is overhead for the operating system." }, { "code": null, "e": 25611, "s": 25397, "text": "A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, If you try to enqueue items to t and the queue is already full. All operations in the blocking queue are thread-safe." }, { "code": null, "e": 25691, "s": 25611, "text": "Also, the important specific methods that are to be implemented are as follows:" }, { "code": null, "e": 25711, "s": 25691, "text": "Method 1: execute()" }, { "code": null, "e": 25894, "s": 25711, "text": "This method is contained in the Executor interface. This function executes the given task at some time in the future. It returns nothing hence the return type of this method is void." }, { "code": null, "e": 25927, "s": 25894, "text": "Method 2: myNewFixedThreadPool()" }, { "code": null, "e": 26039, "s": 25927, "text": "This is a factory method of Executors class. It is used to create a fixed number of threads in the thread pool." }, { "code": null, "e": 26072, "s": 26039, "text": "Parameter: int number of threads" }, { "code": null, "e": 26102, "s": 26072, "text": "Return type: ExecutorService " }, { "code": null, "e": 26113, "s": 26102, "text": "Procedure:" }, { "code": null, "e": 27466, "s": 26113, "text": "Create an interface in which we will create a execute method. This method will execute the task given to it.In the code above generated, we have implemented a runnable interface. We are printing the current name of the thread with a delay of 1000 milliseconds. These are the tasks which we are going to execute.MyExecutor class provides a static method myNewFixedThreadPool in which we will pass the number of threads we want to create. This method tells the thread pool that how many threads are going to be there in the thread pool. These threads will execute tasks till all tasks get completed.This is the custom thread pool class. This class is the heart of the whole mechanism. It uses two important concepts LinkedBlockingQueue and Execution class. The execution class is explained further. This class receives the thread count from the myNewFixedThreadPool method. All the tasks we submit are stored in the queue. All the threads will fetch the tasks from the queue. We submit the task by using the execute method of the MyExecuorService.Execution class performs the very important task of adding creating the number of threads that we want in our thread pool. This class is where we are defining how to fetch the task from LinkedBlockingQueue.Finally, in this class, we are gathering all the pieces together and our custom thread pool is ready." }, { "code": null, "e": 27575, "s": 27466, "text": "Create an interface in which we will create a execute method. This method will execute the task given to it." }, { "code": null, "e": 27779, "s": 27575, "text": "In the code above generated, we have implemented a runnable interface. We are printing the current name of the thread with a delay of 1000 milliseconds. These are the tasks which we are going to execute." }, { "code": null, "e": 28066, "s": 27779, "text": "MyExecutor class provides a static method myNewFixedThreadPool in which we will pass the number of threads we want to create. This method tells the thread pool that how many threads are going to be there in the thread pool. These threads will execute tasks till all tasks get completed." }, { "code": null, "e": 28515, "s": 28066, "text": "This is the custom thread pool class. This class is the heart of the whole mechanism. It uses two important concepts LinkedBlockingQueue and Execution class. The execution class is explained further. This class receives the thread count from the myNewFixedThreadPool method. All the tasks we submit are stored in the queue. All the threads will fetch the tasks from the queue. We submit the task by using the execute method of the MyExecuorService." }, { "code": null, "e": 28722, "s": 28515, "text": "Execution class performs the very important task of adding creating the number of threads that we want in our thread pool. This class is where we are defining how to fetch the task from LinkedBlockingQueue." }, { "code": null, "e": 28824, "s": 28722, "text": "Finally, in this class, we are gathering all the pieces together and our custom thread pool is ready." }, { "code": null, "e": 28950, "s": 28824, "text": "Implementation: Here we are passing some threads as 3. The number of tasks is 20 and executing them by using execute method. " }, { "code": null, "e": 28955, "s": 28950, "text": "Java" }, { "code": "// Java Program to illustrate Concept of// CustomThreadPoolExecutor Executor Framework // Importing LinkedBlockingQueue class from java.util// packageimport java.util.concurrent.LinkedBlockingQueue; // Interface// Custom interface for which contains execute methodinterface MyExecutorService { // Method void execute(Runnable r);} // Class 1// Helper classclass MyExecutors { // Member variables of this class int capacity; // Passing the number of threads that // will be in the thread pool static MyExecutorService myNewFixedThreadPool(int capacity) { return new MyThreadPool(capacity); }} // Class 2// Helper class extending to MyExecutorService interfaceclass MyThreadPool implements MyExecutorService { // Member variables of this class static int capacity; static int currentCapacity; // Creating object of LinkedBlockingQueue class // Declaring object of type Runnable static LinkedBlockingQueue<Runnable> linkedTaskBlockingQueue; // Member variables of this class Execution e; // Method 1 public MyThreadPool(int capacity) { // Member variables of this class // this keyword refers to current instance itself this.capacity = capacity; currentCapacity = 0; // Creating a linked blocking queue which will block // if its empty // and it will perform thread safe operation. linkedTaskBlockingQueue = new LinkedBlockingQueue<Runnable>(); // Creating the object of execution class e = new Execution(); } // Method 2 // @Override public void execute(Runnable r) { // Declaring and adding tasks to // blocking queue using add() method linkedTaskBlockingQueue.add(r); // executeMyMethod() method of Execution class // which will execute the tasks e.executeMyMethod(); }} // Class 3// Helper class extending Runnable interfaceclass Execution implements Runnable { // Method 1 of this class void executeMyMethod() { // At start the current capacity will be 0 // The another capacity is the number of threads we // want to create so we will increase the current // capacity count after creating each thread it // means that we will create the threads if the // current capacity is less than capacity passed by // us i.e number of threads we want to create. // In this case 3 threads will get created if (MyThreadPool.currentCapacity < MyThreadPool.capacity) { MyThreadPool.currentCapacity++; // Creating object of Thread class Thread t = new Thread(new Execution()); // Starting the thread t.start(); } } // Method 2 of this class // @Override public void run() { // Till it is true while (true) { // Here we are fetching the tasks from the // linkedblocking queue // which we have submitted using execute method // and executing them if (MyThreadPool.linkedTaskBlockingQueue.size() != 0) { MyThreadPool.linkedTaskBlockingQueue.poll() .run(); } } }} // Class 4// Helper class// Here we are creating a simple task// which is printing current thread nameclass Mytask implements Runnable { // Method 1 of this class // @Override public void run() { // Try block to check for exceptions try { // Making thread to pause fo a second // using sleep() method Thread.sleep(1000); } // Catch block to check for exceptions catch (InterruptedException e) { // Print the exception scaling ith line number // using printStackTrace() method e.printStackTrace(); } // Print and display the current thread using // currentThread() method by getting thread name // using getName() method System.out.println( \"Current Thread :-> \" + Thread.currentThread().getName()); }} // Class 5// Main Classpublic class ExecutorServiceCustom { // Main driver method public static void main(String[] args) { // Getting the object of MyExcutorService by using // the factory method myNewFixedThreadPool // Passing number of threads as 3 MyExecutorService service = MyExecutors.myNewFixedThreadPool(3); for (int i = 0; i < 20; i++) { // Creating 20 tasks and passing them to execute service.execute(new Mytask()); } Runnable runnableTask = null; }}", "e": 33685, "s": 28955, "text": null }, { "code": null, "e": 33694, "s": 33685, "text": "Output: " }, { "code": null, "e": 34254, "s": 33694, "text": "Current Thread :-> Thread-0\nCurrent Thread :-> Thread-1\nCurrent Thread :-> Thread-2\nCurrent Thread :-> Thread-0\nCurrent Thread :-> Thread-1\nCurrent Thread :-> Thread-2\nCurrent Thread :-> Thread-0\nCurrent Thread :-> Thread-1\nCurrent Thread :-> Thread-2\nCurrent Thread :-> Thread-0\nCurrent Thread :-> Thread-1\nCurrent Thread :-> Thread-2\nCurrent Thread :-> Thread-0\nCurrent Thread :-> Thread-1\nCurrent Thread :-> Thread-2\nCurrent Thread :-> Thread-0\nCurrent Thread :-> Thread-1\nCurrent Thread :-> Thread-2\nCurrent Thread :-> Thread-0\nCurrent Thread :-> Thread-1" }, { "code": null, "e": 34429, "s": 34254, "text": "Note: In the above output, we have printed the thread name as defined in the runnable 20 times as we have submitted 20 tasks which is visually described through a video below" }, { "code": null, "e": 34440, "s": 34431, "text": "sweetyty" }, { "code": null, "e": 34452, "s": 34440, "text": "anikakapoor" }, { "code": null, "e": 34467, "s": 34452, "text": "adnanirshad158" }, { "code": null, "e": 34479, "s": 34467, "text": "anikaseth98" }, { "code": null, "e": 34498, "s": 34479, "text": "surindertarika1234" }, { "code": null, "e": 34513, "s": 34498, "text": "sagar0719kumar" }, { "code": null, "e": 34520, "s": 34513, "text": "Picked" }, { "code": null, "e": 34525, "s": 34520, "text": "Java" }, { "code": null, "e": 34530, "s": 34525, "text": "Java" }, { "code": null, "e": 34628, "s": 34530, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34637, "s": 34628, "text": "Comments" }, { "code": null, "e": 34650, "s": 34637, "text": "Old Comments" }, { "code": null, "e": 34680, "s": 34650, "text": "Functional Interfaces in Java" }, { "code": null, "e": 34695, "s": 34680, "text": "Stream In Java" }, { "code": null, "e": 34716, "s": 34695, "text": "Constructors in Java" }, { "code": null, "e": 34762, "s": 34716, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 34781, "s": 34762, "text": "Exceptions in Java" }, { "code": null, "e": 34798, "s": 34781, "text": "Generics in Java" }, { "code": null, "e": 34841, "s": 34798, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 34857, "s": 34841, "text": "Strings in Java" }, { "code": null, "e": 34906, "s": 34857, "text": "How to remove an element from ArrayList in Java?" } ]
How to get timer ticks at a given time in Python?
To get the timer ticks at a given time, use the clock. The python docs state that this function should be used for benchmarking purposes. import time t0= time.clock() print("Hello") t1 = time.clock() - t0 print("Time elapsed: ", t1 - t0) # CPU seconds elapsed (floating point) This will give the output − Time elapsed: 0.0009403145040156798 Note that different systems will have different accuracy based on their internal clock setup (ticks per second). but it's generally at least under 20ms. Also note that clock returns different things on different platforms. On Unix, it returns the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.
[ { "code": null, "e": 1201, "s": 1062, "text": "To get the timer ticks at a given time, use the clock. The python docs state that this function should be used for benchmarking purposes. " }, { "code": null, "e": 1340, "s": 1201, "text": "import time\nt0= time.clock()\nprint(\"Hello\")\nt1 = time.clock() - t0\nprint(\"Time elapsed: \", t1 - t0) # CPU seconds elapsed (floating point)" }, { "code": null, "e": 1368, "s": 1340, "text": "This will give the output −" }, { "code": null, "e": 1405, "s": 1368, "text": "Time elapsed: 0.0009403145040156798" }, { "code": null, "e": 2190, "s": 1405, "text": "Note that different systems will have different accuracy based on their internal clock setup (ticks per second). but it's generally at least under 20ms. Also note that clock returns different things on different platforms. On Unix, it returns the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond." } ]
Perpendicular distance between a point and a Line in 2 D
16 Jun, 2022 Given a point (x1, y1) and a line (ax + by + c = 0). The task is to find the perpendicular distance between the given point and the line. Examples : Input: x1 = 5, y1 = 6, a = -2, b = 3, c = 4 Output:3.32820117735Input: x1 = -1, y1 = 3, a = 4, b = -3, c = – 5 Output:3.6 Approach: The distance (i.e shortest distance) from a given point to a line is the perpendicular distance from that point to the given line. The equation of a line in the plane is given by the equation ax + by + c = 0, where a, b and c are real constants. the co-ordinate of the point is (x1, y1)The formula for distance between a point and a line in 2-D is given by: Distance = (| a*x1 + b*y1 + c |) / (sqrt( a*a + b*b)) Below is the implementation of the above formulae: Program 1: C++ C Java Python C# PHP Javascript // C++ program to find the distance// between a given point and a// given line in 2 D.#include <bits/stdc++.h>using namespace std; // Function to find distancevoid shortest_distance(float x1, float y1, float a, float b, float c){ float d = fabs((a * x1 + b * y1 + c)) / (sqrt(a * a + b * b)); cout << "Perpendicular distance is, " << d << endl; return;} // Driver Codeint main(){ float x1 = 5; float y1 = 6; float a = -2; float b = 3; float c = 4; shortest_distance(x1, y1, a, b, c); return 0;} // This code is contributed Nidhi goel // C program to find the distance// between a given point and a// given line in 2 D.#include<stdio.h>#include<math.h> // Function to find distancevoid shortest_distance(float x1, float y1, float a, float b, float c){ float d = fabs((a * x1 + b * y1 + c)) / (sqrt(a * a + b * b)); printf("Perpendicular distance is %f\n", d); return;} // Driver Codeint main(){ float x1 = 5; float y1 = 6; float a = -2; float b = 3; float c = 4; shortest_distance(x1, y1, a, b, c); return 0;} // This code is contributed// by Amber_Saxena. // Java program to find// the distance between// a given point and a// given line in 2 D.import java.io.*; class GFG{ // Function to find distance static void shortest_distance(float x1, float y1, float a, float b, float c) { double d = Math.abs(((a * x1 + b * y1 + c)) / (Math.sqrt(a * a + b * b))); System.out.println("Perpendicular " + "distance is " + d); return; } // Driver code public static void main (String[] args) { float x1 = 5; float y1 = 6; float a = -2; float b = 3; float c = 4; shortest_distance(x1, y1, a, b, c); }} // This code is contributed// by Mahadev. # Python program to find the distance between# a given point and a given line in 2 D. import math # Function to find distancedef shortest_distance(x1, y1, a, b, c): d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b)) print("Perpendicular distance is"),d # Driver Codex1 = 5y1 = 6a = -2b = 3c = 4shortest_distance(x1, y1, a, b, c) // C# program to find// the distance between// a given point and a// given line in 2 D.using System; class GFG{ // Function to find distance static void shortest_distance(float x1, float y1, float a, float b, float c) { double d = Math.Abs(((a * x1 + b * y1 + c)) / (Math.Sqrt(a * a + b * b))); Console.WriteLine("Perpendicular " + "distance is " + d); return; } // Driver code public static void Main () { float x1 = 5; float y1 = 6; float a = -2; float b = 3; float c = 4; shortest_distance(x1, y1, a, b, c); }} // This code is contributed// by inder_verma.. <?php// PHP program to find the distance// between a given point and a// given line in 2 D. // Function to find distancefunction shortest_distance($x1, $y1, $a, $b, $c){ $d = abs(($a * $x1 + $b * $y1 + $c)) / (sqrt($a * $a + $b * $b)); echo"Perpendicular distance is ", $d;} // Driver Code$x1 = 5;$y1 = 6;$a = -2;$b = 3;$c = 4;shortest_distance($x1, $y1, $a, $b, $c); // This code is contributed// by inder_verma..?> <script> // Javascript program to find// the distance between// a given point and a// given line in 2 D. // Function to find distance function shortest_distance(x1 , y1 , a , b , c) { var d = Math.abs(( (a * x1 + b * y1 + c)) / (Math.sqrt(a * a + b * b))); document.write("Perpendicular " + "distance is " + d.toFixed(11)); return; } // Driver code var x1 = 5; var y1 = 6; var a = -2; var b = 3; var c = 4; shortest_distance(x1, y1, a, b, c); // This code is contributed by todaysgaurav </script> Perpendicular distance is 3.32820117735 Time Complexity: O(1)Auxiliary Space: O(1) Program 2: C++ C Java Python C# PHP Javascript // C++ program to find the distance// between a given point and a// given line in 2 D.#include <bits/stdc++.h>using namespace std; // Function to find distancevoid shortest_distance(float x1, float y1, float a, float b, float c){ float d = fabs((a * x1 + b * y1 + c)) / (sqrt(a * a + b * b)); cout << "Perpendicular distance is " << d << endl; return;} // Driver Codeint main(){ float x1 = -1; float y1 = 3; float a = 4; float b = -3; float c = -5; shortest_distance(x1, y1, a, b, c); return 0;} // This code is contributed by Nidhi goel // C program to find the distance// between a given point and a// given line in 2 D.#include<stdio.h>#include<math.h> // Function to find distancevoid shortest_distance(float x1, float y1, float a, float b, float c){ float d = fabs((a * x1 + b * y1 + c)) / (sqrt(a * a + b * b)); printf("Perpendicular distance is %f\n", d); return;} // Driver Codeint main(){ float x1 = -1; float y1 = 3; float a = 4; float b = -3; float c = - 5; shortest_distance(x1, y1, a, b, c); return 0;} // This code is contributed// by Amber_Saxena. // Java program to find the distance// between a given point and a// given line in 2 D.class GFG{// Function to find distancestatic void shortest_distance(double x1, double y1, double a, double b, double c){ double d = Math.abs((a * x1 + b * y1 + c)) / (Math.sqrt(a * a + b * b)); System.out.println("Perpendicular distance is " + d); return;} // Driver Codepublic static void main(String[] args){ double x1 = -1; double y1 = 3; double a = 4; double b = -3; double c = - 5; shortest_distance(x1, y1, a, b, c);}} // This code is contributed// by mits # Python program to find the distance between# a given point and a given line in 2 D. import math # Function to find distancedef shortest_distance(x1, y1, a, b, c): d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b)) print("Perpendicular distance is"),d # Driver Codex1 = -1y1 = 3a = 4b = -3c = - 5shortest_distance(x1, y1, a, b, c) // C# program to find the distance// between a given point and a// given line in 2 D.using System; class GFG{// Function to find distancestatic void shortest_distance(double x1, double y1, double a, double b, double c){ double d = Math.Abs((a * x1 + b * y1 + c)) / (Math.Sqrt(a * a + b * b)); Console.WriteLine("Perpendicular distance is " + d); return;} // Driver Codepublic static void Main(){ double x1 = -1; double y1 = 3; double a = 4; double b = -3; double c = - 5; shortest_distance(x1, y1, a, b, c);}} // This code is contributed// by Akanksha Rai <?php// PHP program to find the distance// between a given point and a// given line in 2 D. // Function to find distancefunction shortest_distance($x1, $y1, $a, $b, $c){ $d = abs((int)($a * $x1 + $b * $y1 + $c) / sqrt($a * $a + $b * $b)); echo"Perpendicular distance is ", $d;} // Driver Code$x1 = -1;$y1 = 3;$a = 4;$b = -3;$c = -5;shortest_distance($x1, $y1, $a, $b, $c); // This code is contributed// by inder_verma..?> <script> // Javascript program to find the distance// between a given point and a// given line in 2 D. // Function to find distancefunction shortest_distance(x1, y1, a, b, c){ let d = Math.abs((a * x1 + b * y1 + c)) / (Math.sqrt(a * a + b * b)); document.write("Perpendicular distance is " + d); return;} // driver program let x1 = -1; let y1 = 3; let a = 4; let b = -3; let c = - 5; shortest_distance(x1, y1, a, b, c); // This code is contributed by susmitakundugoaldanga.</script> Perpendicular distance is 3.6 Time Complexity: O(1)Auxiliary Space: O(1) Amber_Saxena Mahadev99 inderDuMCA Mithun Kumar Akanksha_Rai susmitakundugoaldanga todaysgaurav simranarora5sos amankr0211 classroompxico math school-programming Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jun, 2022" }, { "code": null, "e": 192, "s": 53, "text": "Given a point (x1, y1) and a line (ax + by + c = 0). The task is to find the perpendicular distance between the given point and the line. " }, { "code": null, "e": 205, "s": 192, "text": "Examples : " }, { "code": null, "e": 327, "s": 205, "text": "Input: x1 = 5, y1 = 6, a = -2, b = 3, c = 4 Output:3.32820117735Input: x1 = -1, y1 = 3, a = 4, b = -3, c = – 5 Output:3.6" }, { "code": null, "e": 698, "s": 329, "text": "Approach: The distance (i.e shortest distance) from a given point to a line is the perpendicular distance from that point to the given line. The equation of a line in the plane is given by the equation ax + by + c = 0, where a, b and c are real constants. the co-ordinate of the point is (x1, y1)The formula for distance between a point and a line in 2-D is given by: " }, { "code": null, "e": 752, "s": 698, "text": "Distance = (| a*x1 + b*y1 + c |) / (sqrt( a*a + b*b))" }, { "code": null, "e": 816, "s": 752, "text": "Below is the implementation of the above formulae: Program 1: " }, { "code": null, "e": 820, "s": 816, "text": "C++" }, { "code": null, "e": 822, "s": 820, "text": "C" }, { "code": null, "e": 827, "s": 822, "text": "Java" }, { "code": null, "e": 834, "s": 827, "text": "Python" }, { "code": null, "e": 837, "s": 834, "text": "C#" }, { "code": null, "e": 841, "s": 837, "text": "PHP" }, { "code": null, "e": 852, "s": 841, "text": "Javascript" }, { "code": "// C++ program to find the distance// between a given point and a// given line in 2 D.#include <bits/stdc++.h>using namespace std; // Function to find distancevoid shortest_distance(float x1, float y1, float a, float b, float c){ float d = fabs((a * x1 + b * y1 + c)) / (sqrt(a * a + b * b)); cout << \"Perpendicular distance is, \" << d << endl; return;} // Driver Codeint main(){ float x1 = 5; float y1 = 6; float a = -2; float b = 3; float c = 4; shortest_distance(x1, y1, a, b, c); return 0;} // This code is contributed Nidhi goel", "e": 1452, "s": 852, "text": null }, { "code": "// C program to find the distance// between a given point and a// given line in 2 D.#include<stdio.h>#include<math.h> // Function to find distancevoid shortest_distance(float x1, float y1, float a, float b, float c){ float d = fabs((a * x1 + b * y1 + c)) / (sqrt(a * a + b * b)); printf(\"Perpendicular distance is %f\\n\", d); return;} // Driver Codeint main(){ float x1 = 5; float y1 = 6; float a = -2; float b = 3; float c = 4; shortest_distance(x1, y1, a, b, c); return 0;} // This code is contributed// by Amber_Saxena.", "e": 2060, "s": 1452, "text": null }, { "code": "// Java program to find// the distance between// a given point and a// given line in 2 D.import java.io.*; class GFG{ // Function to find distance static void shortest_distance(float x1, float y1, float a, float b, float c) { double d = Math.abs(((a * x1 + b * y1 + c)) / (Math.sqrt(a * a + b * b))); System.out.println(\"Perpendicular \" + \"distance is \" + d); return; } // Driver code public static void main (String[] args) { float x1 = 5; float y1 = 6; float a = -2; float b = 3; float c = 4; shortest_distance(x1, y1, a, b, c); }} // This code is contributed// by Mahadev.", "e": 2836, "s": 2060, "text": null }, { "code": "# Python program to find the distance between# a given point and a given line in 2 D. import math # Function to find distancedef shortest_distance(x1, y1, a, b, c): d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b)) print(\"Perpendicular distance is\"),d # Driver Codex1 = 5y1 = 6a = -2b = 3c = 4shortest_distance(x1, y1, a, b, c) ", "e": 3192, "s": 2836, "text": null }, { "code": "// C# program to find// the distance between// a given point and a// given line in 2 D.using System; class GFG{ // Function to find distance static void shortest_distance(float x1, float y1, float a, float b, float c) { double d = Math.Abs(((a * x1 + b * y1 + c)) / (Math.Sqrt(a * a + b * b))); Console.WriteLine(\"Perpendicular \" + \"distance is \" + d); return; } // Driver code public static void Main () { float x1 = 5; float y1 = 6; float a = -2; float b = 3; float c = 4; shortest_distance(x1, y1, a, b, c); }} // This code is contributed// by inder_verma..", "e": 3946, "s": 3192, "text": null }, { "code": "<?php// PHP program to find the distance// between a given point and a// given line in 2 D. // Function to find distancefunction shortest_distance($x1, $y1, $a, $b, $c){ $d = abs(($a * $x1 + $b * $y1 + $c)) / (sqrt($a * $a + $b * $b)); echo\"Perpendicular distance is \", $d;} // Driver Code$x1 = 5;$y1 = 6;$a = -2;$b = 3;$c = 4;shortest_distance($x1, $y1, $a, $b, $c); // This code is contributed// by inder_verma..?>", "e": 4383, "s": 3946, "text": null }, { "code": "<script> // Javascript program to find// the distance between// a given point and a// given line in 2 D. // Function to find distance function shortest_distance(x1 , y1 , a , b , c) { var d = Math.abs(( (a * x1 + b * y1 + c)) / (Math.sqrt(a * a + b * b))); document.write(\"Perpendicular \" + \"distance is \" + d.toFixed(11)); return; } // Driver code var x1 = 5; var y1 = 6; var a = -2; var b = 3; var c = 4; shortest_distance(x1, y1, a, b, c); // This code is contributed by todaysgaurav </script>", "e": 4979, "s": 4383, "text": null }, { "code": null, "e": 5019, "s": 4979, "text": "Perpendicular distance is 3.32820117735" }, { "code": null, "e": 5064, "s": 5021, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 5077, "s": 5064, "text": "Program 2: " }, { "code": null, "e": 5081, "s": 5077, "text": "C++" }, { "code": null, "e": 5083, "s": 5081, "text": "C" }, { "code": null, "e": 5088, "s": 5083, "text": "Java" }, { "code": null, "e": 5095, "s": 5088, "text": "Python" }, { "code": null, "e": 5098, "s": 5095, "text": "C#" }, { "code": null, "e": 5102, "s": 5098, "text": "PHP" }, { "code": null, "e": 5113, "s": 5102, "text": "Javascript" }, { "code": "// C++ program to find the distance// between a given point and a// given line in 2 D.#include <bits/stdc++.h>using namespace std; // Function to find distancevoid shortest_distance(float x1, float y1, float a, float b, float c){ float d = fabs((a * x1 + b * y1 + c)) / (sqrt(a * a + b * b)); cout << \"Perpendicular distance is \" << d << endl; return;} // Driver Codeint main(){ float x1 = -1; float y1 = 3; float a = 4; float b = -3; float c = -5; shortest_distance(x1, y1, a, b, c); return 0;} // This code is contributed by Nidhi goel", "e": 5716, "s": 5113, "text": null }, { "code": "// C program to find the distance// between a given point and a// given line in 2 D.#include<stdio.h>#include<math.h> // Function to find distancevoid shortest_distance(float x1, float y1, float a, float b, float c){ float d = fabs((a * x1 + b * y1 + c)) / (sqrt(a * a + b * b)); printf(\"Perpendicular distance is %f\\n\", d); return;} // Driver Codeint main(){ float x1 = -1; float y1 = 3; float a = 4; float b = -3; float c = - 5; shortest_distance(x1, y1, a, b, c); return 0;} // This code is contributed// by Amber_Saxena.", "e": 6328, "s": 5716, "text": null }, { "code": "// Java program to find the distance// between a given point and a// given line in 2 D.class GFG{// Function to find distancestatic void shortest_distance(double x1, double y1, double a, double b, double c){ double d = Math.abs((a * x1 + b * y1 + c)) / (Math.sqrt(a * a + b * b)); System.out.println(\"Perpendicular distance is \" + d); return;} // Driver Codepublic static void main(String[] args){ double x1 = -1; double y1 = 3; double a = 4; double b = -3; double c = - 5; shortest_distance(x1, y1, a, b, c);}} // This code is contributed// by mits", "e": 6976, "s": 6328, "text": null }, { "code": "# Python program to find the distance between# a given point and a given line in 2 D. import math # Function to find distancedef shortest_distance(x1, y1, a, b, c): d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b)) print(\"Perpendicular distance is\"),d # Driver Codex1 = -1y1 = 3a = 4b = -3c = - 5shortest_distance(x1, y1, a, b, c) ", "e": 7334, "s": 6976, "text": null }, { "code": "// C# program to find the distance// between a given point and a// given line in 2 D.using System; class GFG{// Function to find distancestatic void shortest_distance(double x1, double y1, double a, double b, double c){ double d = Math.Abs((a * x1 + b * y1 + c)) / (Math.Sqrt(a * a + b * b)); Console.WriteLine(\"Perpendicular distance is \" + d); return;} // Driver Codepublic static void Main(){ double x1 = -1; double y1 = 3; double a = 4; double b = -3; double c = - 5; shortest_distance(x1, y1, a, b, c);}} // This code is contributed// by Akanksha Rai", "e": 7988, "s": 7334, "text": null }, { "code": "<?php// PHP program to find the distance// between a given point and a// given line in 2 D. // Function to find distancefunction shortest_distance($x1, $y1, $a, $b, $c){ $d = abs((int)($a * $x1 + $b * $y1 + $c) / sqrt($a * $a + $b * $b)); echo\"Perpendicular distance is \", $d;} // Driver Code$x1 = -1;$y1 = 3;$a = 4;$b = -3;$c = -5;shortest_distance($x1, $y1, $a, $b, $c); // This code is contributed// by inder_verma..?>", "e": 8455, "s": 7988, "text": null }, { "code": "<script> // Javascript program to find the distance// between a given point and a// given line in 2 D. // Function to find distancefunction shortest_distance(x1, y1, a, b, c){ let d = Math.abs((a * x1 + b * y1 + c)) / (Math.sqrt(a * a + b * b)); document.write(\"Perpendicular distance is \" + d); return;} // driver program let x1 = -1; let y1 = 3; let a = 4; let b = -3; let c = - 5; shortest_distance(x1, y1, a, b, c); // This code is contributed by susmitakundugoaldanga.</script>", "e": 8986, "s": 8455, "text": null }, { "code": null, "e": 9016, "s": 8986, "text": "Perpendicular distance is 3.6" }, { "code": null, "e": 9061, "s": 9018, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 9074, "s": 9061, "text": "Amber_Saxena" }, { "code": null, "e": 9084, "s": 9074, "text": "Mahadev99" }, { "code": null, "e": 9095, "s": 9084, "text": "inderDuMCA" }, { "code": null, "e": 9108, "s": 9095, "text": "Mithun Kumar" }, { "code": null, "e": 9121, "s": 9108, "text": "Akanksha_Rai" }, { "code": null, "e": 9143, "s": 9121, "text": "susmitakundugoaldanga" }, { "code": null, "e": 9156, "s": 9143, "text": "todaysgaurav" }, { "code": null, "e": 9172, "s": 9156, "text": "simranarora5sos" }, { "code": null, "e": 9183, "s": 9172, "text": "amankr0211" }, { "code": null, "e": 9198, "s": 9183, "text": "classroompxico" }, { "code": null, "e": 9203, "s": 9198, "text": "math" }, { "code": null, "e": 9222, "s": 9203, "text": "school-programming" }, { "code": null, "e": 9232, "s": 9222, "text": "Geometric" }, { "code": null, "e": 9245, "s": 9232, "text": "Mathematical" }, { "code": null, "e": 9264, "s": 9245, "text": "School Programming" }, { "code": null, "e": 9277, "s": 9264, "text": "Mathematical" }, { "code": null, "e": 9287, "s": 9277, "text": "Geometric" } ]
Tryit Editor v3.7
CSS Grid Item Tryit: Sort grid items
[ { "code": null, "e": 23, "s": 9, "text": "CSS Grid Item" } ]
Interactive Bar Charts with Bokeh | by Ilya Hopkins | Towards Data Science
This article is the second part of my Bokeh love story. The full story (including Jupyter notebooks and all files) is on my Github. The first part of the story is described in the Medium article “Easy Data Visualization Techniques with Bokeh”. No way your data story is full without visualizations, and bar charts are arguably one of the most loved types of categorical data representation. There is a myriad of types, palettes and styles of this Lego-like graphs, and that’s why I decided to devote them a separate article. Let’s start with the simple vertical and horizontal bar charts. We will get to the more complex ones in a jiffy. It is pretty straight-forward to draw bar charts with Bokeh. As usual, we need to specify a type of chart (or chose a glyph) and pass the data to the plotting function. Let’s create a vertical bar chart showing changes in measles occurrences in the US over the years 2000–2015 using the same UN world healthcare indicators database. # Creating a list of categoriesyears = data[data['country']=='United States of America']['year']#Creating the list of valuesvalues = data[data['country']=='United States of America']['measles']# Initializing the plotp = figure( plot_height=300, title="Measles in the USA 2000-2015", tools=TOOLS)#Plottingp.vbar(years, #categories top = values, #bar heights width = .9, fill_alpha = .5, fill_color = 'salmon', line_alpha = .5, line_color='green', line_dash='dashed' )#Signing the axisp.xaxis.axis_label="Years"p.yaxis.axis_label="Measles stats"show(p) Voila! Absolutely in the same fashion, we could create horizontal bar charts. Let’s use reported polio rates for Argentina in 2000–2015 for illustration purposes. # Creating a list of categoriesyears = data[data['country']=='Argentina']['year']#Creating the list of valuesvalues = data[data['country']=='Argentina']['polio'].values# Initializing the plotp = figure( plot_height=300, title="Polio in the Argentina 2000-2015")#Plottingp.hbar(years, left = 0, right = values, height = .9, fill_color = 'azure', line_color='green', line_alpha=.5 )p.xaxis.axis_label="Years"p.yaxis.axis_label="Polio stats"show(p) The code is super-intuitive; we just have to remember we are working with horizontal bars. Our bar charts are rendered in a very simple manner, and they definitely can benefit from some added make-up. For a list of some available palettes please visit Bokeh palettes documentation. In order to use any of them with Bokeh we need to import them specifically. Let’s look at the measles data for a number of countries in 2015 — we’ll render two graphs with a pre-set palette and a randomly chosen colors, as well as we will use the *gridplot* technique. #Importing a pallettefrom bokeh.palettes import Spectral5, Viridis256, Colorblind, Magma256, Turbo256# Creating a list of categorical values values = data[(data['year']==2015)&(data['country'].isin(countries))]['measles']# Set the x_range to the list of categories abovep1 = figure(x_range=countries, plot_height=250, title="Measles in the world in 2015 (pre-set pallette)")# Categorical values can also be used as coordinatesp1.vbar(x=countries, top=values, width=0.9, color = Spectral5, fill_alpha=.75)# Set some properties to make the plot look betterp1.yaxis.axis_label="Measles stats"p1.xgrid.grid_line_color='gray'p1.xgrid.grid_line_alpha=.75p1.xgrid.grid_line_dash = 'dashed'p1.ygrid.grid_line_color='blue'p1.ygrid.grid_line_alpha = .55p1.ygrid.grid_line_dash = 'dotted'p2 = figure(x_range=countries, plot_height=250, title="Measles in the world in 2015 (randomly selected colors from a pallette)")# Categorical values can also be used as coordinatesp2.vbar(x=countries, top=values, width=0.9, color = random.sample(Viridis256,5), fill_alpha=.75)# Set some properties to make the plot look betterp2.yaxis.axis_label="Measles stats"p2.xgrid.grid_line_color='gray'p2.xgrid.grid_line_alpha=.75p2.xgrid.grid_line_dash = 'dashed'p2.ygrid.grid_line_color='blue'p2.ygrid.grid_line_alpha = .55p2.ygrid.grid_line_dash = 'dotted'p = gridplot([[p1,None],[p2,None]], toolbar_location='right')show(p) And here’s the result: This plot looks much friendlier then the ones we started with. And there’s no end to experiments with colors and palettes. Sometimes we need to plot a grouped bar chart. For example, we might need to group our health indicators for some countries. For that, we need to import a special procedure from the bokeh.models module — FactorRange. Let’s look at the data for measles, polio and hiv/aids*1000 for our list of countries for 2014. from bokeh.models import FactorRange#List of used statisticsstats = ['measles','polio','hiv/aids*1000']#Creating a dictionary of our datamdata = {'countries' : countries, 'measles' : data[data['year']==2014][data['country'].isin(countries)]['measles'], 'polio' : data[data['year']==2014][data['country'].isin(countries)]['polio'], 'hiv/aids*1000' : data[data['year']==2014][data['country'].isin(countries)]['hiv/aids']*1000}# Creating tuples for individual bars [ ("France", "measles"), ("France", "polio"), ("France", "hiv/aids*1000"), ("Canada", "measles"), ... ]x = [ (country, stat) for country in countries for stat in stats ]counts = sum(zip(mdata['measles'], mdata['polio'], mdata['hiv/aids*1000']), ())#Creating a column data source - Bokeh's own data type with the fields (Country,[stats],[values],[colors]) source = ColumnDataSource(data=dict(x=x, counts=counts, color=random.sample(Turbo256,15)))#Initializing our plotp = figure(x_range=FactorRange(*x), plot_height=350, title="Health Stats by Country")#Plotting our vertical bar chartp.vbar(x='x', top='counts', width=0.9 ,fill_color='color', source=source)#Enhancing our graphp.y_range.start = 0p.x_range.range_padding = 0.1p.xaxis.major_label_orientation = .9p.xgrid.grid_line_color = Noneshow(p) And here’s the plot: We could use a zillion of possible in-built methods to adjust the visual to our liking as well. Quite often we are not satisfied with a pre-set or a random palette, and we need to use some additional colormapping. That’s the situation when we use factor_cmap function imported from bokeh.transform module. Let’s look at the Canadian data for measles, polio and hiv/aids*1000 in 2000, 2005, 2010 and 2015 respectively. from bokeh.transform import factor_cmap#List of used statisticsstats = ['measles','polio','hiv/aids*1000']years = ['2000','2005','2010','2015']#Creating a dictionary of our datamdata = {'years' : years, 'measles' : data[data['country']=="Canada"][data['year'].isin(years)]['measles'], 'polio' : data[data['country']=="Canada"][data['year'].isin(years)]['polio'], 'hiv/aids*1000' : data[data['country']=="Canada"][data['year'].isin(years)]['hiv/aids']*1000}# Creating tuples for individual bars x = [ (year, stat) for year in years for stat in stats ]counts = sum(zip(mdata['measles'], mdata['polio'], mdata['hiv/aids*1000']), ())#Creating a column data source source = ColumnDataSource(data=dict(x=x, counts=counts, color=random.sample(Turbo256,12)))#Initializing our plot with random colorsp1 = figure(x_range=FactorRange(*x), plot_height=350, title="Health Stats in Canada 2000-2015")#Plotting our vertical bar chartp1.vbar(x='x', top='counts', width=0.9 ,fill_color='color', source=source)#Enhancing our graphp1.y_range.start = 0p1.x_range.range_padding = 0.1p1.xaxis.major_label_orientation = .9p1.xgrid.grid_line_color = None#Creating a new column data source without set colors source1 = ColumnDataSource(data=dict(x=x, counts=counts))#Initializing our plot with synchronized fill colors with factor_cmapp2 = figure(x_range=FactorRange(*x), plot_height=350, title="Health Stats in Canada 2000-2015, color mapped" )p2.vbar(x='x', top='counts', width=0.9, source=source1, fill_color=factor_cmap('x', palette=['salmon', 'green', 'navy'], factors=stats, start=1, end=2))p2.xaxis.major_label_orientation = .7p=gridplot([[p1,None],[p2,None]], toolbar_location='right')show(p) And here we are — the first chart has some random colors, the second one is color factored: Even though the first one looks funkier, the second one has a much more clear message when a color mapping statistics. Plotting a single label in Bokeh is quite straight-forward and doesn’t really require any specific technique. We just need to import the Label class from the bokeh.models.annotations module and its syntax is quite simple. One just needs to know that Bokeh uses a separate layer for plotting, another one for labeling, etc. We will use an add_layer() method in order to assemble our visual together. Let’s look at an example and create a graph of measles in Spain in 2000–2015. from bokeh.models.annotations import Label#Initializing our plotp = figure(x_range=(2000,2015), title='Measles in Spain 2000-2015')#Plotting a linep.line(data[data['country']=='Spain']['year'], data[data['country']=='Spain']['measles'], line_color='navy', line_width=3)#Plotting data points as cirlesp.circle(data[data['country']=='Spain']['year'], data[data['country']=='Spain']['measles'], radius=.2, fill_color='yellow', line_color='salmon')#Instance of Label class as our 2011 Measles Outbreak labellabel = Label(x=2011, y=max(data[data['country']=='Spain']['measles']), x_offset=10, text="2011 Outbreak", text_baseline="top")#Adding a layout with our label to the graphp.add_layout(label)#Styling the graphp.xaxis.axis_label = 'Year'p.yaxis.axis_label = 'Measles stats'p.xgrid.grid_line_dash = 'dashed'p.xgrid.grid_line_color ='gray'p.ygrid.grid_line_dash ='dotted'p.ygrid.grid_line_color = 'gray'p.background_fill_color='green'p.background_fill_alpha=.05show(p) Voila! Adding a single “custom” label is really quite simple. The beauty of Bokeh is that adding a whole set of labels is hardly a tad more difficult. Let’s look at the example of polio in India in 2000–2015 and try adding values to every datapoint. We will simply need to use an instance of ColumnDataSource class for that and import from the bokeh.models module the LabelSet class. from bokeh.models import LabelSet#Instance of ColumnDataSourcesource = ColumnDataSource(data=dict( x=data[data['country']=='India']['year'], y=data[data['country']=='India']['polio'], labels=data[data['country']=='India']['polio'].values))#Initializing our plotp = figure(x_range=(1999,2016), y_range=(50,90), title='Polio in India 2000-2015')#Plotting data points as vertical barsp.vbar(x = 'x', top = 'y', width = .8, fill_color='azure', fill_alpha = 1, line_color='navy', line_alpha=.25, line_width=2, line_dash='dotted', source=source)#Plotting a linep.line(x = 'x', y = 'y', line_color='red',line_width=4, line_alpha=.5, source=source)#Plotting data points as circlesp.circle(x='x',y='y', radius=.2, fill_color='yellow', line_color='red', line_width=2, source=source)#Instance of the LabelSet classlabels = LabelSet(x='x', #positions of labeled datapoints y='y', text='labels', #labels' text level='glyph', #labeling level x_offset=-10, y_offset=15, #move from datapoints source=source, render_mode='canvas', text_baseline='bottom' #relative position to datapoints )p.add_layout(labels)p.xaxis.axis_label = 'Year'p.yaxis.axis_label = 'Measles stats'p.xgrid.grid_line_dash = 'dashed'p.xgrid.grid_line_color ='gray'p.ygrid.grid_line_dash ='dotted'p.ygrid.grid_line_color = 'gray'p.background_fill_color='salmon'p.background_fill_alpha=.05show(p) And that’s it: There is quite a number of other interactive techniques that can really reshape your visualization and give your data-driven story a whole new dimension. Just to name a few — linking with panning, linking with brushing, hovering, etc. Some of them are illustrated in the corresponding project’s notebook on Github. Bokeh is truly an endless source of inspiration. I can not praise enough its simplicity, smooth learning curve and wonderful interactive visuals one can render just in a few lines of code!!
[ { "code": null, "e": 416, "s": 172, "text": "This article is the second part of my Bokeh love story. The full story (including Jupyter notebooks and all files) is on my Github. The first part of the story is described in the Medium article “Easy Data Visualization Techniques with Bokeh”." }, { "code": null, "e": 697, "s": 416, "text": "No way your data story is full without visualizations, and bar charts are arguably one of the most loved types of categorical data representation. There is a myriad of types, palettes and styles of this Lego-like graphs, and that’s why I decided to devote them a separate article." }, { "code": null, "e": 810, "s": 697, "text": "Let’s start with the simple vertical and horizontal bar charts. We will get to the more complex ones in a jiffy." }, { "code": null, "e": 1143, "s": 810, "text": "It is pretty straight-forward to draw bar charts with Bokeh. As usual, we need to specify a type of chart (or chose a glyph) and pass the data to the plotting function. Let’s create a vertical bar chart showing changes in measles occurrences in the US over the years 2000–2015 using the same UN world healthcare indicators database." }, { "code": null, "e": 1810, "s": 1143, "text": "# Creating a list of categoriesyears = data[data['country']=='United States of America']['year']#Creating the list of valuesvalues = data[data['country']=='United States of America']['measles']# Initializing the plotp = figure( plot_height=300, title=\"Measles in the USA 2000-2015\", tools=TOOLS)#Plottingp.vbar(years, #categories top = values, #bar heights width = .9, fill_alpha = .5, fill_color = 'salmon', line_alpha = .5, line_color='green', line_dash='dashed' )#Signing the axisp.xaxis.axis_label=\"Years\"p.yaxis.axis_label=\"Measles stats\"show(p)" }, { "code": null, "e": 1817, "s": 1810, "text": "Voila!" }, { "code": null, "e": 1973, "s": 1817, "text": "Absolutely in the same fashion, we could create horizontal bar charts. Let’s use reported polio rates for Argentina in 2000–2015 for illustration purposes." }, { "code": null, "e": 2473, "s": 1973, "text": "# Creating a list of categoriesyears = data[data['country']=='Argentina']['year']#Creating the list of valuesvalues = data[data['country']=='Argentina']['polio'].values# Initializing the plotp = figure( plot_height=300, title=\"Polio in the Argentina 2000-2015\")#Plottingp.hbar(years, left = 0, right = values, height = .9, fill_color = 'azure', line_color='green', line_alpha=.5 )p.xaxis.axis_label=\"Years\"p.yaxis.axis_label=\"Polio stats\"show(p)" }, { "code": null, "e": 2564, "s": 2473, "text": "The code is super-intuitive; we just have to remember we are working with horizontal bars." }, { "code": null, "e": 2674, "s": 2564, "text": "Our bar charts are rendered in a very simple manner, and they definitely can benefit from some added make-up." }, { "code": null, "e": 2831, "s": 2674, "text": "For a list of some available palettes please visit Bokeh palettes documentation. In order to use any of them with Bokeh we need to import them specifically." }, { "code": null, "e": 3024, "s": 2831, "text": "Let’s look at the measles data for a number of countries in 2015 — we’ll render two graphs with a pre-set palette and a randomly chosen colors, as well as we will use the *gridplot* technique." }, { "code": null, "e": 4471, "s": 3024, "text": "#Importing a pallettefrom bokeh.palettes import Spectral5, Viridis256, Colorblind, Magma256, Turbo256# Creating a list of categorical values values = data[(data['year']==2015)&(data['country'].isin(countries))]['measles']# Set the x_range to the list of categories abovep1 = figure(x_range=countries, plot_height=250, title=\"Measles in the world in 2015 (pre-set pallette)\")# Categorical values can also be used as coordinatesp1.vbar(x=countries, top=values, width=0.9, color = Spectral5, fill_alpha=.75)# Set some properties to make the plot look betterp1.yaxis.axis_label=\"Measles stats\"p1.xgrid.grid_line_color='gray'p1.xgrid.grid_line_alpha=.75p1.xgrid.grid_line_dash = 'dashed'p1.ygrid.grid_line_color='blue'p1.ygrid.grid_line_alpha = .55p1.ygrid.grid_line_dash = 'dotted'p2 = figure(x_range=countries, plot_height=250, title=\"Measles in the world in 2015 (randomly selected colors from a pallette)\")# Categorical values can also be used as coordinatesp2.vbar(x=countries, top=values, width=0.9, color = random.sample(Viridis256,5), fill_alpha=.75)# Set some properties to make the plot look betterp2.yaxis.axis_label=\"Measles stats\"p2.xgrid.grid_line_color='gray'p2.xgrid.grid_line_alpha=.75p2.xgrid.grid_line_dash = 'dashed'p2.ygrid.grid_line_color='blue'p2.ygrid.grid_line_alpha = .55p2.ygrid.grid_line_dash = 'dotted'p = gridplot([[p1,None],[p2,None]], toolbar_location='right')show(p)" }, { "code": null, "e": 4494, "s": 4471, "text": "And here’s the result:" }, { "code": null, "e": 4617, "s": 4494, "text": "This plot looks much friendlier then the ones we started with. And there’s no end to experiments with colors and palettes." }, { "code": null, "e": 4930, "s": 4617, "text": "Sometimes we need to plot a grouped bar chart. For example, we might need to group our health indicators for some countries. For that, we need to import a special procedure from the bokeh.models module — FactorRange. Let’s look at the data for measles, polio and hiv/aids*1000 for our list of countries for 2014." }, { "code": null, "e": 6220, "s": 4930, "text": "from bokeh.models import FactorRange#List of used statisticsstats = ['measles','polio','hiv/aids*1000']#Creating a dictionary of our datamdata = {'countries' : countries, 'measles' : data[data['year']==2014][data['country'].isin(countries)]['measles'], 'polio' : data[data['year']==2014][data['country'].isin(countries)]['polio'], 'hiv/aids*1000' : data[data['year']==2014][data['country'].isin(countries)]['hiv/aids']*1000}# Creating tuples for individual bars [ (\"France\", \"measles\"), (\"France\", \"polio\"), (\"France\", \"hiv/aids*1000\"), (\"Canada\", \"measles\"), ... ]x = [ (country, stat) for country in countries for stat in stats ]counts = sum(zip(mdata['measles'], mdata['polio'], mdata['hiv/aids*1000']), ())#Creating a column data source - Bokeh's own data type with the fields (Country,[stats],[values],[colors]) source = ColumnDataSource(data=dict(x=x, counts=counts, color=random.sample(Turbo256,15)))#Initializing our plotp = figure(x_range=FactorRange(*x), plot_height=350, title=\"Health Stats by Country\")#Plotting our vertical bar chartp.vbar(x='x', top='counts', width=0.9 ,fill_color='color', source=source)#Enhancing our graphp.y_range.start = 0p.x_range.range_padding = 0.1p.xaxis.major_label_orientation = .9p.xgrid.grid_line_color = Noneshow(p)" }, { "code": null, "e": 6241, "s": 6220, "text": "And here’s the plot:" }, { "code": null, "e": 6337, "s": 6241, "text": "We could use a zillion of possible in-built methods to adjust the visual to our liking as well." }, { "code": null, "e": 6659, "s": 6337, "text": "Quite often we are not satisfied with a pre-set or a random palette, and we need to use some additional colormapping. That’s the situation when we use factor_cmap function imported from bokeh.transform module. Let’s look at the Canadian data for measles, polio and hiv/aids*1000 in 2000, 2005, 2010 and 2015 respectively." }, { "code": null, "e": 8401, "s": 6659, "text": "from bokeh.transform import factor_cmap#List of used statisticsstats = ['measles','polio','hiv/aids*1000']years = ['2000','2005','2010','2015']#Creating a dictionary of our datamdata = {'years' : years, 'measles' : data[data['country']==\"Canada\"][data['year'].isin(years)]['measles'], 'polio' : data[data['country']==\"Canada\"][data['year'].isin(years)]['polio'], 'hiv/aids*1000' : data[data['country']==\"Canada\"][data['year'].isin(years)]['hiv/aids']*1000}# Creating tuples for individual bars x = [ (year, stat) for year in years for stat in stats ]counts = sum(zip(mdata['measles'], mdata['polio'], mdata['hiv/aids*1000']), ())#Creating a column data source source = ColumnDataSource(data=dict(x=x, counts=counts, color=random.sample(Turbo256,12)))#Initializing our plot with random colorsp1 = figure(x_range=FactorRange(*x), plot_height=350, title=\"Health Stats in Canada 2000-2015\")#Plotting our vertical bar chartp1.vbar(x='x', top='counts', width=0.9 ,fill_color='color', source=source)#Enhancing our graphp1.y_range.start = 0p1.x_range.range_padding = 0.1p1.xaxis.major_label_orientation = .9p1.xgrid.grid_line_color = None#Creating a new column data source without set colors source1 = ColumnDataSource(data=dict(x=x, counts=counts))#Initializing our plot with synchronized fill colors with factor_cmapp2 = figure(x_range=FactorRange(*x), plot_height=350, title=\"Health Stats in Canada 2000-2015, color mapped\" )p2.vbar(x='x', top='counts', width=0.9, source=source1, fill_color=factor_cmap('x', palette=['salmon', 'green', 'navy'], factors=stats, start=1, end=2))p2.xaxis.major_label_orientation = .7p=gridplot([[p1,None],[p2,None]], toolbar_location='right')show(p)" }, { "code": null, "e": 8493, "s": 8401, "text": "And here we are — the first chart has some random colors, the second one is color factored:" }, { "code": null, "e": 8612, "s": 8493, "text": "Even though the first one looks funkier, the second one has a much more clear message when a color mapping statistics." }, { "code": null, "e": 9089, "s": 8612, "text": "Plotting a single label in Bokeh is quite straight-forward and doesn’t really require any specific technique. We just need to import the Label class from the bokeh.models.annotations module and its syntax is quite simple. One just needs to know that Bokeh uses a separate layer for plotting, another one for labeling, etc. We will use an add_layer() method in order to assemble our visual together. Let’s look at an example and create a graph of measles in Spain in 2000–2015." }, { "code": null, "e": 10153, "s": 9089, "text": "from bokeh.models.annotations import Label#Initializing our plotp = figure(x_range=(2000,2015), title='Measles in Spain 2000-2015')#Plotting a linep.line(data[data['country']=='Spain']['year'], data[data['country']=='Spain']['measles'], line_color='navy', line_width=3)#Plotting data points as cirlesp.circle(data[data['country']=='Spain']['year'], data[data['country']=='Spain']['measles'], radius=.2, fill_color='yellow', line_color='salmon')#Instance of Label class as our 2011 Measles Outbreak labellabel = Label(x=2011, y=max(data[data['country']=='Spain']['measles']), x_offset=10, text=\"2011 Outbreak\", text_baseline=\"top\")#Adding a layout with our label to the graphp.add_layout(label)#Styling the graphp.xaxis.axis_label = 'Year'p.yaxis.axis_label = 'Measles stats'p.xgrid.grid_line_dash = 'dashed'p.xgrid.grid_line_color ='gray'p.ygrid.grid_line_dash ='dotted'p.ygrid.grid_line_color = 'gray'p.background_fill_color='green'p.background_fill_alpha=.05show(p)" }, { "code": null, "e": 10160, "s": 10153, "text": "Voila!" }, { "code": null, "e": 10537, "s": 10160, "text": "Adding a single “custom” label is really quite simple. The beauty of Bokeh is that adding a whole set of labels is hardly a tad more difficult. Let’s look at the example of polio in India in 2000–2015 and try adding values to every datapoint. We will simply need to use an instance of ColumnDataSource class for that and import from the bokeh.models module the LabelSet class." }, { "code": null, "e": 12173, "s": 10537, "text": "from bokeh.models import LabelSet#Instance of ColumnDataSourcesource = ColumnDataSource(data=dict( x=data[data['country']=='India']['year'], y=data[data['country']=='India']['polio'], labels=data[data['country']=='India']['polio'].values))#Initializing our plotp = figure(x_range=(1999,2016), y_range=(50,90), title='Polio in India 2000-2015')#Plotting data points as vertical barsp.vbar(x = 'x', top = 'y', width = .8, fill_color='azure', fill_alpha = 1, line_color='navy', line_alpha=.25, line_width=2, line_dash='dotted', source=source)#Plotting a linep.line(x = 'x', y = 'y', line_color='red',line_width=4, line_alpha=.5, source=source)#Plotting data points as circlesp.circle(x='x',y='y', radius=.2, fill_color='yellow', line_color='red', line_width=2, source=source)#Instance of the LabelSet classlabels = LabelSet(x='x', #positions of labeled datapoints y='y', text='labels', #labels' text level='glyph', #labeling level x_offset=-10, y_offset=15, #move from datapoints source=source, render_mode='canvas', text_baseline='bottom' #relative position to datapoints )p.add_layout(labels)p.xaxis.axis_label = 'Year'p.yaxis.axis_label = 'Measles stats'p.xgrid.grid_line_dash = 'dashed'p.xgrid.grid_line_color ='gray'p.ygrid.grid_line_dash ='dotted'p.ygrid.grid_line_color = 'gray'p.background_fill_color='salmon'p.background_fill_alpha=.05show(p)" }, { "code": null, "e": 12188, "s": 12173, "text": "And that’s it:" }, { "code": null, "e": 12503, "s": 12188, "text": "There is quite a number of other interactive techniques that can really reshape your visualization and give your data-driven story a whole new dimension. Just to name a few — linking with panning, linking with brushing, hovering, etc. Some of them are illustrated in the corresponding project’s notebook on Github." } ]
C# program to convert floating to binary
Let’s say the following is our float − float n = 50.5f; Take an empty string to display the binary value and loop until the value of our float variable is greater than 1 − string a = ""; while (n >= 1) { a = (n % 2) + a; n = n / 2; } Let us see the complete example − Live Demo using System; using System.IO; using System.CodeDom.Compiler; namespace Program { class Demo { static void Main(string[] args) { // float to binary Console.WriteLine("float to binary = "); float n = 50.5f; string a = ""; while (n >= 1) { a = (n % 2) + a; n = n / 2; } Console.Write(a); } } } float to binary = 1.5781251.156250.31250.6251.250.5
[ { "code": null, "e": 1101, "s": 1062, "text": "Let’s say the following is our float −" }, { "code": null, "e": 1118, "s": 1101, "text": "float n = 50.5f;" }, { "code": null, "e": 1234, "s": 1118, "text": "Take an empty string to display the binary value and loop until the value of our float variable is greater than 1 −" }, { "code": null, "e": 1303, "s": 1234, "text": "string a = \"\";\n\nwhile (n >= 1) {\n a = (n % 2) + a;\n n = n / 2;\n}" }, { "code": null, "e": 1337, "s": 1303, "text": "Let us see the complete example −" }, { "code": null, "e": 1348, "s": 1337, "text": " Live Demo" }, { "code": null, "e": 1748, "s": 1348, "text": "using System;\nusing System.IO;\nusing System.CodeDom.Compiler;\n\nnamespace Program {\n class Demo {\n static void Main(string[] args) {\n\n // float to binary\n Console.WriteLine(\"float to binary = \");\n float n = 50.5f;\n string a = \"\";\n\n while (n >= 1) {\n a = (n % 2) + a;\n n = n / 2;\n }\n Console.Write(a);\n }\n }\n}" }, { "code": null, "e": 1800, "s": 1748, "text": "float to binary =\n1.5781251.156250.31250.6251.250.5" } ]
Hibernate Composite Key Mapping Example - 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 the context of relational databases, a composite key is a combination of two or more columns in a table that can be used to make the uniqueness of a table row. In this tutorials, we are going to implement how to define a hibernate composite key, and how to map the database composite primary keys in a hibernate mapping. Here is the example for Hibernate composite key: Lets create a database table with composite primary key. CREATE TABLE `student` ( `studentid` int(11) NOT NULL AUTO_INCREMENT, `courceid` int(11) NOT NULL, `studentname` varchar(50) DEFAULT NULL, `studentAddress` varchar(50) DEFAULT NULL, PRIMARY KEY (`studentid`,`courceid`) ) ENGINE=InnoDB AUTO_INCREMENT=1 Project Structure : Required Dependencies : <dependencies> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.0.Final</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</version> </dependency> </dependencies> HibernateUtility : HibernateUitl.java package com.onlinetutorialspoint.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private HibernateUtil() { } private static SessionFactory sessionFactory; public static synchronized SessionFactory getInstnce() { if (sessionFactory == null) { Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); sessionFactory = configuration.buildSessionFactory(builder.build()); } return sessionFactory; } } Hibernate POJO: Student.java package com.onlinetutorialspoint.beans; import java.io.Serializable; public class Student implements Serializable { private static final long serialVersionUID = 1 L; private int studentId; private String studentName; private String studentAddress; private int courceId; public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentAddress() { return studentAddress; } public void setStudentAddress(String studentAddress) { this.studentAddress = studentAddress; } public int getCourceId() { return courceId; } public void setCourceId(int courceId) { this.courceId = courceId; } } Hibernate Mapping File : student.hbm.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.onlinetutorialspoint.beans.Student" table="student"> <composite-id> <key-property name="studentId" column="studentid" /> <key-property name="courceId" column="courceid" /> </composite-id> <property name="studentName" /> <property name="studentAddress" /> </class> </hibernate-mapping> Lets Run the Application : Main.java import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.onlinetutorialspoint.beans.Student; import com.onlinetutorialspoint.util.HibernateUtil; public class Main { public static void main(String args[]) { SessionFactory sessionFactory = HibernateUtil.getInstnce(); Session session = sessionFactory.openSession(); Student student = new Student(); student.setStudentId(103); student.setStudentAddress("Hyderabad"); student.setStudentName("Johny"); student.setCourceId(201); Transaction tx = session.beginTransaction(); session.save(student); tx.commit(); session.close(); } } Hibernate: insert into student (studentName, studentAddress, studentid, courceid) values (?, ?, ?, ?) Happy Learning 🙂 Hibernate-Composite Key-Example File size: 17 KB Downloads: 943 Hibernate One to One Mapping using primary key (XML) One to One Mapping in Hibernate using foreign key (XML) Hibernate Filter Example Xml Configuration hbm2ddl.auto Example in Hibernate XML Config Hibernate Native SQL Query Example Many to One Mapping in Hibernate Example Hibernate Many to Many Mapping Example (XML) Hibernate One To Many Example (XML Mapping) hibernate update query example How to convert Java Object to JSON Hibernate session differences between load() and get() Generator Classes in Hibernate Calling Stored Procedures in Hibernate HQL update, delete Query Example Basic Hibernate Example with XML Configuration Hibernate One to One Mapping using primary key (XML) One to One Mapping in Hibernate using foreign key (XML) Hibernate Filter Example Xml Configuration hbm2ddl.auto Example in Hibernate XML Config Hibernate Native SQL Query Example Many to One Mapping in Hibernate Example Hibernate Many to Many Mapping Example (XML) Hibernate One To Many Example (XML Mapping) hibernate update query example How to convert Java Object to JSON Hibernate session differences between load() and get() Generator Classes in Hibernate Calling Stored Procedures in Hibernate HQL update, delete Query Example Basic Hibernate Example with XML Configuration Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "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": 771, "s": 398, "text": "In the context of relational databases, a composite key is a combination of two or more columns in a table that can be used to make the uniqueness of a table row. In this tutorials, we are going to implement how to define a hibernate composite key, and how to map the database composite primary keys in a hibernate mapping. Here is the example for Hibernate composite key:" }, { "code": null, "e": 828, "s": 771, "text": "Lets create a database table with composite primary key." }, { "code": null, "e": 1080, "s": 828, "text": "CREATE TABLE `student` (\n`studentid` int(11) NOT NULL AUTO_INCREMENT,\n`courceid` int(11) NOT NULL,\n`studentname` varchar(50) DEFAULT NULL,\n`studentAddress` varchar(50) DEFAULT NULL,\nPRIMARY KEY (`studentid`,`courceid`)\n) ENGINE=InnoDB AUTO_INCREMENT=1" }, { "code": null, "e": 1101, "s": 1080, "text": "Project Structure : " }, { "code": null, "e": 1126, "s": 1101, "text": " Required Dependencies :" }, { "code": null, "e": 1514, "s": 1126, "text": "<dependencies>\n <!-- Hibernate -->\n <dependency>\n <groupId>org.hibernate</groupId>\n <artifactId>hibernate-core</artifactId>\n <version>4.3.0.Final</version>\n </dependency>\n <!-- MySQL Driver -->\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <version>5.0.5</version>\n </dependency>\n</dependencies>" }, { "code": null, "e": 1552, "s": 1514, "text": "HibernateUtility : HibernateUitl.java" }, { "code": null, "e": 2369, "s": 1552, "text": "package com.onlinetutorialspoint.util;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.boot.registry.StandardServiceRegistryBuilder;\nimport org.hibernate.cfg.Configuration;\npublic class HibernateUtil { \n private HibernateUtil() { \n } \n private static SessionFactory sessionFactory; \n public static synchronized SessionFactory getInstnce() { \n if (sessionFactory == null) { \n Configuration configuration = new Configuration().configure(\"hibernate.cfg.xml\"); \n StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); \n sessionFactory = configuration.buildSessionFactory(builder.build()); \n } \n return sessionFactory; \n }\n}" }, { "code": null, "e": 2398, "s": 2369, "text": "Hibernate POJO: Student.java" }, { "code": null, "e": 3457, "s": 2398, "text": "package com.onlinetutorialspoint.beans;\nimport java.io.Serializable;\npublic class Student implements Serializable { \n private static final long serialVersionUID = 1 L; \n private int studentId; \n private String studentName; \n private String studentAddress; \n private int courceId; \n public int getStudentId() { \n return studentId; \n } \n public void setStudentId(int studentId) { \n this.studentId = studentId; \n } \n public String getStudentName() { \n return studentName; \n } \n public void setStudentName(String studentName) { \n this.studentName = studentName; \n } \n public String getStudentAddress() { \n return studentAddress; \n } \n public void setStudentAddress(String studentAddress) { \n this.studentAddress = studentAddress; \n } \n public int getCourceId() { \n return courceId; \n } \n public void setCourceId(int courceId) { \n this.courceId = courceId; \n }\n}" }, { "code": null, "e": 3500, "s": 3459, "text": "Hibernate Mapping File : student.hbm.xml" }, { "code": null, "e": 4040, "s": 3500, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC\n \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n<hibernate-mapping>\n <class name=\"com.onlinetutorialspoint.beans.Student\" table=\"student\">\n <composite-id>\n <key-property name=\"studentId\" column=\"studentid\" />\n <key-property name=\"courceId\" column=\"courceid\" />\n </composite-id>\n <property name=\"studentName\" />\n <property name=\"studentAddress\" />\n </class>\n</hibernate-mapping>\n" }, { "code": null, "e": 4077, "s": 4040, "text": "Lets Run the Application : Main.java" }, { "code": null, "e": 4875, "s": 4077, "text": "import org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\nimport com.onlinetutorialspoint.beans.Student;\nimport com.onlinetutorialspoint.util.HibernateUtil;\npublic class Main { \n public static void main(String args[]) { \n SessionFactory sessionFactory = HibernateUtil.getInstnce(); \n Session session = sessionFactory.openSession(); \n Student student = new Student(); \n student.setStudentId(103); \n student.setStudentAddress(\"Hyderabad\"); \n student.setStudentName(\"Johny\"); \n student.setCourceId(201); \n Transaction tx = session.beginTransaction(); \n session.save(student); \n tx.commit(); \n session.close(); \n }\n}" }, { "code": null, "e": 4977, "s": 4875, "text": "Hibernate: insert into student (studentName, studentAddress, studentid, courceid) values (?, ?, ?, ?)" }, { "code": null, "e": 4995, "s": 4977, "text": " Happy Learning 🙂" }, { "code": null, "e": 5063, "s": 4995, "text": "\n\nHibernate-Composite Key-Example\n\nFile size: 17 KB\nDownloads: 943\n" }, { "code": null, "e": 5698, "s": 5063, "text": "\nHibernate One to One Mapping using primary key (XML)\nOne to One Mapping in Hibernate using foreign key (XML)\nHibernate Filter Example Xml Configuration\nhbm2ddl.auto Example in Hibernate XML Config\nHibernate Native SQL Query Example\nMany to One Mapping in Hibernate Example\nHibernate Many to Many Mapping Example (XML)\nHibernate One To Many Example (XML Mapping)\nhibernate update query example\nHow to convert Java Object to JSON\nHibernate session differences between load() and get()\nGenerator Classes in Hibernate\nCalling Stored Procedures in Hibernate\nHQL update, delete Query Example\nBasic Hibernate Example with XML Configuration\n" }, { "code": null, "e": 5751, "s": 5698, "text": "Hibernate One to One Mapping using primary key (XML)" }, { "code": null, "e": 5807, "s": 5751, "text": "One to One Mapping in Hibernate using foreign key (XML)" }, { "code": null, "e": 5850, "s": 5807, "text": "Hibernate Filter Example Xml Configuration" }, { "code": null, "e": 5895, "s": 5850, "text": "hbm2ddl.auto Example in Hibernate XML Config" }, { "code": null, "e": 5930, "s": 5895, "text": "Hibernate Native SQL Query Example" }, { "code": null, "e": 5971, "s": 5930, "text": "Many to One Mapping in Hibernate Example" }, { "code": null, "e": 6016, "s": 5971, "text": "Hibernate Many to Many Mapping Example (XML)" }, { "code": null, "e": 6060, "s": 6016, "text": "Hibernate One To Many Example (XML Mapping)" }, { "code": null, "e": 6091, "s": 6060, "text": "hibernate update query example" }, { "code": null, "e": 6126, "s": 6091, "text": "How to convert Java Object to JSON" }, { "code": null, "e": 6181, "s": 6126, "text": "Hibernate session differences between load() and get()" }, { "code": null, "e": 6212, "s": 6181, "text": "Generator Classes in Hibernate" }, { "code": null, "e": 6251, "s": 6212, "text": "Calling Stored Procedures in Hibernate" }, { "code": null, "e": 6284, "s": 6251, "text": "HQL update, delete Query Example" }, { "code": null, "e": 6331, "s": 6284, "text": "Basic Hibernate Example with XML Configuration" }, { "code": null, "e": 6337, "s": 6335, "text": "Δ" }, { "code": null, "e": 6363, "s": 6337, "text": " Hibernate – Introduction" }, { "code": null, "e": 6387, "s": 6363, "text": " Hibernate – Advantages" }, { "code": null, "e": 6419, "s": 6387, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 6449, "s": 6419, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 6479, "s": 6449, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 6517, "s": 6479, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 6544, "s": 6517, "text": " Hibernate – Object States" }, { "code": null, "e": 6582, "s": 6544, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 6620, "s": 6582, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 6670, "s": 6620, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 6700, "s": 6670, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 6739, "s": 6700, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 6779, "s": 6739, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 6810, "s": 6779, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 6845, "s": 6810, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 6870, "s": 6845, "text": " Hibernate – Named Query" }, { "code": null, "e": 6900, "s": 6870, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 6929, "s": 6900, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 6966, "s": 6929, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 6992, "s": 6966, "text": " Hibernate – Restrictions" }, { "code": null, "e": 7016, "s": 6992, "text": " Hibernate – Projection" }, { "code": null, "e": 7050, "s": 7016, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 7084, "s": 7050, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 7114, "s": 7084, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 7147, "s": 7114, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 7179, "s": 7147, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 7205, "s": 7179, "text": " Hibernate – Update Query" }, { "code": null, "e": 7234, "s": 7205, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 7258, "s": 7234, "text": " Hibernate – Right Join" }, { "code": null, "e": 7281, "s": 7258, "text": " Hibernate – Left Join" }, { "code": null, "e": 7305, "s": 7281, "text": " Hibernate – Pagination" }, { "code": null, "e": 7336, "s": 7305, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 7366, "s": 7336, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 7400, "s": 7366, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 7429, "s": 7400, "text": " Hibernate – Table per Class" }, { "code": null, "e": 7462, "s": 7429, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 7500, "s": 7462, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 7542, "s": 7500, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 7573, "s": 7542, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 7606, "s": 7573, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 7644, "s": 7606, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 7669, "s": 7644, "text": " Hibernate – Interceptor" }, { "code": null, "e": 7715, "s": 7669, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
passwd command in Linux with Examples - GeeksforGeeks
24 May, 2019 passwd command in Linux is used to change the user account passwords. The root user reserves the privilege to change the password for any user on the system, while a normal user can only change the account password for his or her own account. Syntax: passwd [options] [username] Example: Command: passwd Command [root]: passwd user1 Note: sudo can be used to invoke root privileges by normal users, and can change the password for root itself. This is particularly helpful when a user is member of admin group (holds a position in sudoers list (/etc/sudoers) and can use commands with sudo) and the root password is not set, which is case with many common distributions of linux. Command: sudo passwd root Processing in passwd command: Verify current user password : Once the user enters passwd command, it prompts for current user password, which is verified against the password stored in /etc/shadow file user. The root user can bypass this step and can directly change the password, so as the forgotten passwords may be recovered.Verify password aging information : In Linux, a user password can be set to expire after a given period of time. Also, a user can be prohibited to change his/her password for a period. This password aging information (and the password itself) is stored in a file /etc/shadow.Change the password : After authentication, the user is prompted to enter the new password and verify it by retyping the password./etc/shadow file: The shadow file is a list of colon separated values with 9 fields, as shown below:user1:$6$x8wAJRpP$EWC97sXW5tqac10Q2TQyXkR.1l1jdK4VLK1pkZKmA2mbA6UnSGyo94Pis074viWBA3sVbkCptSZzuP2K.y.an/:17887:0:99999:7:::field 1: User name.field 2: Encrypted Password.field 3: Number of days since January 1, 1970 to when the password was last changed.field 4: Minimum number of days for which password can not be changed. (value 0 means it can be changed anytime).field 5: Number of days after password must be changed. (value 99999 means that the password never expires).field 6: Number of days to warn user for expiring password.field 7: Number of days after password expires that the account is disabled.field 8: The number of days from January 1, 1970 to the date when an account was disabled.field 9: This field is reserved for some possible future use.passwd options:-d, –delete: This option deletes the user password and makes the account password-less.-e, –expire: This option immediately expires the account password and forces the user to change password on their next login.-h, –help: Display help related to the passwd command.-i, –inactive INACTIVE_DAYS: This option is followed by an integer, INACTIVE_DAYS, which is the number of days after the password expires that the account will be deactivated.example: passwd -i 3 user1 -k, –keep-tokens: This option is used when you only want to change the password if it is expired. It keeps the authentication tokens for the authentication if the password is not yet expired, even if you requested to change it. Note that if the expiry period for a user is set to 99999, then this option will not keep tokens and the password will be changed.-l, –lock: Lock the password of user. This appends the encrypted password of the user with a character ‘!’, and thus making it unable to match with any of input password combinations. This does not disable the account but prevents the user from logging in using a password. Though other authentication methods like ssh keys can be used to login to the account.-n, –mindays MIN_DAYS: Change the minimum number of days between password changes to MIN_DAYS so that the user can’t change the password for MIN_DAYS.-q, –quiet: This option is used for quiet mode. While using this option to change a password, the message “Changing password for $user.”, which usually gets printed before changing a password, does not get echoed.-r, –repository REPO: This option is used to change password for repository named “REPO”.-R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory. This basically changes the root directory for the passwd process for once, and since CHROOT_DIR is a sub-directory of the root, it can not access the configuration files outside the CHROOT_DIR.-S, –status: Shows the password status (7 fields) of user in the following format:user1 P 12/22/2018 0 99999 7 3The first field is the user’s login name. The second field indicates if the user account has a locked password (L), has no Password (NP), or has a usable password (P). The third field gives the date of the last password change. The next four fields are the minimum age, maximum age, warning period, and inactivity period for the password. These ages are expressed in days.-S [, –status] -a [, –all]: This combination of options shows password status for all users. Note that -a or –all cannot be used without -S option.-u, –unlock: Unlock the password of an account.-w, –warndays WARN_DAYS: This option is used to change the number of days before the password is to expire, to display the warning for expiring password.-x, –maxdays MAX_DAYS Set the maximum number of days for which the password remains valid. After MAX_DAYS, the password will expire and the user will be forced to change password.My Personal Notes arrow_drop_upSave Verify current user password : Once the user enters passwd command, it prompts for current user password, which is verified against the password stored in /etc/shadow file user. The root user can bypass this step and can directly change the password, so as the forgotten passwords may be recovered. Verify password aging information : In Linux, a user password can be set to expire after a given period of time. Also, a user can be prohibited to change his/her password for a period. This password aging information (and the password itself) is stored in a file /etc/shadow. Change the password : After authentication, the user is prompted to enter the new password and verify it by retyping the password./etc/shadow file: The shadow file is a list of colon separated values with 9 fields, as shown below:user1:$6$x8wAJRpP$EWC97sXW5tqac10Q2TQyXkR.1l1jdK4VLK1pkZKmA2mbA6UnSGyo94Pis074viWBA3sVbkCptSZzuP2K.y.an/:17887:0:99999:7:::field 1: User name.field 2: Encrypted Password.field 3: Number of days since January 1, 1970 to when the password was last changed.field 4: Minimum number of days for which password can not be changed. (value 0 means it can be changed anytime).field 5: Number of days after password must be changed. (value 99999 means that the password never expires).field 6: Number of days to warn user for expiring password.field 7: Number of days after password expires that the account is disabled.field 8: The number of days from January 1, 1970 to the date when an account was disabled.field 9: This field is reserved for some possible future use.passwd options:-d, –delete: This option deletes the user password and makes the account password-less.-e, –expire: This option immediately expires the account password and forces the user to change password on their next login.-h, –help: Display help related to the passwd command.-i, –inactive INACTIVE_DAYS: This option is followed by an integer, INACTIVE_DAYS, which is the number of days after the password expires that the account will be deactivated.example: passwd -i 3 user1 -k, –keep-tokens: This option is used when you only want to change the password if it is expired. It keeps the authentication tokens for the authentication if the password is not yet expired, even if you requested to change it. Note that if the expiry period for a user is set to 99999, then this option will not keep tokens and the password will be changed.-l, –lock: Lock the password of user. This appends the encrypted password of the user with a character ‘!’, and thus making it unable to match with any of input password combinations. This does not disable the account but prevents the user from logging in using a password. Though other authentication methods like ssh keys can be used to login to the account.-n, –mindays MIN_DAYS: Change the minimum number of days between password changes to MIN_DAYS so that the user can’t change the password for MIN_DAYS.-q, –quiet: This option is used for quiet mode. While using this option to change a password, the message “Changing password for $user.”, which usually gets printed before changing a password, does not get echoed.-r, –repository REPO: This option is used to change password for repository named “REPO”.-R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory. This basically changes the root directory for the passwd process for once, and since CHROOT_DIR is a sub-directory of the root, it can not access the configuration files outside the CHROOT_DIR.-S, –status: Shows the password status (7 fields) of user in the following format:user1 P 12/22/2018 0 99999 7 3The first field is the user’s login name. The second field indicates if the user account has a locked password (L), has no Password (NP), or has a usable password (P). The third field gives the date of the last password change. The next four fields are the minimum age, maximum age, warning period, and inactivity period for the password. These ages are expressed in days.-S [, –status] -a [, –all]: This combination of options shows password status for all users. Note that -a or –all cannot be used without -S option.-u, –unlock: Unlock the password of an account.-w, –warndays WARN_DAYS: This option is used to change the number of days before the password is to expire, to display the warning for expiring password.-x, –maxdays MAX_DAYS Set the maximum number of days for which the password remains valid. After MAX_DAYS, the password will expire and the user will be forced to change password.My Personal Notes arrow_drop_upSave /etc/shadow file: The shadow file is a list of colon separated values with 9 fields, as shown below: user1:$6$x8wAJRpP$EWC97sXW5tqac10Q2TQyXkR.1l1jdK4VLK1pkZKmA2mbA6UnSGyo94Pis074viWBA3sVbkCptSZzuP2K.y.an/:17887:0:99999:7::: field 1: User name. field 2: Encrypted Password. field 3: Number of days since January 1, 1970 to when the password was last changed. field 4: Minimum number of days for which password can not be changed. (value 0 means it can be changed anytime). field 5: Number of days after password must be changed. (value 99999 means that the password never expires). field 6: Number of days to warn user for expiring password. field 7: Number of days after password expires that the account is disabled. field 8: The number of days from January 1, 1970 to the date when an account was disabled. field 9: This field is reserved for some possible future use. passwd options: -d, –delete: This option deletes the user password and makes the account password-less. -e, –expire: This option immediately expires the account password and forces the user to change password on their next login. -h, –help: Display help related to the passwd command. -i, –inactive INACTIVE_DAYS: This option is followed by an integer, INACTIVE_DAYS, which is the number of days after the password expires that the account will be deactivated.example: passwd -i 3 user1 example: passwd -i 3 user1 -k, –keep-tokens: This option is used when you only want to change the password if it is expired. It keeps the authentication tokens for the authentication if the password is not yet expired, even if you requested to change it. Note that if the expiry period for a user is set to 99999, then this option will not keep tokens and the password will be changed. -l, –lock: Lock the password of user. This appends the encrypted password of the user with a character ‘!’, and thus making it unable to match with any of input password combinations. This does not disable the account but prevents the user from logging in using a password. Though other authentication methods like ssh keys can be used to login to the account. -n, –mindays MIN_DAYS: Change the minimum number of days between password changes to MIN_DAYS so that the user can’t change the password for MIN_DAYS. -q, –quiet: This option is used for quiet mode. While using this option to change a password, the message “Changing password for $user.”, which usually gets printed before changing a password, does not get echoed. -r, –repository REPO: This option is used to change password for repository named “REPO”. -R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory. This basically changes the root directory for the passwd process for once, and since CHROOT_DIR is a sub-directory of the root, it can not access the configuration files outside the CHROOT_DIR. -S, –status: Shows the password status (7 fields) of user in the following format:user1 P 12/22/2018 0 99999 7 3The first field is the user’s login name. The second field indicates if the user account has a locked password (L), has no Password (NP), or has a usable password (P). The third field gives the date of the last password change. The next four fields are the minimum age, maximum age, warning period, and inactivity period for the password. These ages are expressed in days.-S [, –status] -a [, –all]: This combination of options shows password status for all users. Note that -a or –all cannot be used without -S option. user1 P 12/22/2018 0 99999 7 3 The first field is the user’s login name. The second field indicates if the user account has a locked password (L), has no Password (NP), or has a usable password (P). The third field gives the date of the last password change. The next four fields are the minimum age, maximum age, warning period, and inactivity period for the password. These ages are expressed in days. -S [, –status] -a [, –all]: This combination of options shows password status for all users. Note that -a or –all cannot be used without -S option. -u, –unlock: Unlock the password of an account. -w, –warndays WARN_DAYS: This option is used to change the number of days before the password is to expire, to display the warning for expiring password. -x, –maxdays MAX_DAYS Set the maximum number of days for which the password remains valid. After MAX_DAYS, the password will expire and the user will be forced to change password. linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples SORT command in Linux/Unix with examples curl command in Linux with Examples UDP Server-Client implementation in C 'crontab' in Linux with Examples Conditional Statements | Shell Script diff command in Linux with examples tee command in Linux with examples
[ { "code": null, "e": 24616, "s": 24588, "text": "\n24 May, 2019" }, { "code": null, "e": 24859, "s": 24616, "text": "passwd command in Linux is used to change the user account passwords. The root user reserves the privilege to change the password for any user on the system, while a normal user can only change the account password for his or her own account." }, { "code": null, "e": 24867, "s": 24859, "text": "Syntax:" }, { "code": null, "e": 24897, "s": 24867, "text": " passwd [options] [username] " }, { "code": null, "e": 24906, "s": 24897, "text": "Example:" }, { "code": null, "e": 24923, "s": 24906, "text": "Command: passwd " }, { "code": null, "e": 24953, "s": 24923, "text": "Command [root]: passwd user1 " }, { "code": null, "e": 25300, "s": 24953, "text": "Note: sudo can be used to invoke root privileges by normal users, and can change the password for root itself. This is particularly helpful when a user is member of admin group (holds a position in sudoers list (/etc/sudoers) and can use commands with sudo) and the root password is not set, which is case with many common distributions of linux." }, { "code": null, "e": 25327, "s": 25300, "text": "Command: sudo passwd root " }, { "code": null, "e": 25357, "s": 25327, "text": "Processing in passwd command:" }, { "code": null, "e": 29940, "s": 25357, "text": "Verify current user password : Once the user enters passwd command, it prompts for current user password, which is verified against the password stored in /etc/shadow file user. The root user can bypass this step and can directly change the password, so as the forgotten passwords may be recovered.Verify password aging information : In Linux, a user password can be set to expire after a given period of time. Also, a user can be prohibited to change his/her password for a period. This password aging information (and the password itself) is stored in a file /etc/shadow.Change the password : After authentication, the user is prompted to enter the new password and verify it by retyping the password./etc/shadow file: The shadow file is a list of colon separated values with 9 fields, as shown below:user1:$6$x8wAJRpP$EWC97sXW5tqac10Q2TQyXkR.1l1jdK4VLK1pkZKmA2mbA6UnSGyo94Pis074viWBA3sVbkCptSZzuP2K.y.an/:17887:0:99999:7:::field 1: User name.field 2: Encrypted Password.field 3: Number of days since January 1, 1970 to when the password was last changed.field 4: Minimum number of days for which password can not be changed. (value 0 means it can be changed anytime).field 5: Number of days after password must be changed. (value 99999 means that the password never expires).field 6: Number of days to warn user for expiring password.field 7: Number of days after password expires that the account is disabled.field 8: The number of days from January 1, 1970 to the date when an account was disabled.field 9: This field is reserved for some possible future use.passwd options:-d, –delete: This option deletes the user password and makes the account password-less.-e, –expire: This option immediately expires the account password and forces the user to change password on their next login.-h, –help: Display help related to the passwd command.-i, –inactive INACTIVE_DAYS: This option is followed by an integer, INACTIVE_DAYS, which is the number of days after the password expires that the account will be deactivated.example: passwd -i 3 user1 -k, –keep-tokens: This option is used when you only want to change the password if it is expired. It keeps the authentication tokens for the authentication if the password is not yet expired, even if you requested to change it. Note that if the expiry period for a user is set to 99999, then this option will not keep tokens and the password will be changed.-l, –lock: Lock the password of user. This appends the encrypted password of the user with a character ‘!’, and thus making it unable to match with any of input password combinations. This does not disable the account but prevents the user from logging in using a password. Though other authentication methods like ssh keys can be used to login to the account.-n, –mindays MIN_DAYS: Change the minimum number of days between password changes to MIN_DAYS so that the user can’t change the password for MIN_DAYS.-q, –quiet: This option is used for quiet mode. While using this option to change a password, the message “Changing password for $user.”, which usually gets printed before changing a password, does not get echoed.-r, –repository REPO: This option is used to change password for repository named “REPO”.-R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory. This basically changes the root directory for the passwd process for once, and since CHROOT_DIR is a sub-directory of the root, it can not access the configuration files outside the CHROOT_DIR.-S, –status: Shows the password status (7 fields) of user in the following format:user1 P 12/22/2018 0 99999 7 3The first field is the user’s login name. The second field indicates if the user account has a locked password (L), has no Password (NP), or has a usable password (P). The third field gives the date of the last password change. The next four fields are the minimum age, maximum age, warning period, and inactivity period for the password. These ages are expressed in days.-S [, –status] -a [, –all]: This combination of options shows password status for all users. Note that -a or –all cannot be used without -S option.-u, –unlock: Unlock the password of an account.-w, –warndays WARN_DAYS: This option is used to change the number of days before the password is to expire, to display the warning for expiring password.-x, –maxdays MAX_DAYS Set the maximum number of days for which the password remains valid. After MAX_DAYS, the password will expire and the user will be forced to change password.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30239, "s": 29940, "text": "Verify current user password : Once the user enters passwd command, it prompts for current user password, which is verified against the password stored in /etc/shadow file user. The root user can bypass this step and can directly change the password, so as the forgotten passwords may be recovered." }, { "code": null, "e": 30515, "s": 30239, "text": "Verify password aging information : In Linux, a user password can be set to expire after a given period of time. Also, a user can be prohibited to change his/her password for a period. This password aging information (and the password itself) is stored in a file /etc/shadow." }, { "code": null, "e": 34525, "s": 30515, "text": "Change the password : After authentication, the user is prompted to enter the new password and verify it by retyping the password./etc/shadow file: The shadow file is a list of colon separated values with 9 fields, as shown below:user1:$6$x8wAJRpP$EWC97sXW5tqac10Q2TQyXkR.1l1jdK4VLK1pkZKmA2mbA6UnSGyo94Pis074viWBA3sVbkCptSZzuP2K.y.an/:17887:0:99999:7:::field 1: User name.field 2: Encrypted Password.field 3: Number of days since January 1, 1970 to when the password was last changed.field 4: Minimum number of days for which password can not be changed. (value 0 means it can be changed anytime).field 5: Number of days after password must be changed. (value 99999 means that the password never expires).field 6: Number of days to warn user for expiring password.field 7: Number of days after password expires that the account is disabled.field 8: The number of days from January 1, 1970 to the date when an account was disabled.field 9: This field is reserved for some possible future use.passwd options:-d, –delete: This option deletes the user password and makes the account password-less.-e, –expire: This option immediately expires the account password and forces the user to change password on their next login.-h, –help: Display help related to the passwd command.-i, –inactive INACTIVE_DAYS: This option is followed by an integer, INACTIVE_DAYS, which is the number of days after the password expires that the account will be deactivated.example: passwd -i 3 user1 -k, –keep-tokens: This option is used when you only want to change the password if it is expired. It keeps the authentication tokens for the authentication if the password is not yet expired, even if you requested to change it. Note that if the expiry period for a user is set to 99999, then this option will not keep tokens and the password will be changed.-l, –lock: Lock the password of user. This appends the encrypted password of the user with a character ‘!’, and thus making it unable to match with any of input password combinations. This does not disable the account but prevents the user from logging in using a password. Though other authentication methods like ssh keys can be used to login to the account.-n, –mindays MIN_DAYS: Change the minimum number of days between password changes to MIN_DAYS so that the user can’t change the password for MIN_DAYS.-q, –quiet: This option is used for quiet mode. While using this option to change a password, the message “Changing password for $user.”, which usually gets printed before changing a password, does not get echoed.-r, –repository REPO: This option is used to change password for repository named “REPO”.-R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory. This basically changes the root directory for the passwd process for once, and since CHROOT_DIR is a sub-directory of the root, it can not access the configuration files outside the CHROOT_DIR.-S, –status: Shows the password status (7 fields) of user in the following format:user1 P 12/22/2018 0 99999 7 3The first field is the user’s login name. The second field indicates if the user account has a locked password (L), has no Password (NP), or has a usable password (P). The third field gives the date of the last password change. The next four fields are the minimum age, maximum age, warning period, and inactivity period for the password. These ages are expressed in days.-S [, –status] -a [, –all]: This combination of options shows password status for all users. Note that -a or –all cannot be used without -S option.-u, –unlock: Unlock the password of an account.-w, –warndays WARN_DAYS: This option is used to change the number of days before the password is to expire, to display the warning for expiring password.-x, –maxdays MAX_DAYS Set the maximum number of days for which the password remains valid. After MAX_DAYS, the password will expire and the user will be forced to change password.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 34626, "s": 34525, "text": "/etc/shadow file: The shadow file is a list of colon separated values with 9 fields, as shown below:" }, { "code": null, "e": 34750, "s": 34626, "text": "user1:$6$x8wAJRpP$EWC97sXW5tqac10Q2TQyXkR.1l1jdK4VLK1pkZKmA2mbA6UnSGyo94Pis074viWBA3sVbkCptSZzuP2K.y.an/:17887:0:99999:7:::" }, { "code": null, "e": 34770, "s": 34750, "text": "field 1: User name." }, { "code": null, "e": 34799, "s": 34770, "text": "field 2: Encrypted Password." }, { "code": null, "e": 34884, "s": 34799, "text": "field 3: Number of days since January 1, 1970 to when the password was last changed." }, { "code": null, "e": 34998, "s": 34884, "text": "field 4: Minimum number of days for which password can not be changed. (value 0 means it can be changed anytime)." }, { "code": null, "e": 35107, "s": 34998, "text": "field 5: Number of days after password must be changed. (value 99999 means that the password never expires)." }, { "code": null, "e": 35167, "s": 35107, "text": "field 6: Number of days to warn user for expiring password." }, { "code": null, "e": 35244, "s": 35167, "text": "field 7: Number of days after password expires that the account is disabled." }, { "code": null, "e": 35335, "s": 35244, "text": "field 8: The number of days from January 1, 1970 to the date when an account was disabled." }, { "code": null, "e": 35397, "s": 35335, "text": "field 9: This field is reserved for some possible future use." }, { "code": null, "e": 35413, "s": 35397, "text": "passwd options:" }, { "code": null, "e": 35501, "s": 35413, "text": "-d, –delete: This option deletes the user password and makes the account password-less." }, { "code": null, "e": 35627, "s": 35501, "text": "-e, –expire: This option immediately expires the account password and forces the user to change password on their next login." }, { "code": null, "e": 35682, "s": 35627, "text": "-h, –help: Display help related to the passwd command." }, { "code": null, "e": 35885, "s": 35682, "text": "-i, –inactive INACTIVE_DAYS: This option is followed by an integer, INACTIVE_DAYS, which is the number of days after the password expires that the account will be deactivated.example: passwd -i 3 user1 " }, { "code": null, "e": 35913, "s": 35885, "text": "example: passwd -i 3 user1 " }, { "code": null, "e": 36272, "s": 35913, "text": "-k, –keep-tokens: This option is used when you only want to change the password if it is expired. It keeps the authentication tokens for the authentication if the password is not yet expired, even if you requested to change it. Note that if the expiry period for a user is set to 99999, then this option will not keep tokens and the password will be changed." }, { "code": null, "e": 36633, "s": 36272, "text": "-l, –lock: Lock the password of user. This appends the encrypted password of the user with a character ‘!’, and thus making it unable to match with any of input password combinations. This does not disable the account but prevents the user from logging in using a password. Though other authentication methods like ssh keys can be used to login to the account." }, { "code": null, "e": 36784, "s": 36633, "text": "-n, –mindays MIN_DAYS: Change the minimum number of days between password changes to MIN_DAYS so that the user can’t change the password for MIN_DAYS." }, { "code": null, "e": 36998, "s": 36784, "text": "-q, –quiet: This option is used for quiet mode. While using this option to change a password, the message “Changing password for $user.”, which usually gets printed before changing a password, does not get echoed." }, { "code": null, "e": 37088, "s": 36998, "text": "-r, –repository REPO: This option is used to change password for repository named “REPO”." }, { "code": null, "e": 37409, "s": 37088, "text": "-R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory. This basically changes the root directory for the passwd process for once, and since CHROOT_DIR is a sub-directory of the root, it can not access the configuration files outside the CHROOT_DIR." }, { "code": null, "e": 38041, "s": 37409, "text": "-S, –status: Shows the password status (7 fields) of user in the following format:user1 P 12/22/2018 0 99999 7 3The first field is the user’s login name. The second field indicates if the user account has a locked password (L), has no Password (NP), or has a usable password (P). The third field gives the date of the last password change. The next four fields are the minimum age, maximum age, warning period, and inactivity period for the password. These ages are expressed in days.-S [, –status] -a [, –all]: This combination of options shows password status for all users. Note that -a or –all cannot be used without -S option." }, { "code": null, "e": 38072, "s": 38041, "text": "user1 P 12/22/2018 0 99999 7 3" }, { "code": null, "e": 38445, "s": 38072, "text": "The first field is the user’s login name. The second field indicates if the user account has a locked password (L), has no Password (NP), or has a usable password (P). The third field gives the date of the last password change. The next four fields are the minimum age, maximum age, warning period, and inactivity period for the password. These ages are expressed in days." }, { "code": null, "e": 38593, "s": 38445, "text": "-S [, –status] -a [, –all]: This combination of options shows password status for all users. Note that -a or –all cannot be used without -S option." }, { "code": null, "e": 38641, "s": 38593, "text": "-u, –unlock: Unlock the password of an account." }, { "code": null, "e": 38795, "s": 38641, "text": "-w, –warndays WARN_DAYS: This option is used to change the number of days before the password is to expire, to display the warning for expiring password." }, { "code": null, "e": 38975, "s": 38795, "text": "-x, –maxdays MAX_DAYS Set the maximum number of days for which the password remains valid. After MAX_DAYS, the password will expire and the user will be forced to change password." }, { "code": null, "e": 38989, "s": 38975, "text": "linux-command" }, { "code": null, "e": 39011, "s": 38989, "text": "Linux-system-commands" }, { "code": null, "e": 39018, "s": 39011, "text": "Picked" }, { "code": null, "e": 39029, "s": 39018, "text": "Linux-Unix" }, { "code": null, "e": 39127, "s": 39029, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39136, "s": 39127, "text": "Comments" }, { "code": null, "e": 39149, "s": 39136, "text": "Old Comments" }, { "code": null, "e": 39187, "s": 39149, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 39222, "s": 39187, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 39257, "s": 39222, "text": "tar command in Linux with examples" }, { "code": null, "e": 39298, "s": 39257, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 39334, "s": 39298, "text": "curl command in Linux with Examples" }, { "code": null, "e": 39372, "s": 39334, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 39405, "s": 39372, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 39443, "s": 39405, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 39479, "s": 39443, "text": "diff command in Linux with examples" } ]
How to get row index or column index based on their names in R?
We might prefer to use row index or column index during the analysis instead of using their numbers, therefore, we can get them with the help of grep function. While dealing with a large data set it becomes helpful because large data sets have large number of rows and columns so it is easier to recall them with their indexes instead of numbers. Specifically, column indexes are needed, on the other hand, rows are required in special cases only such as analysing a particular case. Consider the below data frame − > set.seed(1) > x1<-rnorm(50,0.5) > x2<-rnorm(50,0.8) > x3<-rpois(50,2) > x4<-rpois(50,5) > x5<-runif(50,5,10) > df<-data.frame(x1,x2,x3,x4,x5) > head(df,20) x1 x2 x3 x4 x5 1 -0.1264538 1.19810588 1 6 8.368561 2 0.6836433 0.18797361 1 9 5.474289 3 -0.3356286 1.14111969 2 5 7.462981 4 2.0952808 -0.32936310 1 5 7.307759 5 0.8295078 2.23302370 1 5 6.876083 6 -0.3204684 2.78039990 2 2 9.955496 7 0.9874291 0.43277852 2 3 5.881754 8 1.2383247 -0.24413463 0 5 9.067176 9 1.0757814 1.36971963 1 4 5.342233 10 0.1946116 0.66494540 3 9 7.002249 11 2.0117812 3.20161776 5 5 5.705722 12 0.8898432 0.76076000 0 4 5.966549 13 -0.1212406 1.48973936 3 4 9.206759 14 -1.7146999 0.82800216 5 7 8.599570 15 1.6249309 0.05672679 3 6 6.336060 16 0.4550664 0.98879230 1 3 7.475008 17 0.4838097 -1.00495863 2 2 5.415569 18 1.4438362 2.26555486 5 6 6.769421 19 1.3212212 0.95325334 5 6 9.846044 20 1.0939013 2.97261167 1 3 8.123571 Finding the index of columns based on their names − > grep("x3", colnames(df)) [1] 3 > grep("x5", colnames(df)) [1] 5 > grep("x1", colnames(df)) [1] 1 Let’s change the row names because they are numbered from 1 to 50, so row index will be same as their name. We will change them to 50 to 1 as shown below − > rownames(df)<-50:1 > head(df,20) x1 x2 x3 x4 x5 50 -0.1264538 1.19810588 1 6 8.368561 49 0.6836433 0.18797361 1 9 5.474289 48 -0.3356286 1.14111969 2 5 7.462981 47 2.0952808 -0.32936310 1 5 7.307759 46 0.8295078 2.23302370 1 5 6.876083 45 -0.3204684 2.78039990 2 2 9.955496 44 0.9874291 0.43277852 2 3 5.881754 43 1.2383247 -0.24413463 0 5 9.067176 42 1.0757814 1.36971963 1 4 5.342233 41 0.1946116 0.66494540 3 9 7.002249 40 2.0117812 3.20161776 5 5 5.705722 39 0.8898432 0.76076000 0 4 5.966549 38 -0.1212406 1.48973936 3 4 9.206759 37 -1.7146999 0.82800216 5 7 8.599570 36 1.6249309 0.05672679 3 6 6.336060 35 0.4550664 0.98879230 1 3 7.475008 34 0.4838097 -1.00495863 2 2 5.415569 33 1.4438362 2.26555486 5 6 6.769421 32 1.3212212 0.95325334 5 6 9.846044 31 1.0939013 2.97261167 1 3 8.123571 Now let’s find the row names that contains number 5 − > grep(5, rownames(df)) [1] 1 6 16 26 36 46 Finding the row name of the tenth row − > grep(10, rownames(df)) [1] 41 Finding the row names that contains number 4 − > grep(4, rownames(df)) [1] 2 3 4 5 6 7 8 9 10 11 17 27 37 47
[ { "code": null, "e": 1546, "s": 1062, "text": "We might prefer to use row index or column index during the analysis instead of using their numbers, therefore, we can get them with the help of grep function. While dealing with a large data set it becomes helpful because large data sets have large number of rows and columns so it is easier to recall them with their indexes instead of numbers. Specifically, column indexes are needed, on the other hand, rows are required in special cases only such as analysing a particular case." }, { "code": null, "e": 1578, "s": 1546, "text": "Consider the below data frame −" }, { "code": null, "e": 2511, "s": 1578, "text": "> set.seed(1)\n> x1<-rnorm(50,0.5)\n> x2<-rnorm(50,0.8)\n> x3<-rpois(50,2)\n> x4<-rpois(50,5)\n> x5<-runif(50,5,10)\n> df<-data.frame(x1,x2,x3,x4,x5)\n> head(df,20)\nx1 x2 x3 x4 x5\n1 -0.1264538 1.19810588 1 6 8.368561\n2 0.6836433 0.18797361 1 9 5.474289\n3 -0.3356286 1.14111969 2 5 7.462981\n4 2.0952808 -0.32936310 1 5 7.307759\n5 0.8295078 2.23302370 1 5 6.876083\n6 -0.3204684 2.78039990 2 2 9.955496\n7 0.9874291 0.43277852 2 3 5.881754\n8 1.2383247 -0.24413463 0 5 9.067176\n9 1.0757814 1.36971963 1 4 5.342233\n10 0.1946116 0.66494540 3 9 7.002249\n11 2.0117812 3.20161776 5 5 5.705722\n12 0.8898432 0.76076000 0 4 5.966549\n13 -0.1212406 1.48973936 3 4 9.206759\n14 -1.7146999 0.82800216 5 7 8.599570\n15 1.6249309 0.05672679 3 6 6.336060\n16 0.4550664 0.98879230 1 3 7.475008\n17 0.4838097 -1.00495863 2 2 5.415569\n18 1.4438362 2.26555486 5 6 6.769421\n19 1.3212212 0.95325334 5 6 9.846044\n20 1.0939013 2.97261167 1 3 8.123571" }, { "code": null, "e": 2563, "s": 2511, "text": "Finding the index of columns based on their names −" }, { "code": null, "e": 2662, "s": 2563, "text": "> grep(\"x3\", colnames(df))\n[1] 3\n> grep(\"x5\", colnames(df))\n[1] 5\n> grep(\"x1\", colnames(df))\n[1] 1" }, { "code": null, "e": 2818, "s": 2662, "text": "Let’s change the row names because they are numbered from 1 to 50, so row index will be same as their name. We will change them to 50 to 1 as shown below −" }, { "code": null, "e": 3773, "s": 2818, "text": "> rownames(df)<-50:1\n> head(df,20)\n x1 x2 x3 x4 x5\n50 -0.1264538 1.19810588 1 6 8.368561\n49 0.6836433 0.18797361 1 9 5.474289\n48 -0.3356286 1.14111969 2 5 7.462981\n47 2.0952808 -0.32936310 1 5 7.307759\n46 0.8295078 2.23302370 1 5 6.876083\n45 -0.3204684 2.78039990 2 2 9.955496\n44 0.9874291 0.43277852 2 3 5.881754\n43 1.2383247 -0.24413463 0 5 9.067176\n42 1.0757814 1.36971963 1 4 5.342233\n41 0.1946116 0.66494540 3 9 7.002249\n40 2.0117812 3.20161776 5 5 5.705722\n39 0.8898432 0.76076000 0 4 5.966549\n38 -0.1212406 1.48973936 3 4 9.206759\n37 -1.7146999 0.82800216 5 7 8.599570\n36 1.6249309 0.05672679 3 6 6.336060\n35 0.4550664 0.98879230 1 3 7.475008\n34 0.4838097 -1.00495863 2 2 5.415569\n33 1.4438362 2.26555486 5 6 6.769421\n32 1.3212212 0.95325334 5 6 9.846044\n31 1.0939013 2.97261167 1 3 8.123571" }, { "code": null, "e": 3827, "s": 3773, "text": "Now let’s find the row names that contains number 5 −" }, { "code": null, "e": 3871, "s": 3827, "text": "> grep(5, rownames(df))\n[1] 1 6 16 26 36 46" }, { "code": null, "e": 3911, "s": 3871, "text": "Finding the row name of the tenth row −" }, { "code": null, "e": 3943, "s": 3911, "text": "> grep(10, rownames(df))\n[1] 41" }, { "code": null, "e": 3990, "s": 3943, "text": "Finding the row names that contains number 4 −" }, { "code": null, "e": 4052, "s": 3990, "text": "> grep(4, rownames(df))\n[1] 2 3 4 5 6 7 8 9 10 11 17 27 37 47" } ]
Prediction of P-Sonic Log in the Volve Oil Field using Machine Learning | by Yohanes Nuwara | Towards Data Science
In 2018, Norwegian oil company Equinor disclosed a massive subsurface and operation dataset from their Volve oil field in the North Sea. For two years until now, it has been good news for all people who are passionate about improving and solving challenges in the study of oil and gas fields in universities, research institutions, and companies. The following is an encouraging quote from Jannicke Nilsson, the COO of Equinor. “Volve is an example of how we searched for every possibility to extend the field life. Now we want to share all Volve data to ensure learning and development of future solutions.” Volve is an oil field located 200 kilometers west of Stavanger at the southern end of the Norwegian sector in the North Sea and produced from 2008 until 2016. When I had a look inside the database that everyone can access through this website, I saw tremendous treasures inside! I started to pitch some ideas to explore the possibility of bringing machine learning until I came up with an idea of doing sonic log prediction with the reason I elaborate in the Motivation section of this article. I keep this project in my GitHub repository (where you can visit) called volve-machine-learning. In the Volve field open database, there are 24 wells. In this study, only 5 wells are used. The well names are 15/9-F-11A, 15/9-F-11B, 15/9-F-1A, 15/9-F-1B, and 15/9-F-1C. Each of these wells has what they are known as logs. The logs are certain physical measurements that represent the properties of each rock strata over the depth. The following is a list of logs that we will use. NPHI is the formation porosity, measured in v/v. RHOB is the formation bulk density, measured in grams per cubic centimeters. GR is the formation radioactivity content, measured in API. RT is the formation true resistivity, measured in ohm-meter. PEF is the formation photoelectric absorption factor, dimensionless. CALI is the borehole diameter, measured in inch. DT is the compressional (P-wave) travel time, measured in microseconds per foot. DTS is the shear (S-wave) travel time, measured in similarly to DT. These well-log datasets have the file format of LAS 2.0, a specific format for well-logs. You can find the datasets here. 3 wells out of 5 (well 15/9-F-11A, 15/9-F-1A, and 15/9-F-1B) have this complete suite of logs, except the 2 others (well 15/9-F-11A and 15/F-1C) don’t have DT and DTS log. This is the reason why we can use supervised learning to produce the DT log in this incomplete dataset using regression models. The 3 datasets that have the DT log is used as the training data, and those that don’t have is used as the test data. The NPHI, RHOB, GR, RT, PEF, and CALI logs are used as the features; whereas the DT is the target for prediction. For now, the DTS log will not be used. Through supervised learning, these training data will be trained with some regression models in Scikit-Learn. Then, the model will be used to produce new DT logs based on the prediction of the features. I will discuss the workflow into seven steps. You may also access my IPython notebook inside my GitHub repo that runs this workflow from start to finish. Access my IPython notebook A Python library called lasio is used to read these LAS datasets. In any formation evaluation, displaying the well-logs is a routine. The following is the display of one of the training data, well 15/9-F-1B, produced using Matplotlib. Each plot represents each log; as we have already discussed, the NPHI, RHOB, GR, RT, PEF, and CALI are the features, and DT is the target. The following is the well-log display of well 15/9-F-1C, one of the 2 wells that don’t have DT log, and hence we will predict to produce a new DT log. The second step is the most critical part of the workflow as it impacts the whole success story of prediction. Pandas is useful for data processing. First, we need to make sure that our entire data does not contain any non-numerical values (NaNs). One trick to filter our data is to set the minimum and maximum depth limit so that all the data starts and ends with numerical values. For instance, the previously displayed well 15/9-F-1B starts from depth at 3,100 m to 3,400 m. Sample code to do this, df = df.loc[(df['DEPTH'] >= 3100) & (df['DEPTH'] <= 3400)] After that, we check if NaNs exist in our data. df.isnull().sum() If it turns all zero, we are safe to go. In our case now, it turns all zero and we are already clean from NaNs. Unless so, we need to handle the NaN values. This action is extensively discussed here. Next, we merge the individual well datasets into two larger single data frames, each for the training and test datasets. df = pd.concat([df1, df2, df3]) After we have now training and test data frames, finally we assign the well names. The reason for doing this is to ease us retrieving any well during our prediction. You can see inside the notebook on how I assign the well names. Below is the final data frame for the training data. Exploratory data analysis (EDA) is crucial to understand our data. Two important things we want to know is the distribution of each individual feature and the correlation of one feature to another. To observe the multivariate distribution, we can use a pair-plot in Seaborn package. The following is the multivariate distribution of the features and the target. At least 3 things we get from the pair-plot. First, we observe how most distributions are skewed and not ideally Gaussian, especially the RT. However, for machine learning, a Gaussian or less skewed data is preferred. We can do normalization on this data that will be discussed next. Second, we can see outliers inside the data. Also in the next part, we will discuss removing these outliers. Third, we see some data pairs are almost linearly (thus highly) correlated, such as NPHI and DT; and inversely correlated, such as RHOB and DT. A pair-plot tells lots of things. We look more into correlations among features and target by calculating the Spearman’s correlation and visualize the results using the heatmap. The following is the Spearman’s correlation heatmap of our data. Just focus on the DT row, we obtain the 2 largest correlation between DT and NPHI (positive correlation of .95) and between DT and RHOB (negative correlation of .79). This correlation result matches with the ones we see before in the pair-plot. Also, other data seems to have a high correlation with DT, except CALI. CALI also seems to have little correlation with other features. As a common practice, any feature with very low correlation is excluded for prediction, hence CALI can be excluded. Here, however, I will keep CALI as a feature. We know before from the pair-plot that most distributions seem skewed. In order to improve our prediction performance, later on, we’d better do a normalization (others may call as scaling). Normalization is a technique to transform the data (without changing it) to be better distributed. Before doing any normalization, I prefer to log transform the resistivity data first. df['RT'] = np.log10(df['RT']) Then, I do normalization with the function fit_transform in Scikit-Learn. There are several normalization techniques; the widely used are standardization (by transforming with the mean and standard deviation) and min-max (with minimum and maximum value). After trying all the methods, I find the power transform technique using Yeo-Johnson method. After normalization, we can see how the data is now distributed again using pair-plot. Look how NPHI, DT, and RT are now less skewed and more Gaussian-like. Although RHOB and GR distribution look multimodal, after normalization it becomes more centered. Also, we just observed many outliers inside the data. The presence of outliers can downgrade the prediction performance. Therefore, we do outlier removal. Scikit-Learn provides several outlier removal methods, such as Isolation Forest, Minimum Covariance using Elliptic Envelope, Local Outlier Factor, and One-class Support Vector Machine. Alongside these, the most widely used outlier removal method, yet basic, is using the standard deviation method. In this method, we specify the threshold as the min and max values away from the standard deviation. We can build this ourselves. threshold = 3df = df[np.abs(df - df.mean()) <= (threshold * df.std())] All 5 methods are implemented. There are two ways that I use to compare which method performs the best outlier removal. One way is to count the data before outliers removed and the data after outliers removed for each method. From this result, we see that the standard deviation method remove the fewest outliers (as much as only 302), followed One-class SVM and Minimum Covariance with relatively fewer outliers, compared to others (>10,000). As you may have already known, fewer outliers removed is better. Then, to decide which one is better between standard deviation and One-class SVM, I produce the box-plots using Pandas for each feature before and after normalization. Below are the box-plots. The key observation is that before and after outlier removal, outliers still exist in the data within the newly computed summary stats. This (indirectly) is a visual representation to choose which method is the best. Now it becomes visible by observing the number of outliers that One-class SVM performs “cleaner” than the standard deviation method. Although Minimum Covariance is also clean, still One-class SVM is the winner. The conclusion is: we use One-class SVM. Again, we produce a pair-plot to observe the final result of our data. Look how the outliers are now much more reduced. We are all set for machine learning. Now comes the main course! In the fifth step, we have not yet actually do the prediction to our real test data (well 15/F-11B and 15/F-1C that don’t have DT log). Be patient! We need to evaluate the performance of each regression model that we use by training the train data and testing the model to the train data themselves, and then we evaluate how close the predicted DT log to the true DT log. In this step, test data = train data I tried 6 regression models from Scikit-Learn, namely the classic linear regression, Random Forest, Support Vector Machine, Decision Tree, Gradient Boosting, and K-Nearest Neighbors regressors. Keep in mind that we always have to de-normalize our result after we finish the prediction because we did normalization just earlier. In Scikit-Learn, we do this using an inverse_transform function. I use R2 and root mean squared error (RMSE) as the scoring metric to measure the performance of each regression model. The following is the result of the scoring metric for each regressor. From the result, we see that the regressors perform very excellent! It is understandable why the classic linear regressor doesn’t perform as very well as the other regressors (lowest R2 and RMSE). The reason is that not all features are perfectly and linearly correlated. We can then display both the true DT log and the predicted DT log to compare the closeness of both. The following is true vs. predicted DT log for each well using Gradient Boosting regressor. In fact, all the regressors that I use are still using the default hyperparameters. For instance, two of several hyperparameters of Gradient Boosting are the number of estimators and the maximum depth. The defaults are 100 and 3, respectively. From the scoring metric of Gradient Boosting, we knew already the R2 and RMSE achieved are around .94 and .22, respectively. We can do the hyperparameter tuning to determine the best hyperparameter values in order to increase the performance score. The hyperparameter tuning on the Gradient Boosting regressor is started by doing a train-test split with a composition of 0.7 train and 0.3 test. And then, through the produced train and test splits, a grid search with defined searched sets of hyperparameters and 3-fold cross-validation are done. The following are the searched parameter grids. Number of estimators n_estimators: 100 and 1,000 Maximum depth max_depth: 10 and 100 It took ~5 minutes to tune the hyperparameters until it gives a result of 1,000 and 100 for the number of estimators and maximum depth each as the best hyperparameters. The previous step is then repeated by including the hyperparameters and it prints the new scoring metric as follows. Both R2 and RMSE improve a lot to around .98 and .12! With this result, we are confident enough to use Gradient Boosting for prediction. The following is the true vs. predicted DT log plot after hyperparameter tuning. Finally, we do the real prediction! Now, compile the Gradient Boosting regressor with the hyperparameters previously tuned (number of estimators = 1,000 and maximum depth = 10) to our real test data. Remember that our real test data are the wells that don’t have DT log; well 15/9-F-11B and 15/9-F-1C, or the so-called well 2 and well 5. The following are the predicted DT logs in well 2 and well 5. The predicted logs in well 15/9-F-11B and well 15/9-F-1C are pleasing! To close our workflow, we can import the predicted result to the original datasets and write to CSV file. Here is the final CSV result: well 15/9-F-11B and 15/9-F-1C We have proved the successful utilization of supervised learning to the Volve oil field open dataset owned by Equinor. With this workflow, new P-sonic (DT) logs have been predicted on two wells that originally don’t have a DT log using the Gradient Boosting method. I hope this article brings new fresh air for any ML practitioners in geoscience to start exploring other possibilities of ML in this dataset. In the meantime, I am thinking of other possibilities that I will actively update in my GitHub (follow my work to get the updates) and will write another very soon!
[ { "code": null, "e": 600, "s": 172, "text": "In 2018, Norwegian oil company Equinor disclosed a massive subsurface and operation dataset from their Volve oil field in the North Sea. For two years until now, it has been good news for all people who are passionate about improving and solving challenges in the study of oil and gas fields in universities, research institutions, and companies. The following is an encouraging quote from Jannicke Nilsson, the COO of Equinor." }, { "code": null, "e": 781, "s": 600, "text": "“Volve is an example of how we searched for every possibility to extend the field life. Now we want to share all Volve data to ensure learning and development of future solutions.”" }, { "code": null, "e": 940, "s": 781, "text": "Volve is an oil field located 200 kilometers west of Stavanger at the southern end of the Norwegian sector in the North Sea and produced from 2008 until 2016." }, { "code": null, "e": 1276, "s": 940, "text": "When I had a look inside the database that everyone can access through this website, I saw tremendous treasures inside! I started to pitch some ideas to explore the possibility of bringing machine learning until I came up with an idea of doing sonic log prediction with the reason I elaborate in the Motivation section of this article." }, { "code": null, "e": 1373, "s": 1276, "text": "I keep this project in my GitHub repository (where you can visit) called volve-machine-learning." }, { "code": null, "e": 1545, "s": 1373, "text": "In the Volve field open database, there are 24 wells. In this study, only 5 wells are used. The well names are 15/9-F-11A, 15/9-F-11B, 15/9-F-1A, 15/9-F-1B, and 15/9-F-1C." }, { "code": null, "e": 1757, "s": 1545, "text": "Each of these wells has what they are known as logs. The logs are certain physical measurements that represent the properties of each rock strata over the depth. The following is a list of logs that we will use." }, { "code": null, "e": 1806, "s": 1757, "text": "NPHI is the formation porosity, measured in v/v." }, { "code": null, "e": 1883, "s": 1806, "text": "RHOB is the formation bulk density, measured in grams per cubic centimeters." }, { "code": null, "e": 1943, "s": 1883, "text": "GR is the formation radioactivity content, measured in API." }, { "code": null, "e": 2004, "s": 1943, "text": "RT is the formation true resistivity, measured in ohm-meter." }, { "code": null, "e": 2073, "s": 2004, "text": "PEF is the formation photoelectric absorption factor, dimensionless." }, { "code": null, "e": 2122, "s": 2073, "text": "CALI is the borehole diameter, measured in inch." }, { "code": null, "e": 2203, "s": 2122, "text": "DT is the compressional (P-wave) travel time, measured in microseconds per foot." }, { "code": null, "e": 2271, "s": 2203, "text": "DTS is the shear (S-wave) travel time, measured in similarly to DT." }, { "code": null, "e": 2393, "s": 2271, "text": "These well-log datasets have the file format of LAS 2.0, a specific format for well-logs. You can find the datasets here." }, { "code": null, "e": 2693, "s": 2393, "text": "3 wells out of 5 (well 15/9-F-11A, 15/9-F-1A, and 15/9-F-1B) have this complete suite of logs, except the 2 others (well 15/9-F-11A and 15/F-1C) don’t have DT and DTS log. This is the reason why we can use supervised learning to produce the DT log in this incomplete dataset using regression models." }, { "code": null, "e": 2964, "s": 2693, "text": "The 3 datasets that have the DT log is used as the training data, and those that don’t have is used as the test data. The NPHI, RHOB, GR, RT, PEF, and CALI logs are used as the features; whereas the DT is the target for prediction. For now, the DTS log will not be used." }, { "code": null, "e": 3167, "s": 2964, "text": "Through supervised learning, these training data will be trained with some regression models in Scikit-Learn. Then, the model will be used to produce new DT logs based on the prediction of the features." }, { "code": null, "e": 3321, "s": 3167, "text": "I will discuss the workflow into seven steps. You may also access my IPython notebook inside my GitHub repo that runs this workflow from start to finish." }, { "code": null, "e": 3348, "s": 3321, "text": "Access my IPython notebook" }, { "code": null, "e": 3722, "s": 3348, "text": "A Python library called lasio is used to read these LAS datasets. In any formation evaluation, displaying the well-logs is a routine. The following is the display of one of the training data, well 15/9-F-1B, produced using Matplotlib. Each plot represents each log; as we have already discussed, the NPHI, RHOB, GR, RT, PEF, and CALI are the features, and DT is the target." }, { "code": null, "e": 3873, "s": 3722, "text": "The following is the well-log display of well 15/9-F-1C, one of the 2 wells that don’t have DT log, and hence we will predict to produce a new DT log." }, { "code": null, "e": 4022, "s": 3873, "text": "The second step is the most critical part of the workflow as it impacts the whole success story of prediction. Pandas is useful for data processing." }, { "code": null, "e": 4375, "s": 4022, "text": "First, we need to make sure that our entire data does not contain any non-numerical values (NaNs). One trick to filter our data is to set the minimum and maximum depth limit so that all the data starts and ends with numerical values. For instance, the previously displayed well 15/9-F-1B starts from depth at 3,100 m to 3,400 m. Sample code to do this," }, { "code": null, "e": 4434, "s": 4375, "text": "df = df.loc[(df['DEPTH'] >= 3100) & (df['DEPTH'] <= 3400)]" }, { "code": null, "e": 4482, "s": 4434, "text": "After that, we check if NaNs exist in our data." }, { "code": null, "e": 4500, "s": 4482, "text": "df.isnull().sum()" }, { "code": null, "e": 4700, "s": 4500, "text": "If it turns all zero, we are safe to go. In our case now, it turns all zero and we are already clean from NaNs. Unless so, we need to handle the NaN values. This action is extensively discussed here." }, { "code": null, "e": 4821, "s": 4700, "text": "Next, we merge the individual well datasets into two larger single data frames, each for the training and test datasets." }, { "code": null, "e": 4853, "s": 4821, "text": "df = pd.concat([df1, df2, df3])" }, { "code": null, "e": 5083, "s": 4853, "text": "After we have now training and test data frames, finally we assign the well names. The reason for doing this is to ease us retrieving any well during our prediction. You can see inside the notebook on how I assign the well names." }, { "code": null, "e": 5136, "s": 5083, "text": "Below is the final data frame for the training data." }, { "code": null, "e": 5334, "s": 5136, "text": "Exploratory data analysis (EDA) is crucial to understand our data. Two important things we want to know is the distribution of each individual feature and the correlation of one feature to another." }, { "code": null, "e": 5498, "s": 5334, "text": "To observe the multivariate distribution, we can use a pair-plot in Seaborn package. The following is the multivariate distribution of the features and the target." }, { "code": null, "e": 6069, "s": 5498, "text": "At least 3 things we get from the pair-plot. First, we observe how most distributions are skewed and not ideally Gaussian, especially the RT. However, for machine learning, a Gaussian or less skewed data is preferred. We can do normalization on this data that will be discussed next. Second, we can see outliers inside the data. Also in the next part, we will discuss removing these outliers. Third, we see some data pairs are almost linearly (thus highly) correlated, such as NPHI and DT; and inversely correlated, such as RHOB and DT. A pair-plot tells lots of things." }, { "code": null, "e": 6278, "s": 6069, "text": "We look more into correlations among features and target by calculating the Spearman’s correlation and visualize the results using the heatmap. The following is the Spearman’s correlation heatmap of our data." }, { "code": null, "e": 6659, "s": 6278, "text": "Just focus on the DT row, we obtain the 2 largest correlation between DT and NPHI (positive correlation of .95) and between DT and RHOB (negative correlation of .79). This correlation result matches with the ones we see before in the pair-plot. Also, other data seems to have a high correlation with DT, except CALI. CALI also seems to have little correlation with other features." }, { "code": null, "e": 6821, "s": 6659, "text": "As a common practice, any feature with very low correlation is excluded for prediction, hence CALI can be excluded. Here, however, I will keep CALI as a feature." }, { "code": null, "e": 7110, "s": 6821, "text": "We know before from the pair-plot that most distributions seem skewed. In order to improve our prediction performance, later on, we’d better do a normalization (others may call as scaling). Normalization is a technique to transform the data (without changing it) to be better distributed." }, { "code": null, "e": 7196, "s": 7110, "text": "Before doing any normalization, I prefer to log transform the resistivity data first." }, { "code": null, "e": 7226, "s": 7196, "text": "df['RT'] = np.log10(df['RT'])" }, { "code": null, "e": 7574, "s": 7226, "text": "Then, I do normalization with the function fit_transform in Scikit-Learn. There are several normalization techniques; the widely used are standardization (by transforming with the mean and standard deviation) and min-max (with minimum and maximum value). After trying all the methods, I find the power transform technique using Yeo-Johnson method." }, { "code": null, "e": 7661, "s": 7574, "text": "After normalization, we can see how the data is now distributed again using pair-plot." }, { "code": null, "e": 7828, "s": 7661, "text": "Look how NPHI, DT, and RT are now less skewed and more Gaussian-like. Although RHOB and GR distribution look multimodal, after normalization it becomes more centered." }, { "code": null, "e": 7983, "s": 7828, "text": "Also, we just observed many outliers inside the data. The presence of outliers can downgrade the prediction performance. Therefore, we do outlier removal." }, { "code": null, "e": 8411, "s": 7983, "text": "Scikit-Learn provides several outlier removal methods, such as Isolation Forest, Minimum Covariance using Elliptic Envelope, Local Outlier Factor, and One-class Support Vector Machine. Alongside these, the most widely used outlier removal method, yet basic, is using the standard deviation method. In this method, we specify the threshold as the min and max values away from the standard deviation. We can build this ourselves." }, { "code": null, "e": 8482, "s": 8411, "text": "threshold = 3df = df[np.abs(df - df.mean()) <= (threshold * df.std())]" }, { "code": null, "e": 8708, "s": 8482, "text": "All 5 methods are implemented. There are two ways that I use to compare which method performs the best outlier removal. One way is to count the data before outliers removed and the data after outliers removed for each method." }, { "code": null, "e": 8991, "s": 8708, "text": "From this result, we see that the standard deviation method remove the fewest outliers (as much as only 302), followed One-class SVM and Minimum Covariance with relatively fewer outliers, compared to others (>10,000). As you may have already known, fewer outliers removed is better." }, { "code": null, "e": 9184, "s": 8991, "text": "Then, to decide which one is better between standard deviation and One-class SVM, I produce the box-plots using Pandas for each feature before and after normalization. Below are the box-plots." }, { "code": null, "e": 9401, "s": 9184, "text": "The key observation is that before and after outlier removal, outliers still exist in the data within the newly computed summary stats. This (indirectly) is a visual representation to choose which method is the best." }, { "code": null, "e": 9612, "s": 9401, "text": "Now it becomes visible by observing the number of outliers that One-class SVM performs “cleaner” than the standard deviation method. Although Minimum Covariance is also clean, still One-class SVM is the winner." }, { "code": null, "e": 9724, "s": 9612, "text": "The conclusion is: we use One-class SVM. Again, we produce a pair-plot to observe the final result of our data." }, { "code": null, "e": 9810, "s": 9724, "text": "Look how the outliers are now much more reduced. We are all set for machine learning." }, { "code": null, "e": 10209, "s": 9810, "text": "Now comes the main course! In the fifth step, we have not yet actually do the prediction to our real test data (well 15/F-11B and 15/F-1C that don’t have DT log). Be patient! We need to evaluate the performance of each regression model that we use by training the train data and testing the model to the train data themselves, and then we evaluate how close the predicted DT log to the true DT log." }, { "code": null, "e": 10246, "s": 10209, "text": "In this step, test data = train data" }, { "code": null, "e": 10440, "s": 10246, "text": "I tried 6 regression models from Scikit-Learn, namely the classic linear regression, Random Forest, Support Vector Machine, Decision Tree, Gradient Boosting, and K-Nearest Neighbors regressors." }, { "code": null, "e": 10639, "s": 10440, "text": "Keep in mind that we always have to de-normalize our result after we finish the prediction because we did normalization just earlier. In Scikit-Learn, we do this using an inverse_transform function." }, { "code": null, "e": 10828, "s": 10639, "text": "I use R2 and root mean squared error (RMSE) as the scoring metric to measure the performance of each regression model. The following is the result of the scoring metric for each regressor." }, { "code": null, "e": 11100, "s": 10828, "text": "From the result, we see that the regressors perform very excellent! It is understandable why the classic linear regressor doesn’t perform as very well as the other regressors (lowest R2 and RMSE). The reason is that not all features are perfectly and linearly correlated." }, { "code": null, "e": 11292, "s": 11100, "text": "We can then display both the true DT log and the predicted DT log to compare the closeness of both. The following is true vs. predicted DT log for each well using Gradient Boosting regressor." }, { "code": null, "e": 11536, "s": 11292, "text": "In fact, all the regressors that I use are still using the default hyperparameters. For instance, two of several hyperparameters of Gradient Boosting are the number of estimators and the maximum depth. The defaults are 100 and 3, respectively." }, { "code": null, "e": 11785, "s": 11536, "text": "From the scoring metric of Gradient Boosting, we knew already the R2 and RMSE achieved are around .94 and .22, respectively. We can do the hyperparameter tuning to determine the best hyperparameter values in order to increase the performance score." }, { "code": null, "e": 12131, "s": 11785, "text": "The hyperparameter tuning on the Gradient Boosting regressor is started by doing a train-test split with a composition of 0.7 train and 0.3 test. And then, through the produced train and test splits, a grid search with defined searched sets of hyperparameters and 3-fold cross-validation are done. The following are the searched parameter grids." }, { "code": null, "e": 12180, "s": 12131, "text": "Number of estimators n_estimators: 100 and 1,000" }, { "code": null, "e": 12216, "s": 12180, "text": "Maximum depth max_depth: 10 and 100" }, { "code": null, "e": 12385, "s": 12216, "text": "It took ~5 minutes to tune the hyperparameters until it gives a result of 1,000 and 100 for the number of estimators and maximum depth each as the best hyperparameters." }, { "code": null, "e": 12502, "s": 12385, "text": "The previous step is then repeated by including the hyperparameters and it prints the new scoring metric as follows." }, { "code": null, "e": 12720, "s": 12502, "text": "Both R2 and RMSE improve a lot to around .98 and .12! With this result, we are confident enough to use Gradient Boosting for prediction. The following is the true vs. predicted DT log plot after hyperparameter tuning." }, { "code": null, "e": 13058, "s": 12720, "text": "Finally, we do the real prediction! Now, compile the Gradient Boosting regressor with the hyperparameters previously tuned (number of estimators = 1,000 and maximum depth = 10) to our real test data. Remember that our real test data are the wells that don’t have DT log; well 15/9-F-11B and 15/9-F-1C, or the so-called well 2 and well 5." }, { "code": null, "e": 13120, "s": 13058, "text": "The following are the predicted DT logs in well 2 and well 5." }, { "code": null, "e": 13297, "s": 13120, "text": "The predicted logs in well 15/9-F-11B and well 15/9-F-1C are pleasing! To close our workflow, we can import the predicted result to the original datasets and write to CSV file." }, { "code": null, "e": 13357, "s": 13297, "text": "Here is the final CSV result: well 15/9-F-11B and 15/9-F-1C" }, { "code": null, "e": 13623, "s": 13357, "text": "We have proved the successful utilization of supervised learning to the Volve oil field open dataset owned by Equinor. With this workflow, new P-sonic (DT) logs have been predicted on two wells that originally don’t have a DT log using the Gradient Boosting method." } ]
Logstash - Parsing the Logs
Logstash receives the logs using input plugins and then uses the filter plugins to parse and transform the data. The parsing and transformation of logs are performed according to the systems present in the output destination. Logstash parses the logging data and forwards only the required fields. Later, these fields are transformed into the destination system’s compatible and understandable form. Parsing of the logs is performed my using the GROK (Graphical Representation of Knowledge) patterns and you can find them in Github − https://github.com/elastic/logstash/tree/v1.4.2/patterns. Logstash matches the data of logs with a specified GROK Pattern or a pattern sequence for parsing the logs like "%{COMBINEDAPACHELOG}", which is commonly used for apache logs. The parsed data is more structured and easy to search and for performing queries. Logstash searches for the specified GROK patterns in the input logs and extracts the matching lines from the logs. You can use GROK debugger to test your GROK patterns. The syntax for a GROK pattern is %{SYNTAX:SEMANTIC}. Logstash GROK filter is written in the following form − %{PATTERN:FieldName} Here, PATTERN represents the GROK pattern and the fieldname is the name of the field, which represents the parsed data in the output. For example, using online GROK debugger https://grokdebug.herokuapp.com/ A sample error line in a log − [Wed Dec 07 21:54:54.048805 2016] [:error] [pid 1234:tid 3456829102] [client 192.168.1.1:25007] JSP Notice: Undefined index: abc in /home/manu/tpworks/tutorialspoint.com/index.jsp on line 11 This GROK pattern sequence matches to the log event, which comprises of a timestamp followed by Log Level, Process Id, Transaction Id and an Error Message. \[(%{DAY:day} %{MONTH:month} %{MONTHDAY} %{TIME} %{YEAR})\] \[.*:%{LOGLEVEL:loglevel}\] \[pid %{NUMBER:pid}:tid %{NUMBER:tid}\] \[client %{IP:clientip}:.*\] %{GREEDYDATA:errormsg} The output is in JSON format. { "day": [ "Wed" ], "month": [ "Dec" ], "loglevel": [ "error" ], "pid": [ "1234" ], "tid": [ "3456829102" ], "clientip": [ "192.168.1.1" ], "errormsg": [ "JSP Notice: Undefined index: abc in /home/manu/tpworks/tutorialspoint.com/index.jsp on line 11" ] } Print Add Notes Bookmark this page
[ { "code": null, "e": 2455, "s": 2055, "text": "Logstash receives the logs using input plugins and then uses the filter plugins to parse and transform the data. The parsing and transformation of logs are performed according to the systems present in the output destination. Logstash parses the logging data and forwards only the required fields. Later, these fields are transformed into the destination system’s compatible and understandable form." }, { "code": null, "e": 2589, "s": 2455, "text": "Parsing of the logs is performed my using the GROK (Graphical Representation of Knowledge) patterns and you can find them in Github −" }, { "code": null, "e": 2647, "s": 2589, "text": "https://github.com/elastic/logstash/tree/v1.4.2/patterns." }, { "code": null, "e": 2823, "s": 2647, "text": "Logstash matches the data of logs with a specified GROK Pattern or a pattern sequence for parsing the logs like \"%{COMBINEDAPACHELOG}\", which is commonly used for apache logs." }, { "code": null, "e": 3074, "s": 2823, "text": "The parsed data is more structured and easy to search and for performing queries. Logstash searches for the specified GROK patterns in the input logs and extracts the matching lines from the logs. You can use GROK debugger to test your GROK patterns." }, { "code": null, "e": 3183, "s": 3074, "text": "The syntax for a GROK pattern is %{SYNTAX:SEMANTIC}. Logstash GROK filter is written in the following form −" }, { "code": null, "e": 3204, "s": 3183, "text": "%{PATTERN:FieldName}" }, { "code": null, "e": 3338, "s": 3204, "text": "Here, PATTERN represents the GROK pattern and the fieldname is the name of the field, which represents the parsed data in the output." }, { "code": null, "e": 3411, "s": 3338, "text": "For example, using online GROK debugger https://grokdebug.herokuapp.com/" }, { "code": null, "e": 3442, "s": 3411, "text": "A sample error line in a log −" }, { "code": null, "e": 3641, "s": 3442, "text": "[Wed Dec 07 21:54:54.048805 2016] [:error] [pid 1234:tid 3456829102]\n [client 192.168.1.1:25007] JSP Notice: Undefined index: abc in\n /home/manu/tpworks/tutorialspoint.com/index.jsp on line 11\n" }, { "code": null, "e": 3797, "s": 3641, "text": "This GROK pattern sequence matches to the log event, which comprises of a timestamp followed by Log Level, Process Id, Transaction Id and an Error Message." }, { "code": null, "e": 3984, "s": 3797, "text": "\\[(%{DAY:day} %{MONTH:month} %{MONTHDAY} %{TIME} %{YEAR})\\] \\[.*:%{LOGLEVEL:loglevel}\\]\n \\[pid %{NUMBER:pid}:tid %{NUMBER:tid}\\] \\[client %{IP:clientip}:.*\\]\n %{GREEDYDATA:errormsg}\n" }, { "code": null, "e": 4014, "s": 3984, "text": "The output is in JSON format." }, { "code": null, "e": 4361, "s": 4014, "text": "{\n \"day\": [\n \"Wed\"\n ],\n \"month\": [\n \"Dec\"\n ],\n \"loglevel\": [\n \"error\"\n ],\n \"pid\": [\n \"1234\"\n ],\n \"tid\": [\n \"3456829102\"\n ],\n \"clientip\": [\n \"192.168.1.1\"\n ],\n \"errormsg\": [\n \"JSP Notice: Undefined index: abc in\n /home/manu/tpworks/tutorialspoint.com/index.jsp on line 11\"\n ]\n}\n" }, { "code": null, "e": 4368, "s": 4361, "text": " Print" }, { "code": null, "e": 4379, "s": 4368, "text": " Add Notes" } ]
Android | Horizontal RecyclerView with Examples - GeeksforGeeks
16 Dec, 2019 RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customized vastly while improving on the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user. For example: if a user scrolled down to a position where the items 4 and 5 are visible; items 1, 2 and 3 would be cleared from the memory to reduce memory consumption. In this article, we will learn how to create recycler view which can be scrolled in a horizontal direction. Here are the detailed steps: Step 1: Add the dependency of Recycler View widget in your projectLatest dependency for Recycler View is:implementation 'com.android.support:recyclerview-v7:28.0.0' Also add the dependency for Card View. Latest dependency for Card View is:implementation 'com.android.support:cardview-v7:28.0.0' Step 2: Setting up the activity_main.xml layout fileThe activity_main.xml layout file consists of:Relative layout which contains the recycler viewRecycler view widgetHere is complete code for activity_main.xml:activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?> <!--Relative Layout--><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.geeksforgeeks.horizontalrecyclerview.MainActivity" android:id="@+id/relativelayout"> <!--Recycler View widget--> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:scrollbars="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> </RelativeLayout>Step 3: Setting up the item.xml layout file for Recycler viewThe item.xml layout file consists of the layout for an item of Recycler View. Item Layout contains a Card View with Text view in it with some text.Here is complete code for item.xml:item.xmlitem.xml<?xml version="1.0" encoding="utf-8"?> <!--Card View widget--><android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/cardview" android:layout_width="100dp" android:layout_height="wrap_content" card_view:contentPadding="8dp" card_view:cardCornerRadius="8dp" card_view:cardElevation="8dp" card_view:cardBackgroundColor="#0F9D58" android:layout_margin="1dp" > <!--Text View over Card View--> <TextView android:id="@+id/textview" android:layout_gravity="center"' android:layout_marginTop="4dp" android:layout_marginBottom="4dp" android:textSize="22dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#fff"/> </android.support.v7.widget.CardView>Step 4: Setting up the code for Recycler View AdapterThe adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of RecylcerView. The basic methods for a successful implementation are:onCreateViewHolder,onBindViewHolder,getItemCountThe adapter is used to set data to Recycler View from Data source.Here is complete code for adapter.java:Adapter.javaAdapter.javapackage com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.widget.RecyclerView;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import android.view.LayoutInflater;import java.util.List; // The adapter class which// extends RecyclerView Adapterpublic class Adapter extends RecyclerView.Adapter<Adapter.MyView> { // List with String type private List<String> list; // View Holder class which // extends RecyclerView.ViewHolder public class MyView extends RecyclerView.ViewHolder { // Text View TextView textView; // parameterised constructor for View Holder class // which takes the view as a parameter public MyView(View view) { super(view); // initialise TextView with id textView = (TextView)view .findViewById(R.id.textview); } } // Constructor for adapter class // which takes a list of String type public Adapter(List<String> horizontalList) { this.list = horizontalList; } // Override onCreateViewHolder which deals // with the inflation of the card layout // as an item for the RecyclerView. @Override public MyView onCreateViewHolder(ViewGroup parent, int viewType) { // Inflate item.xml using LayoutInflator View itemView = LayoutInflater .from(parent.getContext()) .inflate(R.layout.item, parent, false); // return itemView return new MyView(itemView); } // Override onBindViewHolder which deals // with the setting of different data // and methods related to clicks on // particular items of the RecyclerView. @Override public void onBindViewHolder(final MyView holder, final int position) { // Set the text of each item of // Recycler view with the list items holder.textView.setText(list.get(position)); } // Override getItemCount which Returns // the length of the RecyclerView. @Override public int getItemCount() { return list.size(); }}Step 5. Setting up the code for MainActivity.java file for Recycler viewThe MainActivity contains RecyclerView. Set Layout Manager on Recycler view using LinearLayoutManager class.Here is complete code for MainActivity.java:MainActivity.javaMainActivity.javapackage com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.LinearLayoutManager;import android.view.View;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Recycler View object RecyclerView recyclerView; // Array list for recycler view data source ArrayList<String> source; // Layout Manager RecyclerView.LayoutManager RecyclerViewLayoutManager; // adapter class object Adapter adapter; // Linear Layout Manager LinearLayoutManager HorizontalLayout; View ChildView; int RecyclerViewItemPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialisation with id's recyclerView = (RecyclerView)findViewById( R.id.recyclerview); RecyclerViewLayoutManager = new LinearLayoutManager( getApplicationContext()); // Set LayoutManager on Recycler View recyclerView.setLayoutManager( RecyclerViewLayoutManager); // Adding items to RecyclerView. AddItemsToRecyclerViewArrayList(); // calling constructor of adapter // with source list as a parameter adapter = new Adapter(source); // Set Horizontal Layout Manager // for Recycler view HorizontalLayout = new LinearLayoutManager( MainActivity.this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(HorizontalLayout); // Set adapter on recycler view recyclerView.setAdapter(adapter); } // Function to add items in RecyclerView. public void AddItemsToRecyclerViewArrayList() { // Adding items to ArrayList source = new ArrayList<>(); source.add("gfg"); source.add("is"); source.add("best"); source.add("site"); source.add("for"); source.add("interview"); source.add("preparation"); }} Step 1: Add the dependency of Recycler View widget in your projectLatest dependency for Recycler View is:implementation 'com.android.support:recyclerview-v7:28.0.0' Also add the dependency for Card View. Latest dependency for Card View is:implementation 'com.android.support:cardview-v7:28.0.0' Latest dependency for Recycler View is:implementation 'com.android.support:recyclerview-v7:28.0.0' implementation 'com.android.support:recyclerview-v7:28.0.0' Also add the dependency for Card View. Latest dependency for Card View is:implementation 'com.android.support:cardview-v7:28.0.0' implementation 'com.android.support:cardview-v7:28.0.0' Step 2: Setting up the activity_main.xml layout fileThe activity_main.xml layout file consists of:Relative layout which contains the recycler viewRecycler view widgetHere is complete code for activity_main.xml:activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?> <!--Relative Layout--><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.geeksforgeeks.horizontalrecyclerview.MainActivity" android:id="@+id/relativelayout"> <!--Recycler View widget--> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:scrollbars="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> </RelativeLayout> Relative layout which contains the recycler view Recycler view widget Here is complete code for activity_main.xml: activity_main.xml <?xml version="1.0" encoding="utf-8"?> <!--Relative Layout--><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.geeksforgeeks.horizontalrecyclerview.MainActivity" android:id="@+id/relativelayout"> <!--Recycler View widget--> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:scrollbars="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> </RelativeLayout> Step 3: Setting up the item.xml layout file for Recycler viewThe item.xml layout file consists of the layout for an item of Recycler View. Item Layout contains a Card View with Text view in it with some text.Here is complete code for item.xml:item.xmlitem.xml<?xml version="1.0" encoding="utf-8"?> <!--Card View widget--><android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/cardview" android:layout_width="100dp" android:layout_height="wrap_content" card_view:contentPadding="8dp" card_view:cardCornerRadius="8dp" card_view:cardElevation="8dp" card_view:cardBackgroundColor="#0F9D58" android:layout_margin="1dp" > <!--Text View over Card View--> <TextView android:id="@+id/textview" android:layout_gravity="center"' android:layout_marginTop="4dp" android:layout_marginBottom="4dp" android:textSize="22dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#fff"/> </android.support.v7.widget.CardView> item.xml <?xml version="1.0" encoding="utf-8"?> <!--Card View widget--><android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/cardview" android:layout_width="100dp" android:layout_height="wrap_content" card_view:contentPadding="8dp" card_view:cardCornerRadius="8dp" card_view:cardElevation="8dp" card_view:cardBackgroundColor="#0F9D58" android:layout_margin="1dp" > <!--Text View over Card View--> <TextView android:id="@+id/textview" android:layout_gravity="center"' android:layout_marginTop="4dp" android:layout_marginBottom="4dp" android:textSize="22dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#fff"/> </android.support.v7.widget.CardView> Step 4: Setting up the code for Recycler View AdapterThe adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of RecylcerView. The basic methods for a successful implementation are:onCreateViewHolder,onBindViewHolder,getItemCountThe adapter is used to set data to Recycler View from Data source.Here is complete code for adapter.java:Adapter.javaAdapter.javapackage com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.widget.RecyclerView;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import android.view.LayoutInflater;import java.util.List; // The adapter class which// extends RecyclerView Adapterpublic class Adapter extends RecyclerView.Adapter<Adapter.MyView> { // List with String type private List<String> list; // View Holder class which // extends RecyclerView.ViewHolder public class MyView extends RecyclerView.ViewHolder { // Text View TextView textView; // parameterised constructor for View Holder class // which takes the view as a parameter public MyView(View view) { super(view); // initialise TextView with id textView = (TextView)view .findViewById(R.id.textview); } } // Constructor for adapter class // which takes a list of String type public Adapter(List<String> horizontalList) { this.list = horizontalList; } // Override onCreateViewHolder which deals // with the inflation of the card layout // as an item for the RecyclerView. @Override public MyView onCreateViewHolder(ViewGroup parent, int viewType) { // Inflate item.xml using LayoutInflator View itemView = LayoutInflater .from(parent.getContext()) .inflate(R.layout.item, parent, false); // return itemView return new MyView(itemView); } // Override onBindViewHolder which deals // with the setting of different data // and methods related to clicks on // particular items of the RecyclerView. @Override public void onBindViewHolder(final MyView holder, final int position) { // Set the text of each item of // Recycler view with the list items holder.textView.setText(list.get(position)); } // Override getItemCount which Returns // the length of the RecyclerView. @Override public int getItemCount() { return list.size(); }} onCreateViewHolder, onBindViewHolder, getItemCount The adapter is used to set data to Recycler View from Data source. Here is complete code for adapter.java: Adapter.java package com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.widget.RecyclerView;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import android.view.LayoutInflater;import java.util.List; // The adapter class which// extends RecyclerView Adapterpublic class Adapter extends RecyclerView.Adapter<Adapter.MyView> { // List with String type private List<String> list; // View Holder class which // extends RecyclerView.ViewHolder public class MyView extends RecyclerView.ViewHolder { // Text View TextView textView; // parameterised constructor for View Holder class // which takes the view as a parameter public MyView(View view) { super(view); // initialise TextView with id textView = (TextView)view .findViewById(R.id.textview); } } // Constructor for adapter class // which takes a list of String type public Adapter(List<String> horizontalList) { this.list = horizontalList; } // Override onCreateViewHolder which deals // with the inflation of the card layout // as an item for the RecyclerView. @Override public MyView onCreateViewHolder(ViewGroup parent, int viewType) { // Inflate item.xml using LayoutInflator View itemView = LayoutInflater .from(parent.getContext()) .inflate(R.layout.item, parent, false); // return itemView return new MyView(itemView); } // Override onBindViewHolder which deals // with the setting of different data // and methods related to clicks on // particular items of the RecyclerView. @Override public void onBindViewHolder(final MyView holder, final int position) { // Set the text of each item of // Recycler view with the list items holder.textView.setText(list.get(position)); } // Override getItemCount which Returns // the length of the RecyclerView. @Override public int getItemCount() { return list.size(); }} Step 5. Setting up the code for MainActivity.java file for Recycler viewThe MainActivity contains RecyclerView. Set Layout Manager on Recycler view using LinearLayoutManager class.Here is complete code for MainActivity.java:MainActivity.javaMainActivity.javapackage com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.LinearLayoutManager;import android.view.View;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Recycler View object RecyclerView recyclerView; // Array list for recycler view data source ArrayList<String> source; // Layout Manager RecyclerView.LayoutManager RecyclerViewLayoutManager; // adapter class object Adapter adapter; // Linear Layout Manager LinearLayoutManager HorizontalLayout; View ChildView; int RecyclerViewItemPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialisation with id's recyclerView = (RecyclerView)findViewById( R.id.recyclerview); RecyclerViewLayoutManager = new LinearLayoutManager( getApplicationContext()); // Set LayoutManager on Recycler View recyclerView.setLayoutManager( RecyclerViewLayoutManager); // Adding items to RecyclerView. AddItemsToRecyclerViewArrayList(); // calling constructor of adapter // with source list as a parameter adapter = new Adapter(source); // Set Horizontal Layout Manager // for Recycler view HorizontalLayout = new LinearLayoutManager( MainActivity.this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(HorizontalLayout); // Set adapter on recycler view recyclerView.setAdapter(adapter); } // Function to add items in RecyclerView. public void AddItemsToRecyclerViewArrayList() { // Adding items to ArrayList source = new ArrayList<>(); source.add("gfg"); source.add("is"); source.add("best"); source.add("site"); source.add("for"); source.add("interview"); source.add("preparation"); }} MainActivity.java package com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.LinearLayoutManager;import android.view.View;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Recycler View object RecyclerView recyclerView; // Array list for recycler view data source ArrayList<String> source; // Layout Manager RecyclerView.LayoutManager RecyclerViewLayoutManager; // adapter class object Adapter adapter; // Linear Layout Manager LinearLayoutManager HorizontalLayout; View ChildView; int RecyclerViewItemPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialisation with id's recyclerView = (RecyclerView)findViewById( R.id.recyclerview); RecyclerViewLayoutManager = new LinearLayoutManager( getApplicationContext()); // Set LayoutManager on Recycler View recyclerView.setLayoutManager( RecyclerViewLayoutManager); // Adding items to RecyclerView. AddItemsToRecyclerViewArrayList(); // calling constructor of adapter // with source list as a parameter adapter = new Adapter(source); // Set Horizontal Layout Manager // for Recycler view HorizontalLayout = new LinearLayoutManager( MainActivity.this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(HorizontalLayout); // Set adapter on recycler view recyclerView.setAdapter(adapter); } // Function to add items in RecyclerView. public void AddItemsToRecyclerViewArrayList() { // Adding items to ArrayList source = new ArrayList<>(); source.add("gfg"); source.add("is"); source.add("best"); source.add("site"); source.add("for"); source.add("interview"); source.add("preparation"); }} Output: android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java Multithreading in Java LinkedList in Java
[ { "code": null, "e": 25370, "s": 25342, "text": "\n16 Dec, 2019" }, { "code": null, "e": 25842, "s": 25370, "text": "RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customized vastly while improving on the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user." }, { "code": null, "e": 26010, "s": 25842, "text": "For example: if a user scrolled down to a position where the items 4 and 5 are visible; items 1, 2 and 3 would be cleared from the memory to reduce memory consumption." }, { "code": null, "e": 26118, "s": 26010, "text": "In this article, we will learn how to create recycler view which can be scrolled in a horizontal direction." }, { "code": null, "e": 26147, "s": 26118, "text": "Here are the detailed steps:" }, { "code": null, "e": 33778, "s": 26147, "text": "Step 1: Add the dependency of Recycler View widget in your projectLatest dependency for Recycler View is:implementation 'com.android.support:recyclerview-v7:28.0.0'\nAlso add the dependency for Card View. Latest dependency for Card View is:implementation 'com.android.support:cardview-v7:28.0.0'\nStep 2: Setting up the activity_main.xml layout fileThe activity_main.xml layout file consists of:Relative layout which contains the recycler viewRecycler view widgetHere is complete code for activity_main.xml:activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Relative Layout--><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"com.geeksforgeeks.horizontalrecyclerview.MainActivity\" android:id=\"@+id/relativelayout\"> <!--Recycler View widget--> <android.support.v7.widget.RecyclerView android:id=\"@+id/recyclerview\" android:scrollbars=\"horizontal\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerVertical=\"true\" android:layout_centerHorizontal=\"true\" /> </RelativeLayout>Step 3: Setting up the item.xml layout file for Recycler viewThe item.xml layout file consists of the layout for an item of Recycler View. Item Layout contains a Card View with Text view in it with some text.Here is complete code for item.xml:item.xmlitem.xml<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Card View widget--><android.support.v7.widget.CardView xmlns:card_view=\"http://schemas.android.com/apk/res-auto\" xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/cardview\" android:layout_width=\"100dp\" android:layout_height=\"wrap_content\" card_view:contentPadding=\"8dp\" card_view:cardCornerRadius=\"8dp\" card_view:cardElevation=\"8dp\" card_view:cardBackgroundColor=\"#0F9D58\" android:layout_margin=\"1dp\" > <!--Text View over Card View--> <TextView android:id=\"@+id/textview\" android:layout_gravity=\"center\"' android:layout_marginTop=\"4dp\" android:layout_marginBottom=\"4dp\" android:textSize=\"22dp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textColor=\"#fff\"/> </android.support.v7.widget.CardView>Step 4: Setting up the code for Recycler View AdapterThe adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of RecylcerView. The basic methods for a successful implementation are:onCreateViewHolder,onBindViewHolder,getItemCountThe adapter is used to set data to Recycler View from Data source.Here is complete code for adapter.java:Adapter.javaAdapter.javapackage com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.widget.RecyclerView;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import android.view.LayoutInflater;import java.util.List; // The adapter class which// extends RecyclerView Adapterpublic class Adapter extends RecyclerView.Adapter<Adapter.MyView> { // List with String type private List<String> list; // View Holder class which // extends RecyclerView.ViewHolder public class MyView extends RecyclerView.ViewHolder { // Text View TextView textView; // parameterised constructor for View Holder class // which takes the view as a parameter public MyView(View view) { super(view); // initialise TextView with id textView = (TextView)view .findViewById(R.id.textview); } } // Constructor for adapter class // which takes a list of String type public Adapter(List<String> horizontalList) { this.list = horizontalList; } // Override onCreateViewHolder which deals // with the inflation of the card layout // as an item for the RecyclerView. @Override public MyView onCreateViewHolder(ViewGroup parent, int viewType) { // Inflate item.xml using LayoutInflator View itemView = LayoutInflater .from(parent.getContext()) .inflate(R.layout.item, parent, false); // return itemView return new MyView(itemView); } // Override onBindViewHolder which deals // with the setting of different data // and methods related to clicks on // particular items of the RecyclerView. @Override public void onBindViewHolder(final MyView holder, final int position) { // Set the text of each item of // Recycler view with the list items holder.textView.setText(list.get(position)); } // Override getItemCount which Returns // the length of the RecyclerView. @Override public int getItemCount() { return list.size(); }}Step 5. Setting up the code for MainActivity.java file for Recycler viewThe MainActivity contains RecyclerView. Set Layout Manager on Recycler view using LinearLayoutManager class.Here is complete code for MainActivity.java:MainActivity.javaMainActivity.javapackage com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.LinearLayoutManager;import android.view.View;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Recycler View object RecyclerView recyclerView; // Array list for recycler view data source ArrayList<String> source; // Layout Manager RecyclerView.LayoutManager RecyclerViewLayoutManager; // adapter class object Adapter adapter; // Linear Layout Manager LinearLayoutManager HorizontalLayout; View ChildView; int RecyclerViewItemPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialisation with id's recyclerView = (RecyclerView)findViewById( R.id.recyclerview); RecyclerViewLayoutManager = new LinearLayoutManager( getApplicationContext()); // Set LayoutManager on Recycler View recyclerView.setLayoutManager( RecyclerViewLayoutManager); // Adding items to RecyclerView. AddItemsToRecyclerViewArrayList(); // calling constructor of adapter // with source list as a parameter adapter = new Adapter(source); // Set Horizontal Layout Manager // for Recycler view HorizontalLayout = new LinearLayoutManager( MainActivity.this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(HorizontalLayout); // Set adapter on recycler view recyclerView.setAdapter(adapter); } // Function to add items in RecyclerView. public void AddItemsToRecyclerViewArrayList() { // Adding items to ArrayList source = new ArrayList<>(); source.add(\"gfg\"); source.add(\"is\"); source.add(\"best\"); source.add(\"site\"); source.add(\"for\"); source.add(\"interview\"); source.add(\"preparation\"); }}" }, { "code": null, "e": 34074, "s": 33778, "text": "Step 1: Add the dependency of Recycler View widget in your projectLatest dependency for Recycler View is:implementation 'com.android.support:recyclerview-v7:28.0.0'\nAlso add the dependency for Card View. Latest dependency for Card View is:implementation 'com.android.support:cardview-v7:28.0.0'\n" }, { "code": null, "e": 34174, "s": 34074, "text": "Latest dependency for Recycler View is:implementation 'com.android.support:recyclerview-v7:28.0.0'\n" }, { "code": null, "e": 34235, "s": 34174, "text": "implementation 'com.android.support:recyclerview-v7:28.0.0'\n" }, { "code": null, "e": 34366, "s": 34235, "text": "Also add the dependency for Card View. Latest dependency for Card View is:implementation 'com.android.support:cardview-v7:28.0.0'\n" }, { "code": null, "e": 34423, "s": 34366, "text": "implementation 'com.android.support:cardview-v7:28.0.0'\n" }, { "code": null, "e": 35399, "s": 34423, "text": "Step 2: Setting up the activity_main.xml layout fileThe activity_main.xml layout file consists of:Relative layout which contains the recycler viewRecycler view widgetHere is complete code for activity_main.xml:activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Relative Layout--><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"com.geeksforgeeks.horizontalrecyclerview.MainActivity\" android:id=\"@+id/relativelayout\"> <!--Recycler View widget--> <android.support.v7.widget.RecyclerView android:id=\"@+id/recyclerview\" android:scrollbars=\"horizontal\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerVertical=\"true\" android:layout_centerHorizontal=\"true\" /> </RelativeLayout>" }, { "code": null, "e": 35448, "s": 35399, "text": "Relative layout which contains the recycler view" }, { "code": null, "e": 35469, "s": 35448, "text": "Recycler view widget" }, { "code": null, "e": 35514, "s": 35469, "text": "Here is complete code for activity_main.xml:" }, { "code": null, "e": 35532, "s": 35514, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Relative Layout--><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"com.geeksforgeeks.horizontalrecyclerview.MainActivity\" android:id=\"@+id/relativelayout\"> <!--Recycler View widget--> <android.support.v7.widget.RecyclerView android:id=\"@+id/recyclerview\" android:scrollbars=\"horizontal\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerVertical=\"true\" android:layout_centerHorizontal=\"true\" /> </RelativeLayout>", "e": 36264, "s": 35532, "text": null }, { "code": null, "e": 37423, "s": 36264, "text": "Step 3: Setting up the item.xml layout file for Recycler viewThe item.xml layout file consists of the layout for an item of Recycler View. Item Layout contains a Card View with Text view in it with some text.Here is complete code for item.xml:item.xmlitem.xml<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Card View widget--><android.support.v7.widget.CardView xmlns:card_view=\"http://schemas.android.com/apk/res-auto\" xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/cardview\" android:layout_width=\"100dp\" android:layout_height=\"wrap_content\" card_view:contentPadding=\"8dp\" card_view:cardCornerRadius=\"8dp\" card_view:cardElevation=\"8dp\" card_view:cardBackgroundColor=\"#0F9D58\" android:layout_margin=\"1dp\" > <!--Text View over Card View--> <TextView android:id=\"@+id/textview\" android:layout_gravity=\"center\"' android:layout_marginTop=\"4dp\" android:layout_marginBottom=\"4dp\" android:textSize=\"22dp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textColor=\"#fff\"/> </android.support.v7.widget.CardView>" }, { "code": null, "e": 37432, "s": 37423, "text": "item.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Card View widget--><android.support.v7.widget.CardView xmlns:card_view=\"http://schemas.android.com/apk/res-auto\" xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/cardview\" android:layout_width=\"100dp\" android:layout_height=\"wrap_content\" card_view:contentPadding=\"8dp\" card_view:cardCornerRadius=\"8dp\" card_view:cardElevation=\"8dp\" card_view:cardBackgroundColor=\"#0F9D58\" android:layout_margin=\"1dp\" > <!--Text View over Card View--> <TextView android:id=\"@+id/textview\" android:layout_gravity=\"center\"' android:layout_marginTop=\"4dp\" android:layout_marginBottom=\"4dp\" android:textSize=\"22dp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textColor=\"#fff\"/> </android.support.v7.widget.CardView>", "e": 38332, "s": 37432, "text": null }, { "code": null, "e": 41034, "s": 38332, "text": "Step 4: Setting up the code for Recycler View AdapterThe adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of RecylcerView. The basic methods for a successful implementation are:onCreateViewHolder,onBindViewHolder,getItemCountThe adapter is used to set data to Recycler View from Data source.Here is complete code for adapter.java:Adapter.javaAdapter.javapackage com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.widget.RecyclerView;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import android.view.LayoutInflater;import java.util.List; // The adapter class which// extends RecyclerView Adapterpublic class Adapter extends RecyclerView.Adapter<Adapter.MyView> { // List with String type private List<String> list; // View Holder class which // extends RecyclerView.ViewHolder public class MyView extends RecyclerView.ViewHolder { // Text View TextView textView; // parameterised constructor for View Holder class // which takes the view as a parameter public MyView(View view) { super(view); // initialise TextView with id textView = (TextView)view .findViewById(R.id.textview); } } // Constructor for adapter class // which takes a list of String type public Adapter(List<String> horizontalList) { this.list = horizontalList; } // Override onCreateViewHolder which deals // with the inflation of the card layout // as an item for the RecyclerView. @Override public MyView onCreateViewHolder(ViewGroup parent, int viewType) { // Inflate item.xml using LayoutInflator View itemView = LayoutInflater .from(parent.getContext()) .inflate(R.layout.item, parent, false); // return itemView return new MyView(itemView); } // Override onBindViewHolder which deals // with the setting of different data // and methods related to clicks on // particular items of the RecyclerView. @Override public void onBindViewHolder(final MyView holder, final int position) { // Set the text of each item of // Recycler view with the list items holder.textView.setText(list.get(position)); } // Override getItemCount which Returns // the length of the RecyclerView. @Override public int getItemCount() { return list.size(); }}" }, { "code": null, "e": 41054, "s": 41034, "text": "onCreateViewHolder," }, { "code": null, "e": 41072, "s": 41054, "text": "onBindViewHolder," }, { "code": null, "e": 41085, "s": 41072, "text": "getItemCount" }, { "code": null, "e": 41152, "s": 41085, "text": "The adapter is used to set data to Recycler View from Data source." }, { "code": null, "e": 41192, "s": 41152, "text": "Here is complete code for adapter.java:" }, { "code": null, "e": 41205, "s": 41192, "text": "Adapter.java" }, { "code": "package com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.widget.RecyclerView;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import android.view.LayoutInflater;import java.util.List; // The adapter class which// extends RecyclerView Adapterpublic class Adapter extends RecyclerView.Adapter<Adapter.MyView> { // List with String type private List<String> list; // View Holder class which // extends RecyclerView.ViewHolder public class MyView extends RecyclerView.ViewHolder { // Text View TextView textView; // parameterised constructor for View Holder class // which takes the view as a parameter public MyView(View view) { super(view); // initialise TextView with id textView = (TextView)view .findViewById(R.id.textview); } } // Constructor for adapter class // which takes a list of String type public Adapter(List<String> horizontalList) { this.list = horizontalList; } // Override onCreateViewHolder which deals // with the inflation of the card layout // as an item for the RecyclerView. @Override public MyView onCreateViewHolder(ViewGroup parent, int viewType) { // Inflate item.xml using LayoutInflator View itemView = LayoutInflater .from(parent.getContext()) .inflate(R.layout.item, parent, false); // return itemView return new MyView(itemView); } // Override onBindViewHolder which deals // with the setting of different data // and methods related to clicks on // particular items of the RecyclerView. @Override public void onBindViewHolder(final MyView holder, final int position) { // Set the text of each item of // Recycler view with the list items holder.textView.setText(list.get(position)); } // Override getItemCount which Returns // the length of the RecyclerView. @Override public int getItemCount() { return list.size(); }}", "e": 43480, "s": 41205, "text": null }, { "code": null, "e": 45982, "s": 43480, "text": "Step 5. Setting up the code for MainActivity.java file for Recycler viewThe MainActivity contains RecyclerView. Set Layout Manager on Recycler view using LinearLayoutManager class.Here is complete code for MainActivity.java:MainActivity.javaMainActivity.javapackage com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.LinearLayoutManager;import android.view.View;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Recycler View object RecyclerView recyclerView; // Array list for recycler view data source ArrayList<String> source; // Layout Manager RecyclerView.LayoutManager RecyclerViewLayoutManager; // adapter class object Adapter adapter; // Linear Layout Manager LinearLayoutManager HorizontalLayout; View ChildView; int RecyclerViewItemPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialisation with id's recyclerView = (RecyclerView)findViewById( R.id.recyclerview); RecyclerViewLayoutManager = new LinearLayoutManager( getApplicationContext()); // Set LayoutManager on Recycler View recyclerView.setLayoutManager( RecyclerViewLayoutManager); // Adding items to RecyclerView. AddItemsToRecyclerViewArrayList(); // calling constructor of adapter // with source list as a parameter adapter = new Adapter(source); // Set Horizontal Layout Manager // for Recycler view HorizontalLayout = new LinearLayoutManager( MainActivity.this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(HorizontalLayout); // Set adapter on recycler view recyclerView.setAdapter(adapter); } // Function to add items in RecyclerView. public void AddItemsToRecyclerViewArrayList() { // Adding items to ArrayList source = new ArrayList<>(); source.add(\"gfg\"); source.add(\"is\"); source.add(\"best\"); source.add(\"site\"); source.add(\"for\"); source.add(\"interview\"); source.add(\"preparation\"); }}" }, { "code": null, "e": 46000, "s": 45982, "text": "MainActivity.java" }, { "code": "package com.geeksforgeeks.horizontalrecyclerview; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.LinearLayoutManager;import android.view.View;import android.widget.Toast;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Recycler View object RecyclerView recyclerView; // Array list for recycler view data source ArrayList<String> source; // Layout Manager RecyclerView.LayoutManager RecyclerViewLayoutManager; // adapter class object Adapter adapter; // Linear Layout Manager LinearLayoutManager HorizontalLayout; View ChildView; int RecyclerViewItemPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialisation with id's recyclerView = (RecyclerView)findViewById( R.id.recyclerview); RecyclerViewLayoutManager = new LinearLayoutManager( getApplicationContext()); // Set LayoutManager on Recycler View recyclerView.setLayoutManager( RecyclerViewLayoutManager); // Adding items to RecyclerView. AddItemsToRecyclerViewArrayList(); // calling constructor of adapter // with source list as a parameter adapter = new Adapter(source); // Set Horizontal Layout Manager // for Recycler view HorizontalLayout = new LinearLayoutManager( MainActivity.this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(HorizontalLayout); // Set adapter on recycler view recyclerView.setAdapter(adapter); } // Function to add items in RecyclerView. public void AddItemsToRecyclerViewArrayList() { // Adding items to ArrayList source = new ArrayList<>(); source.add(\"gfg\"); source.add(\"is\"); source.add(\"best\"); source.add(\"site\"); source.add(\"for\"); source.add(\"interview\"); source.add(\"preparation\"); }}", "e": 48244, "s": 46000, "text": null }, { "code": null, "e": 48254, "s": 48244, "text": "Output: " }, { "code": null, "e": 48262, "s": 48254, "text": "android" }, { "code": null, "e": 48267, "s": 48262, "text": "Java" }, { "code": null, "e": 48272, "s": 48267, "text": "Java" }, { "code": null, "e": 48370, "s": 48272, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48379, "s": 48370, "text": "Comments" }, { "code": null, "e": 48392, "s": 48379, "text": "Old Comments" }, { "code": null, "e": 48422, "s": 48392, "text": "HashMap in Java with Examples" }, { "code": null, "e": 48454, "s": 48422, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 48473, "s": 48454, "text": "Interfaces in Java" }, { "code": null, "e": 48491, "s": 48473, "text": "ArrayList in Java" }, { "code": null, "e": 48523, "s": 48491, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 48547, "s": 48523, "text": "Singleton Class in Java" }, { "code": null, "e": 48567, "s": 48547, "text": "Stack Class in Java" }, { "code": null, "e": 48579, "s": 48567, "text": "Set in Java" }, { "code": null, "e": 48602, "s": 48579, "text": "Multithreading in Java" } ]
JavaFX | ImagePattern Class - GeeksforGeeks
19 Sep, 2018 ImagePattern is a part of JavaFX. This class is used to fills a shape with an image pattern. A user may specify the anchor rectangle, which defines the position, width, and height of the image relative to the upper left corner of the shape. If the shape extends out of the anchor rectangle, the image is tiled. Constructors of the class: ImagePattern(Image i): Creates a new instance of ImagePattern with the specified image.ImagePattern(Image i, double x, double y, double width, double height, boolean prop): Creates an image with specified x, y coordinate, a defined width and height and whether it is proportional or not. ImagePattern(Image i): Creates a new instance of ImagePattern with the specified image. ImagePattern(Image i, double x, double y, double width, double height, boolean prop): Creates an image with specified x, y coordinate, a defined width and height and whether it is proportional or not. Commonly Used Methods: Below programs illustrate the use of ImagePattern Class: Java Program to create a ImagePattern from a image and apply it to the rectangle: In this program we will create a ImagePattern named image_pattern from a image. Import the image using a FileInputStream. Add this image_pattern to the rectangle using the setFill() function. Create a VBox and add the rectangle to the vbox. Add the vbox to the scene and add the scene to the stage. Call the show() function to display the results.// Java Program to create a ImagePattern from// a image and apply it to the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_1 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle("Creating ImagePattern"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Input Image:Output:Java Program to create an ImagePattern form an image, set the x, y coordinate, its height and width, and whether it is proportional or not and apply it to the rectangle: In this program we will create an ImagePattern named image_pattern from an image. Import the image using a FileInputStream. Specify the x, y coordinates of the anchor rectangle, its height, width and whether it is proportional or not bypassing the values as arguments of the constructor of ImagePattern. Add this image_pattern to the rectangle using the setFill() function. Create a VBox and add the rectangle to vbox. Add the vbox to the scene and add the scene to the stage. Call the show() function to display the results.// Java Program to create an ImagePattern form an image, // set the x, y coordinate, its height and width, and // whether it is proportional or not and apply it to// the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_2 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle("Creating ImagePattern"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image, 100, 100, 100, 100, false); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Input Image:Output: Java Program to create a ImagePattern from a image and apply it to the rectangle: In this program we will create a ImagePattern named image_pattern from a image. Import the image using a FileInputStream. Add this image_pattern to the rectangle using the setFill() function. Create a VBox and add the rectangle to the vbox. Add the vbox to the scene and add the scene to the stage. Call the show() function to display the results.// Java Program to create a ImagePattern from// a image and apply it to the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_1 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle("Creating ImagePattern"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Input Image:Output: // Java Program to create a ImagePattern from// a image and apply it to the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_1 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle("Creating ImagePattern"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }} Input Image: Output: Java Program to create an ImagePattern form an image, set the x, y coordinate, its height and width, and whether it is proportional or not and apply it to the rectangle: In this program we will create an ImagePattern named image_pattern from an image. Import the image using a FileInputStream. Specify the x, y coordinates of the anchor rectangle, its height, width and whether it is proportional or not bypassing the values as arguments of the constructor of ImagePattern. Add this image_pattern to the rectangle using the setFill() function. Create a VBox and add the rectangle to vbox. Add the vbox to the scene and add the scene to the stage. Call the show() function to display the results.// Java Program to create an ImagePattern form an image, // set the x, y coordinate, its height and width, and // whether it is proportional or not and apply it to// the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_2 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle("Creating ImagePattern"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image, 100, 100, 100, 100, false); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Input Image:Output: // Java Program to create an ImagePattern form an image, // set the x, y coordinate, its height and width, and // whether it is proportional or not and apply it to// the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_2 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle("Creating ImagePattern"); // create a input stream FileInputStream input = new FileInputStream("D:\\GFG.png"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image, 100, 100, 100, 100, false); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Input Image: Output: Note: The above programs might not run in an online IDE please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/paint/ImagePattern.html JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Generics in Java Exceptions in Java Comparator Interface in Java with Examples HashMap get() Method in Java Functional Interfaces in Java StringBuilder Class in Java with Examples Strings in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n19 Sep, 2018" }, { "code": null, "e": 24259, "s": 23948, "text": "ImagePattern is a part of JavaFX. This class is used to fills a shape with an image pattern. A user may specify the anchor rectangle, which defines the position, width, and height of the image relative to the upper left corner of the shape. If the shape extends out of the anchor rectangle, the image is tiled." }, { "code": null, "e": 24286, "s": 24259, "text": "Constructors of the class:" }, { "code": null, "e": 24574, "s": 24286, "text": "ImagePattern(Image i): Creates a new instance of ImagePattern with the specified image.ImagePattern(Image i, double x, double y, double width, double height, boolean prop): Creates an image with specified x, y coordinate, a defined width and height and whether it is proportional or not." }, { "code": null, "e": 24662, "s": 24574, "text": "ImagePattern(Image i): Creates a new instance of ImagePattern with the specified image." }, { "code": null, "e": 24863, "s": 24662, "text": "ImagePattern(Image i, double x, double y, double width, double height, boolean prop): Creates an image with specified x, y coordinate, a defined width and height and whether it is proportional or not." }, { "code": null, "e": 24886, "s": 24863, "text": "Commonly Used Methods:" }, { "code": null, "e": 24943, "s": 24886, "text": "Below programs illustrate the use of ImagePattern Class:" }, { "code": null, "e": 29069, "s": 24943, "text": "Java Program to create a ImagePattern from a image and apply it to the rectangle: In this program we will create a ImagePattern named image_pattern from a image. Import the image using a FileInputStream. Add this image_pattern to the rectangle using the setFill() function. Create a VBox and add the rectangle to the vbox. Add the vbox to the scene and add the scene to the stage. Call the show() function to display the results.// Java Program to create a ImagePattern from// a image and apply it to the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_1 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle(\"Creating ImagePattern\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Input Image:Output:Java Program to create an ImagePattern form an image, set the x, y coordinate, its height and width, and whether it is proportional or not and apply it to the rectangle: In this program we will create an ImagePattern named image_pattern from an image. Import the image using a FileInputStream. Specify the x, y coordinates of the anchor rectangle, its height, width and whether it is proportional or not bypassing the values as arguments of the constructor of ImagePattern. Add this image_pattern to the rectangle using the setFill() function. Create a VBox and add the rectangle to vbox. Add the vbox to the scene and add the scene to the stage. Call the show() function to display the results.// Java Program to create an ImagePattern form an image, // set the x, y coordinate, its height and width, and // whether it is proportional or not and apply it to// the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_2 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle(\"Creating ImagePattern\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image, 100, 100, 100, 100, false); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Input Image:Output:" }, { "code": null, "e": 30904, "s": 29069, "text": "Java Program to create a ImagePattern from a image and apply it to the rectangle: In this program we will create a ImagePattern named image_pattern from a image. Import the image using a FileInputStream. Add this image_pattern to the rectangle using the setFill() function. Create a VBox and add the rectangle to the vbox. Add the vbox to the scene and add the scene to the stage. Call the show() function to display the results.// Java Program to create a ImagePattern from// a image and apply it to the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_1 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle(\"Creating ImagePattern\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Input Image:Output:" }, { "code": "// Java Program to create a ImagePattern from// a image and apply it to the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_1 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle(\"Creating ImagePattern\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}", "e": 32291, "s": 30904, "text": null }, { "code": null, "e": 32304, "s": 32291, "text": "Input Image:" }, { "code": null, "e": 32312, "s": 32304, "text": "Output:" }, { "code": null, "e": 34604, "s": 32312, "text": "Java Program to create an ImagePattern form an image, set the x, y coordinate, its height and width, and whether it is proportional or not and apply it to the rectangle: In this program we will create an ImagePattern named image_pattern from an image. Import the image using a FileInputStream. Specify the x, y coordinates of the anchor rectangle, its height, width and whether it is proportional or not bypassing the values as arguments of the constructor of ImagePattern. Add this image_pattern to the rectangle using the setFill() function. Create a VBox and add the rectangle to vbox. Add the vbox to the scene and add the scene to the stage. Call the show() function to display the results.// Java Program to create an ImagePattern form an image, // set the x, y coordinate, its height and width, and // whether it is proportional or not and apply it to// the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_2 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle(\"Creating ImagePattern\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image, 100, 100, 100, 100, false); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Input Image:Output:" }, { "code": "// Java Program to create an ImagePattern form an image, // set the x, y coordinate, its height and width, and // whether it is proportional or not and apply it to// the rectangleimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.image.*;import java.io.*;import javafx.scene.paint.*;import javafx.scene.shape.*; public class ImagePattern_2 extends Application { // launch the application public void start(Stage s) throws Exception { // set title for the stage s.setTitle(\"Creating ImagePattern\"); // create a input stream FileInputStream input = new FileInputStream(\"D:\\\\GFG.png\"); // create a image Image image = new Image(input); // create ImagePattern ImagePattern image_pattern = new ImagePattern(image, 100, 100, 100, 100, false); // create a Rectangle Rectangle rect = new Rectangle(100, 100, 200, 150); // set fill for rectangle rect.setFill(image_pattern); // create a VBox VBox vbox = new VBox(rect); // create a scene Scene sc = new Scene(vbox, 200, 200); // set the scene s.setScene(sc); s.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 36182, "s": 34604, "text": null }, { "code": null, "e": 36195, "s": 36182, "text": "Input Image:" }, { "code": null, "e": 36203, "s": 36195, "text": "Output:" }, { "code": null, "e": 36291, "s": 36203, "text": "Note: The above programs might not run in an online IDE please use an offline compiler." }, { "code": null, "e": 36383, "s": 36291, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/paint/ImagePattern.html" }, { "code": null, "e": 36390, "s": 36383, "text": "JavaFX" }, { "code": null, "e": 36395, "s": 36390, "text": "Java" }, { "code": null, "e": 36400, "s": 36395, "text": "Java" }, { "code": null, "e": 36498, "s": 36400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36507, "s": 36498, "text": "Comments" }, { "code": null, "e": 36520, "s": 36507, "text": "Old Comments" }, { "code": null, "e": 36566, "s": 36520, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 36587, "s": 36566, "text": "Constructors in Java" }, { "code": null, "e": 36602, "s": 36587, "text": "Stream In Java" }, { "code": null, "e": 36619, "s": 36602, "text": "Generics in Java" }, { "code": null, "e": 36638, "s": 36619, "text": "Exceptions in Java" }, { "code": null, "e": 36681, "s": 36638, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 36710, "s": 36681, "text": "HashMap get() Method in Java" }, { "code": null, "e": 36740, "s": 36710, "text": "Functional Interfaces in Java" }, { "code": null, "e": 36782, "s": 36740, "text": "StringBuilder Class in Java with Examples" } ]
Send Direct Message On Instagram using Selenium in Python - GeeksforGeeks
04 Jan, 2021 In this article, we will learn how we can send a direct message to users on Instagram without any manual action. We will be using the selenium module to do this task. Chrome Driver for Chrome Browser (https://chromedriver.chromium.org/) or Gecko Driver for Firefox(https://github.com/mozilla/geckodriver/releases)Selenium Package. To install this type the below command in the terminal. Chrome Driver for Chrome Browser (https://chromedriver.chromium.org/) or Gecko Driver for Firefox(https://github.com/mozilla/geckodriver/releases) Selenium Package. To install this type the below command in the terminal. pip install selenium Note: For more information, refer How to install Selenium in Python Approach: Step 1: Importing modules and entering the login information along with the username of the user whom you want to send a message. Python3 from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport selenium.common.exceptionsimport timeimport random # Login Credentialsusername = input('Enter your Username ')password = input('Enter your Password ')url = 'https://instagram.com/' + input('Enter username of user whome you want to send message') Step 2: Function to initialize Firefox or chrome session. You might need to add the path to the web driver. Chrome function, it depends on your installation. Python3 def path(): global chrome # starts a new chrome session chrome = webdriver.Chrome() # Add path if required Step 3: Function to enter the URL of the page Python3 def url_name(url): chrome.get(url) # adjust sleep if you want time.sleep(4) Step 4: Function to login to Instagram Python3 def login(username, your_password): log_but = chrome.find_element_by_class_name("L3NKy") time.sleep(2) log_but.click() time.sleep(4) # finds the username box usern = chrome.find_element_by_name("username") # sends the entered username usern.send_keys(username) # finds the password box passw = chrome.find_element_by_name("password") # sends the entered password passw.send_keys(your_password) # press enter after sending password passw.send_keys(Keys.RETURN) time.sleep(5.5) # Finding Not Now button notk = chrome.find_element_by_class_name("yWX7d") notk.click() time.sleep(3) Step 5: Find the message Button on the User profile page and then send random messages to the user Python3 def send_message(): # Find message button message = chrome.find_element_by_class_name('_862NM ') message.click() time.sleep(2) chrome.find_element_by_class_name('HoLwm ').click() time.sleep(1) l = ['hello', 'Hi', 'How are You', 'Hey', 'Bro whats up'] for x in range(10): mbox = chrome.find_element_by_tag_name('textarea') mbox.send_keys(random.choice(l)) mbox.send_keys(Keys.RETURN) time.sleep(1.2) Step 6: Calling Functions Python3 path()time.sleep(1)url_name(url)login(username, password)send_message()chrome.close() That’s it! This script will automatically send messages to your loved one. You can do a lot by modifying this script like scheduling automatic messages, sending messages to bulk users and many more. Output: UnworthyProgrammer Python Selenium-Exercises Python-selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | os.path.join() method Python | Get unique values from a list Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24318, "s": 24290, "text": "\n04 Jan, 2021" }, { "code": null, "e": 24485, "s": 24318, "text": "In this article, we will learn how we can send a direct message to users on Instagram without any manual action. We will be using the selenium module to do this task." }, { "code": null, "e": 24705, "s": 24485, "text": "Chrome Driver for Chrome Browser (https://chromedriver.chromium.org/) or Gecko Driver for Firefox(https://github.com/mozilla/geckodriver/releases)Selenium Package. To install this type the below command in the terminal." }, { "code": null, "e": 24852, "s": 24705, "text": "Chrome Driver for Chrome Browser (https://chromedriver.chromium.org/) or Gecko Driver for Firefox(https://github.com/mozilla/geckodriver/releases)" }, { "code": null, "e": 24926, "s": 24852, "text": "Selenium Package. To install this type the below command in the terminal." }, { "code": null, "e": 24949, "s": 24926, "text": "pip install selenium\n\n" }, { "code": null, "e": 25018, "s": 24949, "text": "Note: For more information, refer How to install Selenium in Python " }, { "code": null, "e": 25028, "s": 25018, "text": "Approach:" }, { "code": null, "e": 25158, "s": 25028, "text": "Step 1: Importing modules and entering the login information along with the username of the user whom you want to send a message." }, { "code": null, "e": 25166, "s": 25158, "text": "Python3" }, { "code": "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport selenium.common.exceptionsimport timeimport random # Login Credentialsusername = input('Enter your Username ')password = input('Enter your Password ')url = 'https://instagram.com/' + input('Enter username of user whome you want to send message')", "e": 25496, "s": 25166, "text": null }, { "code": null, "e": 25657, "s": 25499, "text": "Step 2: Function to initialize Firefox or chrome session. You might need to add the path to the web driver. Chrome function, it depends on your installation." }, { "code": null, "e": 25667, "s": 25659, "text": "Python3" }, { "code": "def path(): global chrome # starts a new chrome session chrome = webdriver.Chrome() # Add path if required", "e": 25800, "s": 25667, "text": null }, { "code": null, "e": 25849, "s": 25803, "text": "Step 3: Function to enter the URL of the page" }, { "code": null, "e": 25859, "s": 25851, "text": "Python3" }, { "code": "def url_name(url): chrome.get(url) # adjust sleep if you want time.sleep(4)", "e": 25941, "s": 25859, "text": null }, { "code": null, "e": 25982, "s": 25941, "text": "Step 4: Function to login to Instagram " }, { "code": null, "e": 25990, "s": 25982, "text": "Python3" }, { "code": "def login(username, your_password): log_but = chrome.find_element_by_class_name(\"L3NKy\") time.sleep(2) log_but.click() time.sleep(4) # finds the username box usern = chrome.find_element_by_name(\"username\") # sends the entered username usern.send_keys(username) # finds the password box passw = chrome.find_element_by_name(\"password\") # sends the entered password passw.send_keys(your_password) # press enter after sending password passw.send_keys(Keys.RETURN) time.sleep(5.5) # Finding Not Now button notk = chrome.find_element_by_class_name(\"yWX7d\") notk.click() time.sleep(3)", "e": 26648, "s": 25990, "text": null }, { "code": null, "e": 26750, "s": 26651, "text": "Step 5: Find the message Button on the User profile page and then send random messages to the user" }, { "code": null, "e": 26760, "s": 26752, "text": "Python3" }, { "code": "def send_message(): # Find message button message = chrome.find_element_by_class_name('_862NM ') message.click() time.sleep(2) chrome.find_element_by_class_name('HoLwm ').click() time.sleep(1) l = ['hello', 'Hi', 'How are You', 'Hey', 'Bro whats up'] for x in range(10): mbox = chrome.find_element_by_tag_name('textarea') mbox.send_keys(random.choice(l)) mbox.send_keys(Keys.RETURN) time.sleep(1.2)", "e": 27214, "s": 26760, "text": null }, { "code": null, "e": 27243, "s": 27217, "text": "Step 6: Calling Functions" }, { "code": null, "e": 27253, "s": 27245, "text": "Python3" }, { "code": "path()time.sleep(1)url_name(url)login(username, password)send_message()chrome.close()", "e": 27339, "s": 27253, "text": null }, { "code": null, "e": 27538, "s": 27339, "text": "That’s it! This script will automatically send messages to your loved one. You can do a lot by modifying this script like scheduling automatic messages, sending messages to bulk users and many more." }, { "code": null, "e": 27546, "s": 27538, "text": "Output:" }, { "code": null, "e": 27565, "s": 27546, "text": "UnworthyProgrammer" }, { "code": null, "e": 27591, "s": 27565, "text": "Python Selenium-Exercises" }, { "code": null, "e": 27607, "s": 27591, "text": "Python-selenium" }, { "code": null, "e": 27614, "s": 27607, "text": "Python" }, { "code": null, "e": 27712, "s": 27614, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27744, "s": 27712, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27800, "s": 27744, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27842, "s": 27800, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27884, "s": 27842, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27906, "s": 27884, "text": "Defaultdict in Python" }, { "code": null, "e": 27937, "s": 27906, "text": "Python | os.path.join() method" }, { "code": null, "e": 27976, "s": 27937, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28031, "s": 27976, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28060, "s": 28031, "text": "Create a directory in Python" } ]
Apache Kafka - Simple Producer Example
Let us create an application for publishing and consuming messages using a Java client. Kafka producer client consists of the following API’s. Let us understand the most important set of Kafka producer API in this section. The central part of the KafkaProducer API is KafkaProducer class. The KafkaProducer class provides an option to connect a Kafka broker in its constructor with the following methods. KafkaProducer class provides send method to send messages asynchronously to a topic. The signature of send() is as follows KafkaProducer class provides send method to send messages asynchronously to a topic. The signature of send() is as follows producer.send(new ProducerRecord<byte[],byte[]>(topic, partition, key1, value1) , callback); ProducerRecord − The producer manages a buffer of records waiting to be sent. ProducerRecord − The producer manages a buffer of records waiting to be sent. Callback − A user-supplied callback to execute when the record has been acknowl-edged by the server (null indicates no callback). Callback − A user-supplied callback to execute when the record has been acknowl-edged by the server (null indicates no callback). KafkaProducer class provides a flush method to ensure all previously sent messages have been actually completed. Syntax of the flush method is as follows − KafkaProducer class provides a flush method to ensure all previously sent messages have been actually completed. Syntax of the flush method is as follows − public void flush() KafkaProducer class provides partitionFor method, which helps in getting the partition metadata for a given topic. This can be used for custom partitioning. The signature of this method is as follows − KafkaProducer class provides partitionFor method, which helps in getting the partition metadata for a given topic. This can be used for custom partitioning. The signature of this method is as follows − public Map metrics() It returns the map of internal metrics maintained by the producer. public void close() − KafkaProducer class provides close method blocks until all previously sent requests are completed. public void close() − KafkaProducer class provides close method blocks until all previously sent requests are completed. The central part of the Producer API is Producer class. Producer class provides an option to connect Kafka broker in its constructor by the following methods. The producer class provides send method to send messages to either single or multiple topics using the following signatures. public void send(KeyedMessaget<k,v> message) - sends the data to a single topic,par-titioned by key using either sync or async producer. public void send(List<KeyedMessage<k,v>>messages) - sends data to multiple topics. Properties prop = new Properties(); prop.put(producer.type,”async”) ProducerConfig config = new ProducerConfig(prop); There are two types of producers – Sync and Async. The same API configuration applies to Sync producer as well. The difference between them is a sync producer sends messages directly, but sends messages in background. Async producer is preferred when you want a higher throughput. In the previous releases like 0.8, an async producer does not have a callback for send() to register error handlers. This is available only in the current release of 0.9. Producer class provides close method to close the producer pool connections to all Kafka bro-kers. The Producer API’s main configuration settings are listed in the following table for better under-standing − client.id identifies producer application producer.type either sync or async acks The acks config controls the criteria under producer requests are con-sidered complete. retries If producer request fails, then automatically retry with specific value. bootstrap.servers bootstrapping list of brokers. linger.ms if you want to reduce the number of requests you can set linger.ms to something greater than some value. key.serializer Key for the serializer interface. value.serializer value for the serializer interface. batch.size Buffer size. buffer.memory controls the total amount of memory available to the producer for buff-ering. ProducerRecord is a key/value pair that is sent to Kafka cluster.ProducerRecord class constructor for creating a record with partition, key and value pairs using the following signature. public ProducerRecord (string topic, int partition, k key, v value) Topic − user defined topic name that will appended to record. Topic − user defined topic name that will appended to record. Partition − partition count Partition − partition count Key − The key that will be included in the record. Key − The key that will be included in the record. Value − Record contents public ProducerRecord (string topic, k key, v value) ProducerRecord class constructor is used to create a record with key, value pairs and without partition. Topic − Create a topic to assign record. Topic − Create a topic to assign record. Key − key for the record. Key − key for the record. Value − record contents. Value − record contents. public ProducerRecord (string topic, v value) ProducerRecord class creates a record without partition and key. Topic − create a topic. Topic − create a topic. Value − record contents. Value − record contents. The ProducerRecord class methods are listed in the following table − public string topic() Topic will append to the record. public K key() Key that will be included in the record. If no such key, null will be re-turned here. public V value() Record contents. partition() Partition count for the record Before creating the application, first start ZooKeeper and Kafka broker then create your own topic in Kafka broker using create topic command. After that create a java class named Sim-pleProducer.java and type in the following coding. //import util.properties packages import java.util.Properties; //import simple producer packages import org.apache.kafka.clients.producer.Producer; //import KafkaProducer packages import org.apache.kafka.clients.producer.KafkaProducer; //import ProducerRecord packages import org.apache.kafka.clients.producer.ProducerRecord; //Create java class named “SimpleProducer” public class SimpleProducer { public static void main(String[] args) throws Exception{ // Check arguments length value if(args.length == 0){ System.out.println("Enter topic name"); return; } //Assign topicName to string variable String topicName = args[0].toString(); // create instance for properties to access producer configs Properties props = new Properties(); //Assign localhost id props.put("bootstrap.servers", “localhost:9092"); //Set acknowledgements for producer requests. props.put("acks", “all"); //If the request fails, the producer can automatically retry, props.put("retries", 0); //Specify buffer size in config props.put("batch.size", 16384); //Reduce the no of requests less than 0 props.put("linger.ms", 1); //The buffer.memory controls the total amount of memory available to the producer for buffering. props.put("buffer.memory", 33554432); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> producer = new KafkaProducer <String, String>(props); for(int i = 0; i < 10; i++) producer.send(new ProducerRecord<String, String>(topicName, Integer.toString(i), Integer.toString(i))); System.out.println(“Message sent successfully”); producer.close(); } } Compilation − The application can be compiled using the following command. javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*” *.java Execution − The application can be executed using the following command. java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*”:. SimpleProducer <topic-name> Output Message sent successfully To check the above output open new terminal and type Consumer CLI command to receive messages. >> bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic <topic-name> —from-beginning 1 2 3 4 5 6 7 8 9 10 As of now we have created a producer to send messages to Kafka cluster. Now let us create a consumer to consume messages form the Kafka cluster. KafkaConsumer API is used to consume messages from the Kafka cluster. KafkaConsumer class constructor is defined below. public KafkaConsumer(java.util.Map<java.lang.String,java.lang.Object> configs) configs − Return a map of consumer configs. KafkaConsumer class has the following significant methods that are listed in the table below. public java.util.Set<TopicPar-tition> assignment() Get the set of partitions currently assigned by the con-sumer. public string subscription() Subscribe to the given list of topics to get dynamically as-signed partitions. public void sub-scribe(java.util.List<java.lang.String> topics, ConsumerRe-balanceListener listener) Subscribe to the given list of topics to get dynamically as-signed partitions. public void unsubscribe() Unsubscribe the topics from the given list of partitions. public void sub-scribe(java.util.List<java.lang.String> topics) Subscribe to the given list of topics to get dynamically as-signed partitions. If the given list of topics is empty, it is treated the same as unsubscribe(). public void sub-scribe(java.util.regex.Pattern pattern, ConsumerRebalanceLis-tener listener) The argument pattern refers to the subscribing pattern in the format of regular expression and the listener argument gets notifications from the subscribing pattern. public void as-sign(java.util.List<TopicParti-tion> partitions) Manually assign a list of partitions to the customer. poll() Fetch data for the topics or partitions specified using one of the subscribe/assign APIs. This will return error, if the topics are not subscribed before the polling for data. public void commitSync() Commit offsets returned on the last poll() for all the sub-scribed list of topics and partitions. The same operation is applied to commitAsyn(). public void seek(TopicPartition partition, long offset) Fetch the current offset value that consumer will use on the next poll() method. public void resume() Resume the paused partitions. public void wakeup() Wakeup the consumer. The ConsumerRecord API is used to receive records from the Kafka cluster. This API consists of a topic name, partition number, from which the record is being received and an offset that points to the record in a Kafka partition. ConsumerRecord class is used to create a consumer record with specific topic name, partition count and <key, value> pairs. It has the following signature. public ConsumerRecord(string topic,int partition, long offset,K key, V value) Topic − The topic name for consumer record received from the Kafka cluster. Topic − The topic name for consumer record received from the Kafka cluster. Partition − Partition for the topic. Partition − Partition for the topic. Key − The key of the record, if no key exists null will be returned. Key − The key of the record, if no key exists null will be returned. Value − Record contents. Value − Record contents. ConsumerRecords API acts as a container for ConsumerRecord. This API is used to keep the list of ConsumerRecord per partition for a particular topic. Its Constructor is defined below. public ConsumerRecords(java.util.Map<TopicPartition,java.util.List <Consumer-Record>K,V>>> records) TopicPartition − Return a map of partition for a particular topic. TopicPartition − Return a map of partition for a particular topic. Records − Return list of ConsumerRecord. Records − Return list of ConsumerRecord. ConsumerRecords class has the following methods defined. public int count() The number of records for all the topics. public Set partitions() The set of partitions with data in this record set (if no data was returned then the set is empty). public Iterator iterator() Iterator enables you to cycle through a collection, obtaining or re-moving elements. public List records() Get list of records for the given partition. The configuration settings for the Consumer client API main configuration settings are listed below − bootstrap.servers Bootstrapping list of brokers. group.id Assigns an individual consumer to a group. enable.auto.commit Enable auto commit for offsets if the value is true, otherwise not committed. auto.commit.interval.ms Return how often updated consumed offsets are written to ZooKeeper. session.timeout.ms Indicates how many milliseconds Kafka will wait for the ZooKeeper to respond to a request (read or write) before giving up and continuing to consume messages. The producer application steps remain the same here. First, start your ZooKeeper and Kafka broker. Then create a SimpleConsumer application with the java class named SimpleCon-sumer.java and type the following code. import java.util.Properties; import java.util.Arrays; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.ConsumerRecord; public class SimpleConsumer { public static void main(String[] args) throws Exception { if(args.length == 0){ System.out.println("Enter topic name"); return; } //Kafka consumer configuration settings String topicName = args[0].toString(); Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "test"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("session.timeout.ms", "30000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer <String, String>(props); //Kafka Consumer subscribes list of topics here. consumer.subscribe(Arrays.asList(topicName)) //print the topic name System.out.println("Subscribed to topic " + topicName); int i = 0; while (true) { ConsumerRecords<String, String> records = con-sumer.poll(100); for (ConsumerRecord<String, String> record : records) // print the offset,key and value for the consumer records. System.out.printf("offset = %d, key = %s, value = %s\n", record.offset(), record.key(), record.value()); } } } Compilation − The application can be compiled using the following command. javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*” *.java Execution − The application can be executed using the following command java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*”:. SimpleConsumer <topic-name> Input − Open the producer CLI and send some messages to the topic. You can put the smple input as ‘Hello Consumer’. Output − Following will be the output. Subscribed to topic Hello-Kafka offset = 3, key = null, value = Hello Consumer 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2110, "s": 1967, "text": "Let us create an application for publishing and consuming messages using a Java client. Kafka producer client consists of the following API’s." }, { "code": null, "e": 2372, "s": 2110, "text": "Let us understand the most important set of Kafka producer API in this section. The central part of the KafkaProducer API is KafkaProducer class. The KafkaProducer class provides an option to connect a Kafka broker in its constructor with the following methods." }, { "code": null, "e": 2495, "s": 2372, "text": "KafkaProducer class provides send method to send messages asynchronously to a topic. The signature of send() is as follows" }, { "code": null, "e": 2618, "s": 2495, "text": "KafkaProducer class provides send method to send messages asynchronously to a topic. The signature of send() is as follows" }, { "code": null, "e": 2713, "s": 2618, "text": "producer.send(new ProducerRecord<byte[],byte[]>(topic, \npartition, key1, value1) , callback);\n" }, { "code": null, "e": 2791, "s": 2713, "text": "ProducerRecord − The producer manages a buffer of records waiting to be sent." }, { "code": null, "e": 2869, "s": 2791, "text": "ProducerRecord − The producer manages a buffer of records waiting to be sent." }, { "code": null, "e": 2999, "s": 2869, "text": "Callback − A user-supplied callback to execute when the record has been acknowl-edged by the server (null indicates no callback)." }, { "code": null, "e": 3129, "s": 2999, "text": "Callback − A user-supplied callback to execute when the record has been acknowl-edged by the server (null indicates no callback)." }, { "code": null, "e": 3285, "s": 3129, "text": "KafkaProducer class provides a flush method to ensure all previously sent messages have been actually completed. Syntax of the flush method is as follows −" }, { "code": null, "e": 3441, "s": 3285, "text": "KafkaProducer class provides a flush method to ensure all previously sent messages have been actually completed. Syntax of the flush method is as follows −" }, { "code": null, "e": 3462, "s": 3441, "text": "public void flush()\n" }, { "code": null, "e": 3664, "s": 3462, "text": "KafkaProducer class provides partitionFor method, which helps in getting the partition metadata for a given topic. This can be used for custom partitioning. The signature of this method is as follows −" }, { "code": null, "e": 3866, "s": 3664, "text": "KafkaProducer class provides partitionFor method, which helps in getting the partition metadata for a given topic. This can be used for custom partitioning. The signature of this method is as follows −" }, { "code": null, "e": 3888, "s": 3866, "text": "public Map metrics()\n" }, { "code": null, "e": 3955, "s": 3888, "text": "It returns the map of internal metrics maintained by the producer." }, { "code": null, "e": 4076, "s": 3955, "text": "public void close() − KafkaProducer class provides close method blocks until all previously sent requests are completed." }, { "code": null, "e": 4197, "s": 4076, "text": "public void close() − KafkaProducer class provides close method blocks until all previously sent requests are completed." }, { "code": null, "e": 4356, "s": 4197, "text": "The central part of the Producer API is Producer class. Producer class provides an option to connect Kafka broker in its constructor by the following methods." }, { "code": null, "e": 4481, "s": 4356, "text": "The producer class provides send method to send messages to either single or multiple topics using the following signatures." }, { "code": null, "e": 4820, "s": 4481, "text": "public void send(KeyedMessaget<k,v> message) \n- sends the data to a single topic,par-titioned by key using either sync or async producer.\npublic void send(List<KeyedMessage<k,v>>messages)\n- sends data to multiple topics.\nProperties prop = new Properties();\nprop.put(producer.type,”async”)\nProducerConfig config = new ProducerConfig(prop);" }, { "code": null, "e": 4871, "s": 4820, "text": "There are two types of producers – Sync and Async." }, { "code": null, "e": 5272, "s": 4871, "text": "The same API configuration applies to Sync producer as well. The difference between them is a sync producer sends messages directly, but sends messages in background. Async producer is preferred when you want a higher throughput. In the previous releases like 0.8, an async producer does not have a callback for send() to register error handlers. This is available only in the current release of 0.9." }, { "code": null, "e": 5371, "s": 5272, "text": "Producer class provides close method to close the producer pool connections to all Kafka bro-kers." }, { "code": null, "e": 5480, "s": 5371, "text": "The Producer API’s main configuration settings are listed in the following table for better under-standing −" }, { "code": null, "e": 5490, "s": 5480, "text": "client.id" }, { "code": null, "e": 5522, "s": 5490, "text": "identifies producer application" }, { "code": null, "e": 5536, "s": 5522, "text": "producer.type" }, { "code": null, "e": 5557, "s": 5536, "text": "either sync or async" }, { "code": null, "e": 5562, "s": 5557, "text": "acks" }, { "code": null, "e": 5650, "s": 5562, "text": "The acks config controls the criteria under producer requests are con-sidered complete." }, { "code": null, "e": 5658, "s": 5650, "text": "retries" }, { "code": null, "e": 5731, "s": 5658, "text": "If producer request fails, then automatically retry with specific value." }, { "code": null, "e": 5749, "s": 5731, "text": "bootstrap.servers" }, { "code": null, "e": 5780, "s": 5749, "text": "bootstrapping list of brokers." }, { "code": null, "e": 5790, "s": 5780, "text": "linger.ms" }, { "code": null, "e": 5895, "s": 5790, "text": "if you want to reduce the number of requests you can set linger.ms to something greater than some value." }, { "code": null, "e": 5910, "s": 5895, "text": "key.serializer" }, { "code": null, "e": 5944, "s": 5910, "text": "Key for the serializer interface." }, { "code": null, "e": 5961, "s": 5944, "text": "value.serializer" }, { "code": null, "e": 5997, "s": 5961, "text": "value for the serializer interface." }, { "code": null, "e": 6008, "s": 5997, "text": "batch.size" }, { "code": null, "e": 6021, "s": 6008, "text": "Buffer size." }, { "code": null, "e": 6035, "s": 6021, "text": "buffer.memory" }, { "code": null, "e": 6113, "s": 6035, "text": "controls the total amount of memory available to the producer for buff-ering." }, { "code": null, "e": 6300, "s": 6113, "text": "ProducerRecord is a key/value pair that is sent to Kafka cluster.ProducerRecord class constructor for creating a record with partition, key and value pairs using the following signature." }, { "code": null, "e": 6369, "s": 6300, "text": "public ProducerRecord (string topic, int partition, k key, v value)\n" }, { "code": null, "e": 6431, "s": 6369, "text": "Topic − user defined topic name that will appended to record." }, { "code": null, "e": 6493, "s": 6431, "text": "Topic − user defined topic name that will appended to record." }, { "code": null, "e": 6521, "s": 6493, "text": "Partition − partition count" }, { "code": null, "e": 6549, "s": 6521, "text": "Partition − partition count" }, { "code": null, "e": 6600, "s": 6549, "text": "Key − The key that will be included in the record." }, { "code": null, "e": 6651, "s": 6600, "text": "Key − The key that will be included in the record." }, { "code": null, "e": 6675, "s": 6651, "text": "Value − Record contents" }, { "code": null, "e": 6729, "s": 6675, "text": "public ProducerRecord (string topic, k key, v value)\n" }, { "code": null, "e": 6834, "s": 6729, "text": "ProducerRecord class constructor is used to create a record with key, value pairs and without partition." }, { "code": null, "e": 6875, "s": 6834, "text": "Topic − Create a topic to assign record." }, { "code": null, "e": 6916, "s": 6875, "text": "Topic − Create a topic to assign record." }, { "code": null, "e": 6942, "s": 6916, "text": "Key − key for the record." }, { "code": null, "e": 6968, "s": 6942, "text": "Key − key for the record." }, { "code": null, "e": 6993, "s": 6968, "text": "Value − record contents." }, { "code": null, "e": 7018, "s": 6993, "text": "Value − record contents." }, { "code": null, "e": 7065, "s": 7018, "text": "public ProducerRecord (string topic, v value)\n" }, { "code": null, "e": 7130, "s": 7065, "text": "ProducerRecord class creates a record without partition and key." }, { "code": null, "e": 7154, "s": 7130, "text": "Topic − create a topic." }, { "code": null, "e": 7178, "s": 7154, "text": "Topic − create a topic." }, { "code": null, "e": 7203, "s": 7178, "text": "Value − record contents." }, { "code": null, "e": 7228, "s": 7203, "text": "Value − record contents." }, { "code": null, "e": 7297, "s": 7228, "text": "The ProducerRecord class methods are listed in the following table −" }, { "code": null, "e": 7319, "s": 7297, "text": "public string topic()" }, { "code": null, "e": 7352, "s": 7319, "text": "Topic will append to the record." }, { "code": null, "e": 7367, "s": 7352, "text": "public K key()" }, { "code": null, "e": 7453, "s": 7367, "text": "Key that will be included in the record. If no such key, null will be re-turned here." }, { "code": null, "e": 7470, "s": 7453, "text": "public V value()" }, { "code": null, "e": 7487, "s": 7470, "text": "Record contents." }, { "code": null, "e": 7499, "s": 7487, "text": "partition()" }, { "code": null, "e": 7530, "s": 7499, "text": "Partition count for the record" }, { "code": null, "e": 7765, "s": 7530, "text": "Before creating the application, first start ZooKeeper and Kafka broker then create your own topic in Kafka broker using create topic command. After that create a java class named Sim-pleProducer.java and type in the following coding." }, { "code": null, "e": 9821, "s": 7765, "text": "//import util.properties packages\nimport java.util.Properties;\n\n//import simple producer packages\nimport org.apache.kafka.clients.producer.Producer;\n\n//import KafkaProducer packages\nimport org.apache.kafka.clients.producer.KafkaProducer;\n\n//import ProducerRecord packages\nimport org.apache.kafka.clients.producer.ProducerRecord;\n\n//Create java class named “SimpleProducer”\npublic class SimpleProducer {\n \n public static void main(String[] args) throws Exception{\n \n // Check arguments length value\n if(args.length == 0){\n System.out.println(\"Enter topic name\");\n return;\n }\n \n //Assign topicName to string variable\n String topicName = args[0].toString();\n \n // create instance for properties to access producer configs \n Properties props = new Properties();\n \n //Assign localhost id\n props.put(\"bootstrap.servers\", “localhost:9092\");\n \n //Set acknowledgements for producer requests. \n props.put(\"acks\", “all\");\n \n //If the request fails, the producer can automatically retry,\n props.put(\"retries\", 0);\n \n //Specify buffer size in config\n props.put(\"batch.size\", 16384);\n \n //Reduce the no of requests less than 0 \n props.put(\"linger.ms\", 1);\n \n //The buffer.memory controls the total amount of memory available to the producer for buffering. \n props.put(\"buffer.memory\", 33554432);\n \n props.put(\"key.serializer\", \n \"org.apache.kafka.common.serialization.StringSerializer\");\n \n props.put(\"value.serializer\", \n \"org.apache.kafka.common.serialization.StringSerializer\");\n \n Producer<String, String> producer = new KafkaProducer\n <String, String>(props);\n \n for(int i = 0; i < 10; i++)\n producer.send(new ProducerRecord<String, String>(topicName, \n Integer.toString(i), Integer.toString(i)));\n System.out.println(“Message sent successfully”);\n producer.close();\n }\n}" }, { "code": null, "e": 9896, "s": 9821, "text": "Compilation − The application can be compiled using the following command." }, { "code": null, "e": 9956, "s": 9896, "text": "javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*” *.java\n" }, { "code": null, "e": 10029, "s": 9956, "text": "Execution − The application can be executed using the following command." }, { "code": null, "e": 10111, "s": 10029, "text": "java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*”:. SimpleProducer <topic-name>\n" }, { "code": null, "e": 10118, "s": 10111, "text": "Output" }, { "code": null, "e": 10357, "s": 10118, "text": "Message sent successfully\nTo check the above output open new terminal and type Consumer CLI command to receive messages.\n>> bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic <topic-name> —from-beginning\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n" }, { "code": null, "e": 10622, "s": 10357, "text": "As of now we have created a producer to send messages to Kafka cluster. Now let us create a consumer to consume messages form the Kafka cluster. KafkaConsumer API is used to consume messages from the Kafka cluster. KafkaConsumer class constructor is defined below." }, { "code": null, "e": 10702, "s": 10622, "text": "public KafkaConsumer(java.util.Map<java.lang.String,java.lang.Object> configs)\n" }, { "code": null, "e": 10746, "s": 10702, "text": "configs − Return a map of consumer configs." }, { "code": null, "e": 10840, "s": 10746, "text": "KafkaConsumer class has the following significant methods that are listed in the table below." }, { "code": null, "e": 10891, "s": 10840, "text": "public java.util.Set<TopicPar-tition> assignment()" }, { "code": null, "e": 10954, "s": 10891, "text": "Get the set of partitions currently assigned by the con-sumer." }, { "code": null, "e": 10983, "s": 10954, "text": "public string subscription()" }, { "code": null, "e": 11062, "s": 10983, "text": "Subscribe to the given list of topics to get dynamically as-signed partitions." }, { "code": null, "e": 11163, "s": 11062, "text": "public void sub-scribe(java.util.List<java.lang.String> topics, ConsumerRe-balanceListener listener)" }, { "code": null, "e": 11242, "s": 11163, "text": "Subscribe to the given list of topics to get dynamically as-signed partitions." }, { "code": null, "e": 11268, "s": 11242, "text": "public void unsubscribe()" }, { "code": null, "e": 11326, "s": 11268, "text": "Unsubscribe the topics from the given list of partitions." }, { "code": null, "e": 11390, "s": 11326, "text": "public void sub-scribe(java.util.List<java.lang.String> topics)" }, { "code": null, "e": 11548, "s": 11390, "text": "Subscribe to the given list of topics to get dynamically as-signed partitions. If the given list of topics is empty, it is treated the same as unsubscribe()." }, { "code": null, "e": 11641, "s": 11548, "text": "public void sub-scribe(java.util.regex.Pattern pattern, ConsumerRebalanceLis-tener listener)" }, { "code": null, "e": 11807, "s": 11641, "text": "The argument pattern refers to the subscribing pattern in the format of regular expression and the listener argument gets notifications from the subscribing pattern." }, { "code": null, "e": 11871, "s": 11807, "text": "public void as-sign(java.util.List<TopicParti-tion> partitions)" }, { "code": null, "e": 11925, "s": 11871, "text": "Manually assign a list of partitions to the customer." }, { "code": null, "e": 11932, "s": 11925, "text": "poll()" }, { "code": null, "e": 12108, "s": 11932, "text": "Fetch data for the topics or partitions specified using one of the subscribe/assign APIs. This will return error, if the topics are not subscribed before the polling for data." }, { "code": null, "e": 12133, "s": 12108, "text": "public void commitSync()" }, { "code": null, "e": 12278, "s": 12133, "text": "Commit offsets returned on the last poll() for all the sub-scribed list of topics and partitions. The same operation is applied to commitAsyn()." }, { "code": null, "e": 12334, "s": 12278, "text": "public void seek(TopicPartition partition, long offset)" }, { "code": null, "e": 12415, "s": 12334, "text": "Fetch the current offset value that consumer will use on the next poll() method." }, { "code": null, "e": 12436, "s": 12415, "text": "public void resume()" }, { "code": null, "e": 12466, "s": 12436, "text": "Resume the paused partitions." }, { "code": null, "e": 12487, "s": 12466, "text": "public void wakeup()" }, { "code": null, "e": 12508, "s": 12487, "text": "Wakeup the consumer." }, { "code": null, "e": 12892, "s": 12508, "text": "The ConsumerRecord API is used to receive records from the Kafka cluster. This API consists of a topic name, partition number, from which the record is being received and an offset that points to the record in a Kafka partition. ConsumerRecord class is used to create a consumer record with specific topic name, partition count and <key, value> pairs. It has the following signature." }, { "code": null, "e": 12971, "s": 12892, "text": "public ConsumerRecord(string topic,int partition, long offset,K key, V value)\n" }, { "code": null, "e": 13047, "s": 12971, "text": "Topic − The topic name for consumer record received from the Kafka cluster." }, { "code": null, "e": 13123, "s": 13047, "text": "Topic − The topic name for consumer record received from the Kafka cluster." }, { "code": null, "e": 13160, "s": 13123, "text": "Partition − Partition for the topic." }, { "code": null, "e": 13197, "s": 13160, "text": "Partition − Partition for the topic." }, { "code": null, "e": 13266, "s": 13197, "text": "Key − The key of the record, if no key exists null will be returned." }, { "code": null, "e": 13335, "s": 13266, "text": "Key − The key of the record, if no key exists null will be returned." }, { "code": null, "e": 13360, "s": 13335, "text": "Value − Record contents." }, { "code": null, "e": 13385, "s": 13360, "text": "Value − Record contents." }, { "code": null, "e": 13569, "s": 13385, "text": "ConsumerRecords API acts as a container for ConsumerRecord. This API is used to keep the list of ConsumerRecord per partition for a particular topic. Its Constructor is defined below." }, { "code": null, "e": 13670, "s": 13569, "text": "public ConsumerRecords(java.util.Map<TopicPartition,java.util.List\n<Consumer-Record>K,V>>> records)\n" }, { "code": null, "e": 13737, "s": 13670, "text": "TopicPartition − Return a map of partition for a particular topic." }, { "code": null, "e": 13804, "s": 13737, "text": "TopicPartition − Return a map of partition for a particular topic." }, { "code": null, "e": 13845, "s": 13804, "text": "Records − Return list of ConsumerRecord." }, { "code": null, "e": 13886, "s": 13845, "text": "Records − Return list of ConsumerRecord." }, { "code": null, "e": 13943, "s": 13886, "text": "ConsumerRecords class has the following methods defined." }, { "code": null, "e": 13962, "s": 13943, "text": "public int count()" }, { "code": null, "e": 14004, "s": 13962, "text": "The number of records for all the topics." }, { "code": null, "e": 14028, "s": 14004, "text": "public Set partitions()" }, { "code": null, "e": 14128, "s": 14028, "text": "The set of partitions with data in this record set (if no data was returned then the set is empty)." }, { "code": null, "e": 14155, "s": 14128, "text": "public Iterator iterator()" }, { "code": null, "e": 14240, "s": 14155, "text": "Iterator enables you to cycle through a collection, obtaining or re-moving elements." }, { "code": null, "e": 14262, "s": 14240, "text": "public List records()" }, { "code": null, "e": 14307, "s": 14262, "text": "Get list of records for the given partition." }, { "code": null, "e": 14409, "s": 14307, "text": "The configuration settings for the Consumer client API main configuration settings are listed below −" }, { "code": null, "e": 14427, "s": 14409, "text": "bootstrap.servers" }, { "code": null, "e": 14458, "s": 14427, "text": "Bootstrapping list of brokers." }, { "code": null, "e": 14467, "s": 14458, "text": "group.id" }, { "code": null, "e": 14510, "s": 14467, "text": "Assigns an individual consumer to a group." }, { "code": null, "e": 14529, "s": 14510, "text": "enable.auto.commit" }, { "code": null, "e": 14607, "s": 14529, "text": "Enable auto commit for offsets if the value is true, otherwise not committed." }, { "code": null, "e": 14631, "s": 14607, "text": "auto.commit.interval.ms" }, { "code": null, "e": 14699, "s": 14631, "text": "Return how often updated consumed offsets are written to ZooKeeper." }, { "code": null, "e": 14718, "s": 14699, "text": "session.timeout.ms" }, { "code": null, "e": 14877, "s": 14718, "text": "Indicates how many milliseconds Kafka will wait for the ZooKeeper to respond to a request (read or write) before giving up and continuing to consume messages." }, { "code": null, "e": 15093, "s": 14877, "text": "The producer application steps remain the same here. First, start your ZooKeeper and Kafka broker. Then create a SimpleConsumer application with the java class named SimpleCon-sumer.java and type the following code." }, { "code": null, "e": 16820, "s": 15093, "text": "import java.util.Properties;\nimport java.util.Arrays;\nimport org.apache.kafka.clients.consumer.KafkaConsumer;\nimport org.apache.kafka.clients.consumer.ConsumerRecords;\nimport org.apache.kafka.clients.consumer.ConsumerRecord;\n\npublic class SimpleConsumer {\n public static void main(String[] args) throws Exception {\n if(args.length == 0){\n System.out.println(\"Enter topic name\");\n return;\n }\n //Kafka consumer configuration settings\n String topicName = args[0].toString();\n Properties props = new Properties();\n \n props.put(\"bootstrap.servers\", \"localhost:9092\");\n props.put(\"group.id\", \"test\");\n props.put(\"enable.auto.commit\", \"true\");\n props.put(\"auto.commit.interval.ms\", \"1000\");\n props.put(\"session.timeout.ms\", \"30000\");\n props.put(\"key.deserializer\", \n \"org.apache.kafka.common.serialization.StringDeserializer\");\n props.put(\"value.deserializer\", \n \"org.apache.kafka.common.serialization.StringDeserializer\");\n KafkaConsumer<String, String> consumer = new KafkaConsumer\n <String, String>(props);\n \n //Kafka Consumer subscribes list of topics here.\n consumer.subscribe(Arrays.asList(topicName))\n \n //print the topic name\n System.out.println(\"Subscribed to topic \" + topicName);\n int i = 0;\n \n while (true) {\n ConsumerRecords<String, String> records = con-sumer.poll(100);\n for (ConsumerRecord<String, String> record : records)\n \n // print the offset,key and value for the consumer records.\n System.out.printf(\"offset = %d, key = %s, value = %s\\n\", \n record.offset(), record.key(), record.value());\n }\n }\n}" }, { "code": null, "e": 16895, "s": 16820, "text": "Compilation − The application can be compiled using the following command." }, { "code": null, "e": 16955, "s": 16895, "text": "javac -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*” *.java\n" }, { "code": null, "e": 17027, "s": 16955, "text": "Execution − The application can be executed using the following command" }, { "code": null, "e": 17109, "s": 17027, "text": "java -cp “/path/to/kafka/kafka_2.11-0.9.0.0/lib/*”:. SimpleConsumer <topic-name>\n" }, { "code": null, "e": 17225, "s": 17109, "text": "Input − Open the producer CLI and send some messages to the topic. You can put the smple input as ‘Hello Consumer’." }, { "code": null, "e": 17264, "s": 17225, "text": "Output − Following will be the output." }, { "code": null, "e": 17344, "s": 17264, "text": "Subscribed to topic Hello-Kafka\noffset = 3, key = null, value = Hello Consumer\n" }, { "code": null, "e": 17379, "s": 17344, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 17398, "s": 17379, "text": " Arnab Chakraborty" }, { "code": null, "e": 17433, "s": 17398, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 17454, "s": 17433, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 17487, "s": 17454, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 17500, "s": 17487, "text": " Nilay Mehta" }, { "code": null, "e": 17535, "s": 17500, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 17553, "s": 17535, "text": " Bigdata Engineer" }, { "code": null, "e": 17586, "s": 17553, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 17604, "s": 17586, "text": " Bigdata Engineer" }, { "code": null, "e": 17637, "s": 17604, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 17655, "s": 17637, "text": " Bigdata Engineer" }, { "code": null, "e": 17662, "s": 17655, "text": " Print" }, { "code": null, "e": 17673, "s": 17662, "text": " Add Notes" } ]
How to flatten a list using LINQ C#?
Flattening a list means converting a List<List<T>> to List<T>. For example, let us consider a List<List<int>> which needs to be converted to List<int>. The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result. Live Demo using System; using System.Collections.Generic; using System.Linq; namespace DemoApplication{ public class Program{ static void Main(string[] args){ List<List<int>> listOfNumLists = new List<List<int>>{ new List<int>{ 1, 2 }, new List<int>{ 3, 4 } }; var numList = listOfNumLists.SelectMany(i => i); Console.WriteLine("Numbers in the list:"); foreach(var num in numList){ Console.WriteLine(num); } Console.ReadLine(); } } } Numbers in the list: 1 2 3 4 Live Demo using System; using System.Collections.Generic; using System.Linq; namespace DemoApplication{ public class Program{ static void Main(string[] args){ List<List<int>> listOfNumLists = new List<List<int>>{ new List<int>{ 1, 2 }, new List<int>{ 3, 4 } }; var numList = from listOfNumList in listOfNumLists from value in listOfNumList select value; Console.WriteLine("Numbers in the list:"); foreach(var num in numList){ Console.WriteLine(num); } Console.ReadLine(); } } } Numbers in the list: 1 2 3 4
[ { "code": null, "e": 1214, "s": 1062, "text": "Flattening a list means converting a List<List<T>> to List<T>. For example, let us\nconsider a List<List<int>> which needs to be converted to List<int>." }, { "code": null, "e": 1485, "s": 1214, "text": "The SelectMany in LINQ is used to project each element of a sequence to an\nIEnumerable<T> and then flatten the resulting sequences into one sequence. That\nmeans the SelectMany operator combines the records from a sequence of results and\nthen converts it into one result." }, { "code": null, "e": 1496, "s": 1485, "text": " Live Demo" }, { "code": null, "e": 2091, "s": 1496, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace DemoApplication{\n public class Program{\n static void Main(string[] args){\n List<List<int>> listOfNumLists = new List<List<int>>{\n new List<int>{\n 1, 2\n },\n new List<int>{\n 3, 4\n }\n };\n var numList = listOfNumLists.SelectMany(i => i);\n Console.WriteLine(\"Numbers in the list:\");\n foreach(var num in numList){\n Console.WriteLine(num);\n }\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2120, "s": 2091, "text": "Numbers in the list:\n1\n2\n3\n4" }, { "code": null, "e": 2131, "s": 2120, "text": " Live Demo" }, { "code": null, "e": 2788, "s": 2131, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace DemoApplication{\n public class Program{\n static void Main(string[] args){\n List<List<int>> listOfNumLists = new List<List<int>>{\n new List<int>{\n 1, 2\n },\n new List<int>{\n 3, 4\n }\n };\n var numList = from listOfNumList in listOfNumLists\n from value in listOfNumList\n select value;\n Console.WriteLine(\"Numbers in the list:\");\n foreach(var num in numList){\n Console.WriteLine(num);\n }\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2817, "s": 2788, "text": "Numbers in the list:\n1\n2\n3\n4" } ]
How to create pagination text in Android using Kotlin?
This example demonstrates how to create pagination text in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="16dp" android:paddingTop="16dp" android:paddingRight="16dp" android:paddingBottom="16dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/buttonBack" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" /> <Button android:id="@+id/buttonForward" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@android:color/transparent" /> </LinearLayout> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.text.Html import android.text.Spannable import android.text.SpannableString import android.text.TextUtils import android.text.style.ForegroundColorSpan import android.text.style.RelativeSizeSpan import android.text.style.StyleSpan import android.view.ViewTreeObserver import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var buttonBack: Button lateinit var buttonForward: Button private lateinit var textView: TextView private var pagination: Pagination? = null private lateinit var charSequence: CharSequence private var currentIndex = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" buttonBack = findViewById(R.id.buttonBack) buttonForward = findViewById(R.id.buttonForward) textView = findViewById(R.id.tv) val htmlString = Html.fromHtml(getString(R.string.html_string)) val spanString = SpannableString(getString(R.string.long_string)) spanString.setSpan(ForegroundColorSpan(Color.BLUE), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(RelativeSizeSpan(2f), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(StyleSpan(Typeface.MONOSPACE.style), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(ForegroundColorSpan(Color.BLUE), 536, spanString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(RelativeSizeSpan(2f), 536, spanString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(StyleSpan(Typeface.MONOSPACE.style), 536, spanString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) charSequence = TextUtils.concat(htmlString, spanString) textView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { // Removing layout listener to avoid multiple calls textView.viewTreeObserver.removeOnGlobalLayoutListener(this) pagination = Pagination( charSequence, textView.width, textView.height, textView.paint, textView.lineSpacingMultiplier, textView.lineSpacingExtra, textView.includeFontPadding ) update() } }) buttonBack.setOnClickListener { currentIndex = if ((currentIndex > 0)) currentIndex - 1 else 0 update() } buttonForward.setOnClickListener { currentIndex = if ((currentIndex <pagination!!.size() - 1)) currentIndex + 1 else pagination!!.size() - 1 update() } } private fun update() { val text = pagination!![currentIndex] if (text != null) textView.text = text } } Step 4 − Create a Kotlin class and add the following code − import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.text.Html import android.text.Spannable import android.text.SpannableString import android.text.TextUtils import android.text.style.ForegroundColorSpan import android.text.style.RelativeSizeSpan import android.text.style.StyleSpan import android.view.ViewTreeObserver import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var buttonBack: Button lateinit var buttonForward: Button private lateinit var textView: TextView private var pagination: Pagination? = null private lateinit var charSequence: CharSequence private var currentIndex = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" buttonBack = findViewById(R.id.buttonBack) buttonForward = findViewById(R.id.buttonForward) textView = findViewById(R.id.tv) val htmlString = Html.fromHtml(getString(R.string.html_string)) val spanString = SpannableString(getString(R.string.long_string)) spanString.setSpan(ForegroundColorSpan(Color.BLUE), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(RelativeSizeSpan(2f), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(StyleSpan(Typeface.MONOSPACE.style), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(ForegroundColorSpan(Color.BLUE), 536, spanString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(RelativeSizeSpan(2f), 536, spanString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spanString.setSpan(StyleSpan(Typeface.MONOSPACE.style), 536, spanString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) charSequence = TextUtils.concat(htmlString, spanString) textView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { // Removing layout listener to avoid multiple calls textView.viewTreeObserver.removeOnGlobalLayoutListener(this) pagination = Pagination( charSequence, textView.width, textView.height, textView.paint, textView.lineSpacingMultiplier, textView.lineSpacingExtra, textView.includeFontPadding ) update() } }) buttonBack.setOnClickListener { currentIndex = if ((currentIndex > 0)) currentIndex - 1 else 0 update() } buttonForward.setOnClickListener { currentIndex = if ((currentIndex < pagination!!.size() - 1)) currentIndex + 1 else pagination!!.size() - 1 update() } } private fun update() { val text = pagination!![currentIndex] if (text != null) textView.text = text } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
[ { "code": null, "e": 1143, "s": 1062, "text": "This example demonstrates how to create pagination text in Android using Kotlin." }, { "code": null, "e": 1272, "s": 1143, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1337, "s": 1272, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2444, "s": 1337, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingLeft=\"16dp\"\n android:paddingTop=\"16dp\"\n android:paddingRight=\"16dp\"\n android:paddingBottom=\"16dp\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <Button\n android:id=\"@+id/buttonBack\"\n style=\"?android:attr/buttonBarButtonStyle\"\n android:layout_width=\"0dp\"\n android:layout_height=\"match_parent\"\n android:layout_weight=\"1\"\n android:background=\"@android:color/transparent\" />\n <Button\n android:id=\"@+id/buttonForward\"\n style=\"?android:attr/buttonBarButtonStyle\"\n android:layout_width=\"0dp\"\n android:layout_height=\"match_parent\"\n android:layout_weight=\"1\"\n android:background=\"@android:color/transparent\" />\n </LinearLayout>\n <TextView\n android:id=\"@+id/tv\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</RelativeLayout>" }, { "code": null, "e": 2499, "s": 2444, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 5488, "s": 2499, "text": "import android.graphics.Color\nimport android.graphics.Typeface\nimport android.os.Bundle\nimport android.text.Html\nimport android.text.Spannable\nimport android.text.SpannableString\nimport android.text.TextUtils\nimport android.text.style.ForegroundColorSpan\nimport android.text.style.RelativeSizeSpan\nimport android.text.style.StyleSpan\nimport android.view.ViewTreeObserver\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var buttonBack: Button\n lateinit var buttonForward: Button\n private lateinit var textView: TextView\n private var pagination: Pagination? = null\n private lateinit var charSequence: CharSequence\n private var currentIndex = 0\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n buttonBack = findViewById(R.id.buttonBack)\n buttonForward = findViewById(R.id.buttonForward)\n textView = findViewById(R.id.tv)\n val htmlString = Html.fromHtml(getString(R.string.html_string))\n val spanString = SpannableString(getString(R.string.long_string))\n spanString.setSpan(ForegroundColorSpan(Color.BLUE), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(RelativeSizeSpan(2f), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(StyleSpan(Typeface.MONOSPACE.style), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(ForegroundColorSpan(Color.BLUE), 536, spanString.length,\nSpannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(RelativeSizeSpan(2f), 536, spanString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(StyleSpan(Typeface.MONOSPACE.style), 536, spanString.length,\nSpannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n charSequence = TextUtils.concat(htmlString, spanString)\n textView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {\n override fun onGlobalLayout() {\n // Removing layout listener to avoid multiple calls\n textView.viewTreeObserver.removeOnGlobalLayoutListener(this)\n pagination = Pagination(\n charSequence, textView.width,\n textView.height,\n textView.paint,\n textView.lineSpacingMultiplier,\n textView.lineSpacingExtra,\n textView.includeFontPadding\n )\n update()\n }\n })\n buttonBack.setOnClickListener {\n currentIndex = if ((currentIndex > 0)) currentIndex - 1 else 0\n update()\n }\n buttonForward.setOnClickListener {\n currentIndex = if ((currentIndex <pagination!!.size() - 1)) currentIndex + 1 else pagination!!.size() - 1\n update()\n }\n }\n private fun update() {\n val text = pagination!![currentIndex]\n if (text != null) textView.text = text\n }\n}" }, { "code": null, "e": 5548, "s": 5488, "text": "Step 4 − Create a Kotlin class and add the following code −" }, { "code": null, "e": 8544, "s": 5548, "text": "import android.graphics.Color\nimport android.graphics.Typeface\nimport android.os.Bundle\nimport android.text.Html\nimport android.text.Spannable\nimport android.text.SpannableString\nimport android.text.TextUtils\nimport android.text.style.ForegroundColorSpan\nimport android.text.style.RelativeSizeSpan\nimport android.text.style.StyleSpan\nimport android.view.ViewTreeObserver\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var buttonBack: Button\n lateinit var buttonForward: Button\n private lateinit var textView: TextView\n private var pagination: Pagination? = null\n private lateinit var charSequence: CharSequence\n private var currentIndex = 0\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n buttonBack = findViewById(R.id.buttonBack)\n buttonForward = findViewById(R.id.buttonForward)\n textView = findViewById(R.id.tv)\n val htmlString = Html.fromHtml(getString(R.string.html_string))\n val spanString = SpannableString(getString(R.string.long_string))\n spanString.setSpan(ForegroundColorSpan(Color.BLUE), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(RelativeSizeSpan(2f), 0, 24, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(StyleSpan(Typeface.MONOSPACE.style), 0, 24,\nSpannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(ForegroundColorSpan(Color.BLUE), 536, spanString.length,\nSpannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(RelativeSizeSpan(2f), 536, spanString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n spanString.setSpan(StyleSpan(Typeface.MONOSPACE.style), 536, spanString.length,\nSpannable.SPAN_EXCLUSIVE_EXCLUSIVE)\n charSequence = TextUtils.concat(htmlString, spanString)\n textView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {\n override fun onGlobalLayout() {\n // Removing layout listener to avoid multiple calls\n textView.viewTreeObserver.removeOnGlobalLayoutListener(this)\n pagination = Pagination(\n charSequence, textView.width,\n textView.height,\n textView.paint,\n textView.lineSpacingMultiplier,\n textView.lineSpacingExtra,\n textView.includeFontPadding\n )\n update()\n }\n })\n buttonBack.setOnClickListener {\n currentIndex = if ((currentIndex > 0)) currentIndex - 1 else 0\n update()\n }\n buttonForward.setOnClickListener {\n currentIndex = if ((currentIndex < pagination!!.size() - 1)) currentIndex + 1 else pagination!!.size() - 1\n update()\n }\n }\n private fun update() {\n val text = pagination!![currentIndex]\n if (text != null) textView.text = text\n }\n}" }, { "code": null, "e": 8599, "s": 8544, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 9273, "s": 8599, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 9623, "s": 9273, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." } ]
MathF.Cbrt() Method in C# with Examples - GeeksforGeeks
28 Oct, 2019 MathF.Cbrt(Single) Method is used to return the cube root of a floating point value. Syntax: public static float Cbrt (float x);Here, it takes a standard floating point number. Return Value: This method returns the cube root of the given value. Example 1: // C# program to demonstrate the// MathF.Cbrt(Single) Methodusing System; class GFG { // Main Method public static void Main() { // Declaring and initializing value float value = 27f; // getting cube root of value // using Cbrt() method float round = MathF.Cbrt(value); // Display the value Console.WriteLine("Cube root of {0} is {1}", value, round); }} Cube root of 27 is 3 Example 2: // C# program to demonstrate the// MathF.Cbrt(Single) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method Console.WriteLine("Cube root of given "+ "numbers are respectively"); get(8f); get(27.8967f); get(64f); get(125.2534f); } // defining get() method public static void get(float value) { // getting cube root of given value // using Cbrt() method float round = MathF.Cbrt(value); // Display the value Console.WriteLine("Cube root of {0} is {1}", value, round); }} Cube root of given numbers are respectively Cube root of 8 is 2 Cube root of 27.8967 is 3.03285 Cube root of 64 is 4 Cube root of 125.2534 is 5.003376 Akanksha_Rai CSharp-MathF-Class CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | Inheritance C# | List Class Partial Classes in C# Convert String to Character Array in C# Lambda Expressions in C# Linked List Implementation in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n28 Oct, 2019" }, { "code": null, "e": 24387, "s": 24302, "text": "MathF.Cbrt(Single) Method is used to return the cube root of a floating point value." }, { "code": null, "e": 24479, "s": 24387, "text": "Syntax: public static float Cbrt (float x);Here, it takes a standard floating point number." }, { "code": null, "e": 24547, "s": 24479, "text": "Return Value: This method returns the cube root of the given value." }, { "code": null, "e": 24558, "s": 24547, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// MathF.Cbrt(Single) Methodusing System; class GFG { // Main Method public static void Main() { // Declaring and initializing value float value = 27f; // getting cube root of value // using Cbrt() method float round = MathF.Cbrt(value); // Display the value Console.WriteLine(\"Cube root of {0} is {1}\", value, round); }}", "e": 25018, "s": 24558, "text": null }, { "code": null, "e": 25040, "s": 25018, "text": "Cube root of 27 is 3\n" }, { "code": null, "e": 25051, "s": 25040, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// MathF.Cbrt(Single) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method Console.WriteLine(\"Cube root of given \"+ \"numbers are respectively\"); get(8f); get(27.8967f); get(64f); get(125.2534f); } // defining get() method public static void get(float value) { // getting cube root of given value // using Cbrt() method float round = MathF.Cbrt(value); // Display the value Console.WriteLine(\"Cube root of {0} is {1}\", value, round); }}", "e": 25756, "s": 25051, "text": null }, { "code": null, "e": 25908, "s": 25756, "text": "Cube root of given numbers are respectively\nCube root of 8 is 2\nCube root of 27.8967 is 3.03285\nCube root of 64 is 4\nCube root of 125.2534 is 5.003376\n" }, { "code": null, "e": 25921, "s": 25908, "text": "Akanksha_Rai" }, { "code": null, "e": 25940, "s": 25921, "text": "CSharp-MathF-Class" }, { "code": null, "e": 25954, "s": 25940, "text": "CSharp-method" }, { "code": null, "e": 25957, "s": 25954, "text": "C#" }, { "code": null, "e": 26055, "s": 25957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26064, "s": 26055, "text": "Comments" }, { "code": null, "e": 26077, "s": 26064, "text": "Old Comments" }, { "code": null, "e": 26100, "s": 26077, "text": "Extension Method in C#" }, { "code": null, "e": 26128, "s": 26100, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26168, "s": 26128, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26211, "s": 26168, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26228, "s": 26211, "text": "C# | Inheritance" }, { "code": null, "e": 26244, "s": 26228, "text": "C# | List Class" }, { "code": null, "e": 26266, "s": 26244, "text": "Partial Classes in C#" }, { "code": null, "e": 26306, "s": 26266, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 26331, "s": 26306, "text": "Lambda Expressions in C#" } ]
Building an AI Bot to Play Rock, Paper, Scissors | by Darren Broderick (DBro) | Towards Data Science
AI Bot Name: JankenTechnology Used: TensorFlow, Keras, Numpy, SqueezeNet & Open CV TL;DR If you want to get running you can go straight to my GitHub and clone.https://github.com/DarrenBro/rock-paper-scissors-aiThere are detailed instructions you can follow on the Readme. In the Github project, I’ve included model examples, dependencies for the project, SqueezeNet models(will mention later on) and test images. I’ve tried to make it as minimal as possible to get started even if you’ve never worked with ML or python before. The rest of this article will focus on the 4 steps that made Janken; Gathering the data(what seemed appropriate)SqueezeNet and training a Neural NetworkTesting the ModelPlay the game! Gathering the data(what seemed appropriate) SqueezeNet and training a Neural Network Testing the Model Play the game! Gathering the data — what seemed appropriate We want to collect 4 types of images (Rock, Paper, Scissors & Background/Noise) and map them as our input labels. We just need them indexed. In machine learning, when a dataset with correct answers is available, it can looked at as a form of super-supervised learning. This form of training is “Image Classification” and as we know the correct labels, Janken falls under Supervised Image Classification. So we want 100s of images across each category, this requires a bit of work on our end but we reduce the heavy lifting with a simple open CV script to collect all these images in seconds. Things to watch out for. Keeping all input shapes consistentYou can easily get caught up in errors like below if have inconsistent data. shapes. ValueError: Error when checking: expected squeezenet_input to have shape (None, 300, 300, 3) but got array with shape (1, 227, 227, 3). So having something like my diagram above size, capture and then store your data you can automate and collect 100s of images in seconds. Remove Bias A huge area in ML is having a model that has good generalisation. Is the diversity of data good enough to train with? 100s of images of just my own hand will likely have trouble identifying anything other than me as a player. My temporary solution was too used a gloved hand to encourage the CNN to focus on the features of the gesture. I then extended this by reaching out and gathering images from the Quantum unit and train to keep my bias down further. An Improvement idea — Keep all trained images black and white and convert game images also to BW colour. One last thing to note; as I’m angling my hand during image capturing, some came out blurred through the motion. It was important to clean those out by removal as they will only serve to confuse the model to identify static imagery as it would during gameplay. Noise Pollution / Lighting‘Noise’ meaning background or anything other than a hand playing a gesture. One point on this was the trouble I had keeping Janken from recognising nothing was played yet and it would skip between predictions. So keeping a stable background in training was not the best choice, I could have mixed in more contrast, shading, posters, doors, just more natural house and office items into the data. SqueezeNet and training a Neural Network There is a lot to be said here, I added lots of comments into the code in my GitHub (linked at top and bottom), the file to focus on here is called “train_model.py”. KerasEverything revolves around keras for this project, it is a Python API for Deep Learning. Lets have our label inputs map to index values as that’s how the NN will identify them. INPUT_LABELS = { "rock": 0, "paper": 1, "scissors": 2, "noise": 3} After that I decided to go the ‘Sequential Model’. A design that allows a simple 1–1 mapping, in ML terms it’s allowing layers that take in 1 input tensor and create 1 output tensor. For example, sequential allows the Neural Network (NN) to identity a paper image as value of 1. model = Sequential([ SqueezeNet(input_shape=(300, 300, 3), include_top=False), Dropout(0.2), Convolution2D(LABELS_COUNT, (1, 1), padding='valid'), Activation('relu'), GlobalAveragePooling2D(), Activation('softmax') Above is our model definition, the heart of Janken and this is all the architecture designing we’ll need to do, most of the work is around collecting, cleaning and shaping the data before we compile and fit the model. I will talk about ‘SqueezeNet’ shortly. Everything else below is considered a layer (keras.layers), they’re all important so let’s take a minute to explain each. Dropout added to reduce overfitting, 0.2 = 20%, so throughout the training process drop 1/5 of what the resultant to keep the model learning new approaches and not become stale. It’s not unusual to see this as high as 50%. Convolution2D controls the size of the layer by the first argument LABELS_COUNT which will be 4 in total, (3 gestures + noise) label. It is appended to the already defined neural network ‘SqueezeNet’. Activation (ReLU) Rectified Linear Unit turns negative values into 0 and outputs positive values. Why? An Activation function is responsible for taking inputs and assigning weights to output nodes, a model can’t coordinate itself well with negative values, it becomes un-uniform in the sense of how we expect the model to perform. f(x) = max{0, x} => The output of a ReLU unit is non-negative. Returning x, if less than zero then max returns 0. ReLU has become the default activation function for many types of neural networks because a model that uses ReLU is easier to train and often achieves better performance and good model convergence. It’s not be all end all, it can cause a problem called “dying ReLU” if you are returning too many negatives you’ll not want them all turned 0 but return in a negative linear fashion. Search for “Leaky ReLU” if you’re interested in learning more. GlobalAveragePooling2D performs classification and calculates average output of each feature map in previous layer.i.e data reduction layer, prepares model for Activation(‘softmax’). Activation (softmax) gives probabilities of each hand sign.We have a 4 image class (problem), ‘softmax’ handles multi-class, anything more than 2. SqueezeNet It is a pre-built neural network for image classification, meaning we can focus on it’s extension for our purpose to build Janken which is enough work in itself than the added effort to create a neural network from scratch. The training time alone for that could be days. Bonuses you get with SqueezeNet; Smaller Convolutional Neural Networks (CNNs) require less communication across servers during distributed training.Less bandwidth to export a new model.Smaller CNNs are more feasible to deploy and uses less memory. Smaller Convolutional Neural Networks (CNNs) require less communication across servers during distributed training. Less bandwidth to export a new model. Smaller CNNs are more feasible to deploy and uses less memory. To re-visit the line of code from the training script. SqueezeNet(input_shape=(300, 300, 3), include_top=False) # input_shape is an image size of 300 x 300 pixels. 3 is for RGB colour range. # include_top lets you select if you want a final dense layer or not. # Dense layers are capable of interpreting found patterns in order to classify images.e.g. this image contains rock. # Set to False as we have labeled what rock data looks like already. The convolutional layers work as feature extractors. They identify a series of patterns in the image, and each layer can identify more elaborate patterns by seeing patterns of patterns. Note on the weights: The weights in a convolutional layer are fixed-size. A convolutional layer doesn’t care about the size of the input image. It just does the training and presents a resulting image based on the same size of the input image. The weights in a dense layer are totally dependent on the input size. It’s one weight per element of the input. So this demands that your input be always the same size, or else you won’t have proper learned weights. Because of this, setting the final dense layer to false allows you to define the input size (300 x 300). (And the output size will increase/decrease accordingly). Testing the model In the script “test_model” you can see model predictions on images you’ve already processed or new images the model has never seen before. The script handles any new image you want to provide as it will reshape to 300x300 using open CV. Play the game! Predictions on Janken’s play resultI imagined the prediction Janken would make will “flicker” a lot as a moving camera image will always be provide different inputs to analyse and run the model against. Lighting will play a big part so I tried to split my dataset and collect images at different times of the day. Static backgrounds or controls to freeze the image will help make more stable gesture predictions. How did it play out? Janken wasn’t made with lockdown in mind so an ‘elegant’... solution was made to play others through the mac’s webcam onto a shared screen with another player on the monitor. However Janken could only ever beat me constantly, it was able to win 50% of played gestures from other players through the monitor but I suspected the nature of camera imagery and processing made it difficult for Janken to probably make out all gestures. To improve the model I should have gathered images from the the users side through my webcam to give Janken more generalisation. Overall I really enjoyed everything I learnt and there wasn’t a tech used in this project that I was familiar with. Was great to turn the learnings into a game. Finally I added some user controls that hopefully adds to the experience with a best of 3 game counter.The key instructions are along the grey header. Peace Out! Resources Full code GitHub link github.com Keras API : Keras API reference Keras documentationkeras.io SqueezeNet Info towardsdatascience.com arxiv.org O’Reilly (TensorFlow and Keras)
[ { "code": null, "e": 254, "s": 171, "text": "AI Bot Name: JankenTechnology Used: TensorFlow, Keras, Numpy, SqueezeNet & Open CV" }, { "code": null, "e": 260, "s": 254, "text": "TL;DR" }, { "code": null, "e": 443, "s": 260, "text": "If you want to get running you can go straight to my GitHub and clone.https://github.com/DarrenBro/rock-paper-scissors-aiThere are detailed instructions you can follow on the Readme." }, { "code": null, "e": 584, "s": 443, "text": "In the Github project, I’ve included model examples, dependencies for the project, SqueezeNet models(will mention later on) and test images." }, { "code": null, "e": 698, "s": 584, "text": "I’ve tried to make it as minimal as possible to get started even if you’ve never worked with ML or python before." }, { "code": null, "e": 767, "s": 698, "text": "The rest of this article will focus on the 4 steps that made Janken;" }, { "code": null, "e": 882, "s": 767, "text": "Gathering the data(what seemed appropriate)SqueezeNet and training a Neural NetworkTesting the ModelPlay the game!" }, { "code": null, "e": 926, "s": 882, "text": "Gathering the data(what seemed appropriate)" }, { "code": null, "e": 967, "s": 926, "text": "SqueezeNet and training a Neural Network" }, { "code": null, "e": 985, "s": 967, "text": "Testing the Model" }, { "code": null, "e": 1000, "s": 985, "text": "Play the game!" }, { "code": null, "e": 1045, "s": 1000, "text": "Gathering the data — what seemed appropriate" }, { "code": null, "e": 1186, "s": 1045, "text": "We want to collect 4 types of images (Rock, Paper, Scissors & Background/Noise) and map them as our input labels. We just need them indexed." }, { "code": null, "e": 1449, "s": 1186, "text": "In machine learning, when a dataset with correct answers is available, it can looked at as a form of super-supervised learning. This form of training is “Image Classification” and as we know the correct labels, Janken falls under Supervised Image Classification." }, { "code": null, "e": 1637, "s": 1449, "text": "So we want 100s of images across each category, this requires a bit of work on our end but we reduce the heavy lifting with a simple open CV script to collect all these images in seconds." }, { "code": null, "e": 1662, "s": 1637, "text": "Things to watch out for." }, { "code": null, "e": 1782, "s": 1662, "text": "Keeping all input shapes consistentYou can easily get caught up in errors like below if have inconsistent data. shapes." }, { "code": null, "e": 1918, "s": 1782, "text": "ValueError: Error when checking: expected squeezenet_input to have shape (None, 300, 300, 3) but got array with shape (1, 227, 227, 3)." }, { "code": null, "e": 2055, "s": 1918, "text": "So having something like my diagram above size, capture and then store your data you can automate and collect 100s of images in seconds." }, { "code": null, "e": 2067, "s": 2055, "text": "Remove Bias" }, { "code": null, "e": 2133, "s": 2067, "text": "A huge area in ML is having a model that has good generalisation." }, { "code": null, "e": 2293, "s": 2133, "text": "Is the diversity of data good enough to train with? 100s of images of just my own hand will likely have trouble identifying anything other than me as a player." }, { "code": null, "e": 2404, "s": 2293, "text": "My temporary solution was too used a gloved hand to encourage the CNN to focus on the features of the gesture." }, { "code": null, "e": 2524, "s": 2404, "text": "I then extended this by reaching out and gathering images from the Quantum unit and train to keep my bias down further." }, { "code": null, "e": 2629, "s": 2524, "text": "An Improvement idea — Keep all trained images black and white and convert game images also to BW colour." }, { "code": null, "e": 2890, "s": 2629, "text": "One last thing to note; as I’m angling my hand during image capturing, some came out blurred through the motion. It was important to clean those out by removal as they will only serve to confuse the model to identify static imagery as it would during gameplay." }, { "code": null, "e": 3312, "s": 2890, "text": "Noise Pollution / Lighting‘Noise’ meaning background or anything other than a hand playing a gesture. One point on this was the trouble I had keeping Janken from recognising nothing was played yet and it would skip between predictions. So keeping a stable background in training was not the best choice, I could have mixed in more contrast, shading, posters, doors, just more natural house and office items into the data." }, { "code": null, "e": 3353, "s": 3312, "text": "SqueezeNet and training a Neural Network" }, { "code": null, "e": 3519, "s": 3353, "text": "There is a lot to be said here, I added lots of comments into the code in my GitHub (linked at top and bottom), the file to focus on here is called “train_model.py”." }, { "code": null, "e": 3613, "s": 3519, "text": "KerasEverything revolves around keras for this project, it is a Python API for Deep Learning." }, { "code": null, "e": 3701, "s": 3613, "text": "Lets have our label inputs map to index values as that’s how the NN will identify them." }, { "code": null, "e": 3780, "s": 3701, "text": "INPUT_LABELS = { \"rock\": 0, \"paper\": 1, \"scissors\": 2, \"noise\": 3}" }, { "code": null, "e": 3831, "s": 3780, "text": "After that I decided to go the ‘Sequential Model’." }, { "code": null, "e": 4059, "s": 3831, "text": "A design that allows a simple 1–1 mapping, in ML terms it’s allowing layers that take in 1 input tensor and create 1 output tensor. For example, sequential allows the Neural Network (NN) to identity a paper image as value of 1." }, { "code": null, "e": 4292, "s": 4059, "text": "model = Sequential([ SqueezeNet(input_shape=(300, 300, 3), include_top=False), Dropout(0.2), Convolution2D(LABELS_COUNT, (1, 1), padding='valid'), Activation('relu'), GlobalAveragePooling2D(), Activation('softmax')" }, { "code": null, "e": 4510, "s": 4292, "text": "Above is our model definition, the heart of Janken and this is all the architecture designing we’ll need to do, most of the work is around collecting, cleaning and shaping the data before we compile and fit the model." }, { "code": null, "e": 4672, "s": 4510, "text": "I will talk about ‘SqueezeNet’ shortly. Everything else below is considered a layer (keras.layers), they’re all important so let’s take a minute to explain each." }, { "code": null, "e": 4895, "s": 4672, "text": "Dropout added to reduce overfitting, 0.2 = 20%, so throughout the training process drop 1/5 of what the resultant to keep the model learning new approaches and not become stale. It’s not unusual to see this as high as 50%." }, { "code": null, "e": 5096, "s": 4895, "text": "Convolution2D controls the size of the layer by the first argument LABELS_COUNT which will be 4 in total, (3 gestures + noise) label. It is appended to the already defined neural network ‘SqueezeNet’." }, { "code": null, "e": 5427, "s": 5096, "text": "Activation (ReLU) Rectified Linear Unit turns negative values into 0 and outputs positive values. Why? An Activation function is responsible for taking inputs and assigning weights to output nodes, a model can’t coordinate itself well with negative values, it becomes un-uniform in the sense of how we expect the model to perform." }, { "code": null, "e": 5541, "s": 5427, "text": "f(x) = max{0, x} => The output of a ReLU unit is non-negative. Returning x, if less than zero then max returns 0." }, { "code": null, "e": 5739, "s": 5541, "text": "ReLU has become the default activation function for many types of neural networks because a model that uses ReLU is easier to train and often achieves better performance and good model convergence." }, { "code": null, "e": 5985, "s": 5739, "text": "It’s not be all end all, it can cause a problem called “dying ReLU” if you are returning too many negatives you’ll not want them all turned 0 but return in a negative linear fashion. Search for “Leaky ReLU” if you’re interested in learning more." }, { "code": null, "e": 6168, "s": 5985, "text": "GlobalAveragePooling2D performs classification and calculates average output of each feature map in previous layer.i.e data reduction layer, prepares model for Activation(‘softmax’)." }, { "code": null, "e": 6315, "s": 6168, "text": "Activation (softmax) gives probabilities of each hand sign.We have a 4 image class (problem), ‘softmax’ handles multi-class, anything more than 2." }, { "code": null, "e": 6326, "s": 6315, "text": "SqueezeNet" }, { "code": null, "e": 6598, "s": 6326, "text": "It is a pre-built neural network for image classification, meaning we can focus on it’s extension for our purpose to build Janken which is enough work in itself than the added effort to create a neural network from scratch. The training time alone for that could be days." }, { "code": null, "e": 6631, "s": 6598, "text": "Bonuses you get with SqueezeNet;" }, { "code": null, "e": 6846, "s": 6631, "text": "Smaller Convolutional Neural Networks (CNNs) require less communication across servers during distributed training.Less bandwidth to export a new model.Smaller CNNs are more feasible to deploy and uses less memory." }, { "code": null, "e": 6962, "s": 6846, "text": "Smaller Convolutional Neural Networks (CNNs) require less communication across servers during distributed training." }, { "code": null, "e": 7000, "s": 6962, "text": "Less bandwidth to export a new model." }, { "code": null, "e": 7063, "s": 7000, "text": "Smaller CNNs are more feasible to deploy and uses less memory." }, { "code": null, "e": 7118, "s": 7063, "text": "To re-visit the line of code from the training script." }, { "code": null, "e": 7175, "s": 7118, "text": "SqueezeNet(input_shape=(300, 300, 3), include_top=False)" }, { "code": null, "e": 7254, "s": 7175, "text": "# input_shape is an image size of 300 x 300 pixels. 3 is for RGB colour range." }, { "code": null, "e": 7324, "s": 7254, "text": "# include_top lets you select if you want a final dense layer or not." }, { "code": null, "e": 7441, "s": 7324, "text": "# Dense layers are capable of interpreting found patterns in order to classify images.e.g. this image contains rock." }, { "code": null, "e": 7510, "s": 7441, "text": "# Set to False as we have labeled what rock data looks like already." }, { "code": null, "e": 7696, "s": 7510, "text": "The convolutional layers work as feature extractors. They identify a series of patterns in the image, and each layer can identify more elaborate patterns by seeing patterns of patterns." }, { "code": null, "e": 7717, "s": 7696, "text": "Note on the weights:" }, { "code": null, "e": 7940, "s": 7717, "text": "The weights in a convolutional layer are fixed-size. A convolutional layer doesn’t care about the size of the input image. It just does the training and presents a resulting image based on the same size of the input image." }, { "code": null, "e": 8156, "s": 7940, "text": "The weights in a dense layer are totally dependent on the input size. It’s one weight per element of the input. So this demands that your input be always the same size, or else you won’t have proper learned weights." }, { "code": null, "e": 8319, "s": 8156, "text": "Because of this, setting the final dense layer to false allows you to define the input size (300 x 300). (And the output size will increase/decrease accordingly)." }, { "code": null, "e": 8337, "s": 8319, "text": "Testing the model" }, { "code": null, "e": 8476, "s": 8337, "text": "In the script “test_model” you can see model predictions on images you’ve already processed or new images the model has never seen before." }, { "code": null, "e": 8574, "s": 8476, "text": "The script handles any new image you want to provide as it will reshape to 300x300 using open CV." }, { "code": null, "e": 8589, "s": 8574, "text": "Play the game!" }, { "code": null, "e": 8792, "s": 8589, "text": "Predictions on Janken’s play resultI imagined the prediction Janken would make will “flicker” a lot as a moving camera image will always be provide different inputs to analyse and run the model against." }, { "code": null, "e": 8903, "s": 8792, "text": "Lighting will play a big part so I tried to split my dataset and collect images at different times of the day." }, { "code": null, "e": 9002, "s": 8903, "text": "Static backgrounds or controls to freeze the image will help make more stable gesture predictions." }, { "code": null, "e": 9023, "s": 9002, "text": "How did it play out?" }, { "code": null, "e": 9198, "s": 9023, "text": "Janken wasn’t made with lockdown in mind so an ‘elegant’... solution was made to play others through the mac’s webcam onto a shared screen with another player on the monitor." }, { "code": null, "e": 9454, "s": 9198, "text": "However Janken could only ever beat me constantly, it was able to win 50% of played gestures from other players through the monitor but I suspected the nature of camera imagery and processing made it difficult for Janken to probably make out all gestures." }, { "code": null, "e": 9583, "s": 9454, "text": "To improve the model I should have gathered images from the the users side through my webcam to give Janken more generalisation." }, { "code": null, "e": 9744, "s": 9583, "text": "Overall I really enjoyed everything I learnt and there wasn’t a tech used in this project that I was familiar with. Was great to turn the learnings into a game." }, { "code": null, "e": 9895, "s": 9744, "text": "Finally I added some user controls that hopefully adds to the experience with a best of 3 game counter.The key instructions are along the grey header." }, { "code": null, "e": 9906, "s": 9895, "text": "Peace Out!" }, { "code": null, "e": 9916, "s": 9906, "text": "Resources" }, { "code": null, "e": 9938, "s": 9916, "text": "Full code GitHub link" }, { "code": null, "e": 9949, "s": 9938, "text": "github.com" }, { "code": null, "e": 9959, "s": 9949, "text": "Keras API" }, { "code": null, "e": 10009, "s": 9959, "text": ": Keras API reference\nKeras documentationkeras.io" }, { "code": null, "e": 10025, "s": 10009, "text": "SqueezeNet Info" }, { "code": null, "e": 10048, "s": 10025, "text": "towardsdatascience.com" }, { "code": null, "e": 10058, "s": 10048, "text": "arxiv.org" } ]
Explain queue by using linked list in C language
Queue overflow and Queue under flow can be avoided by using linked list. Operations carried out under queue with the help of linked lists in C programming language are as follows − Insert Delete The syntax is as follows − &item : Newnode = (node*) mallac (sizeof (node)); newnode ->data = item; newnode ->link = NULL; if ((front = = NULL) || (rear = = NULL)){ front= newnode; rear = newnode; }else{ Rear->link = newnode; rear = newnode; } The syntax is as follows − if ((front= = NULL)) printf("Deletion is not possible, Queue is empty"); else{ temp = front; front = front ->link; free (temp); } The syntax is as follows − while (front! = NULL){ printf("%d", front ->data); front = front->link; } Following is the C program for queue by using linked lists − #include <stdio.h> #include <stdlib.h> struct node{ int info; struct node *ptr; }*front,*rear,*temp,*front1; int frontelement(); void enq(int data); void deq(); void display(); void create(); int count = 0; void main(){ int no, ch, e; printf("\n 1 - Enqueue"); printf("\n 2 - Dequeue"); printf("\n 3 - Display"); printf("\n 4 - Exit"); printf("\n 5-front"); create(); while (1){ printf("\n Enter choice : "); scanf("%d", &ch); switch (ch){ case 1: printf("Enter data : "); scanf("%d", &no); enq(no); break; case 2: deq(); break; case 3: display(); break; case 4: exit(0); break; case 5: e = frontelement(); if (e != 0) printf("Front element : %d", e); else printf("\n No front element in Queue"); break; default: printf("Wrong choice, Try again "); break; } } } void enq(int data){ if (rear == NULL){ rear = (struct node *)malloc(1*sizeof(struct node)); rear->ptr = NULL; rear->info = data; front = rear; }else{ temp=(struct node *)malloc(1*sizeof(struct node)); rear->ptr = temp; temp->info = data; temp->ptr = NULL; rear = temp; } count++; } void display(){ front1 = front; if ((front1 == NULL) && (rear == NULL)){ printf("Queue is empty"); return; } while (front1 != rear){ printf("%d ", front1->info); front1 = front1->ptr; } if (front1 == rear) printf("%d", front1->info); } void deq(){ front1 = front; if (front1 == NULL){ printf("\n Error"); return; } else if (front1->ptr != NULL){ front1 = front1->ptr; printf("\n Dequeued value : %d", front->info); free(front); front = front1; }else{ printf("\n Dequeued value : %d", front->info); free(front); front = NULL; rear = NULL; } count--; } int frontelement(){ if ((front != NULL) && (rear != NULL)) return(front->info); else return 0; } When the above program is executed, it produces the following result − 1 - Enque 2 - Deque 3 – Display 4 - Exit 5 - Front element Enter choice: 1 Enter data: 14 Enter choice: 1 Enter data: 85 Enter choice: 1 Enter data: 38 Enter choice: 5 Front element: 14 Enter choice: 3 14 85 38 Enter choice: 2 Dequed value: 14 Enter choice: 3 Enter choice: 4
[ { "code": null, "e": 1135, "s": 1062, "text": "Queue overflow and Queue under flow can be avoided by using linked list." }, { "code": null, "e": 1243, "s": 1135, "text": "Operations carried out under queue with the help of linked lists in C programming language are as follows −" }, { "code": null, "e": 1250, "s": 1243, "text": "Insert" }, { "code": null, "e": 1257, "s": 1250, "text": "Delete" }, { "code": null, "e": 1284, "s": 1257, "text": "The syntax is as follows −" }, { "code": null, "e": 1513, "s": 1284, "text": "&item :\nNewnode = (node*) mallac (sizeof (node));\nnewnode ->data = item;\nnewnode ->link = NULL;\nif ((front = = NULL) || (rear = = NULL)){\n front= newnode;\n rear = newnode;\n}else{\n Rear->link = newnode;\n rear = newnode;\n}" }, { "code": null, "e": 1540, "s": 1513, "text": "The syntax is as follows −" }, { "code": null, "e": 1679, "s": 1540, "text": "if ((front= = NULL))\nprintf(\"Deletion is not possible, Queue is empty\");\nelse{\n temp = front;\n front = front ->link;\n free (temp);\n}" }, { "code": null, "e": 1706, "s": 1679, "text": "The syntax is as follows −" }, { "code": null, "e": 1786, "s": 1706, "text": "while (front! = NULL){\n printf(\"%d\", front ->data);\n front = front->link;\n}" }, { "code": null, "e": 1847, "s": 1786, "text": "Following is the C program for queue by using linked lists −" }, { "code": null, "e": 4100, "s": 1847, "text": "#include <stdio.h>\n#include <stdlib.h>\nstruct node{\n int info;\n struct node *ptr;\n}*front,*rear,*temp,*front1;\nint frontelement();\nvoid enq(int data);\nvoid deq();\nvoid display();\nvoid create();\nint count = 0;\nvoid main(){\n int no, ch, e;\n printf(\"\\n 1 - Enqueue\");\n printf(\"\\n 2 - Dequeue\");\n printf(\"\\n 3 - Display\");\n printf(\"\\n 4 - Exit\");\n printf(\"\\n 5-front\");\n create();\n while (1){\n printf(\"\\n Enter choice : \");\n scanf(\"%d\", &ch);\n switch (ch){\n case 1:\n printf(\"Enter data : \");\n scanf(\"%d\", &no);\n enq(no);\n break;\n case 2:\n deq();\n break;\n case 3:\n display();\n break;\n case 4:\n exit(0);\n break;\n case 5:\n e = frontelement();\n if (e != 0)\n printf(\"Front element : %d\", e);\n else\n printf(\"\\n No front element in Queue\");\n break;\n default:\n printf(\"Wrong choice, Try again \");\n break;\n }\n }\n}\nvoid enq(int data){\n if (rear == NULL){\n rear = (struct node *)malloc(1*sizeof(struct node));\n rear->ptr = NULL;\n rear->info = data;\n front = rear;\n }else{\n temp=(struct node *)malloc(1*sizeof(struct node));\n rear->ptr = temp;\n temp->info = data;\n temp->ptr = NULL;\n rear = temp;\n }\n count++;\n}\nvoid display(){\n front1 = front;\n if ((front1 == NULL) && (rear == NULL)){\n printf(\"Queue is empty\");\n return;\n }\n while (front1 != rear){\n printf(\"%d \", front1->info);\n front1 = front1->ptr;\n }\n if (front1 == rear)\n printf(\"%d\", front1->info);\n }\n void deq(){\n front1 = front;\n if (front1 == NULL){\n printf(\"\\n Error\");\n return;\n }\n else\n if (front1->ptr != NULL){\n front1 = front1->ptr;\n printf(\"\\n Dequeued value : %d\", front->info);\n free(front);\n front = front1;\n }else{\n printf(\"\\n Dequeued value : %d\", front->info);\n free(front);\n front = NULL;\n rear = NULL;\n }\n count--;\n}\nint frontelement(){\n if ((front != NULL) && (rear != NULL))\n return(front->info);\n else\n return 0;\n}" }, { "code": null, "e": 4171, "s": 4100, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 4447, "s": 4171, "text": "1 - Enque\n2 - Deque\n3 – Display\n4 - Exit\n5 - Front element\nEnter choice: 1\nEnter data: 14\nEnter choice: 1\nEnter data: 85\nEnter choice: 1\nEnter data: 38\nEnter choice: 5\nFront element: 14\nEnter choice: 3\n14 85 38\nEnter choice: 2\nDequed value: 14\nEnter choice: 3\nEnter choice: 4" } ]
Buffer Overflow Attack with Example - GeeksforGeeks
20 Apr, 2022 A buffer is a temporary area for data storage. When more data (than was originally allocated to be stored) gets placed by a program or system process, the extra data overflows. It causes some of that data to leak out into other buffers, which can corrupt or overwrite whatever data they were holding.In a buffer-overflow attack, the extra data sometimes holds specific instructions for actions intended by a hacker or malicious user; for example, the data could trigger a response that damages files, changes data or unveils private information.Attacker would use a buffer-overflow exploit to take advantage of a program that is waiting on a user’s input. There are two types of buffer overflows: stack-based and heap-based. Heap-based, which are difficult to execute and the least common of the two, attack an application by flooding the memory space reserved for a program. Stack-based buffer overflows, which are more common among attackers, exploit applications and programs by using what is known as a stack: memory space used to store user input.Let us study some real program examples that show the danger of such situations based on the C. In the examples, we do not implement any malicious code injection but just to show that the buffer can be overflow. Modern compilers normally provide overflow checking option during the compile/link time but during the run time it is quite difficult to check this problem without any extra protection mechanism such as using exception handling. C // A C program to demonstrate buffer overflow#include <stdio.h>#include <string.h>#include <stdlib.h> int main(int argc, char *argv[]){ // Reserve 5 byte of buffer plus the terminating NULL. // should allocate 8 bytes = 2 double words, // To overflow, need more than 8 bytes... char buffer[5]; // If more than 8 characters input // by user, there will be access // violation, segmentation fault // a prompt how to execute the program... if (argc < 2) { printf("strcpy() NOT executed....\n"); printf("Syntax: %s <characters>\n", argv[0]); exit(0); } // copy the user input to mybuffer, without any // bound checking a secure version is strcpy_s() strcpy(buffer, argv[1]); printf("buffer content= %s\n", buffer); // you may want to try strcpy_s() printf("strcpy() executed...\n"); return 0;} Compile this program in Linux and for output use command output_file INPUT Input : 12345678 (8 bytes), the program run smoothly. Input : 123456789 (9 bytes) "Segmentation fault" message will be displayed and the program terminates. The vulnerability exists because the buffer could be overflowed if the user input (argv[1]) bigger than 8 bytes. Why 8 bytes? For 32 bit (4 bytes) system, we must fill up a double word (32 bits) memory. Character (char) size is 1 byte, so if we request buffer with 5 bytes, the system will allocate 2 double words (8 bytes). That is why when you input more than 8 bytes; the mybuffer will be over flowedSimilar standard functions that are technically less vulnerable, such as strncpy(), strncat(), and memcpy(), do exist. But the problem with these functions is that it is the programmer responsibility to assert the size of the buffer, not the compiler.Every C/C++ coder or programmer must know the buffer overflow problem before they do the coding. A lot of bugs generated, in most cases can be exploited as a result of buffer overflow.REFERENCES Wikipedia BufferOverflow c++BufferOverflowThis article is contributed by Akash Sharan. 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. kk773572498 secure-coding Advanced Computer Subject C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Linear Regression Copying Files to and from Docker Containers System Design Tutorial Python | Decision tree implementation ML | Underfitting and Overfitting Arrays in C/C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ std::sort() in C++ STL
[ { "code": null, "e": 24143, "s": 24115, "text": "\n20 Apr, 2022" }, { "code": null, "e": 25637, "s": 24143, "text": "A buffer is a temporary area for data storage. When more data (than was originally allocated to be stored) gets placed by a program or system process, the extra data overflows. It causes some of that data to leak out into other buffers, which can corrupt or overwrite whatever data they were holding.In a buffer-overflow attack, the extra data sometimes holds specific instructions for actions intended by a hacker or malicious user; for example, the data could trigger a response that damages files, changes data or unveils private information.Attacker would use a buffer-overflow exploit to take advantage of a program that is waiting on a user’s input. There are two types of buffer overflows: stack-based and heap-based. Heap-based, which are difficult to execute and the least common of the two, attack an application by flooding the memory space reserved for a program. Stack-based buffer overflows, which are more common among attackers, exploit applications and programs by using what is known as a stack: memory space used to store user input.Let us study some real program examples that show the danger of such situations based on the C. In the examples, we do not implement any malicious code injection but just to show that the buffer can be overflow. Modern compilers normally provide overflow checking option during the compile/link time but during the run time it is quite difficult to check this problem without any extra protection mechanism such as using exception handling. " }, { "code": null, "e": 25639, "s": 25637, "text": "C" }, { "code": "// A C program to demonstrate buffer overflow#include <stdio.h>#include <string.h>#include <stdlib.h> int main(int argc, char *argv[]){ // Reserve 5 byte of buffer plus the terminating NULL. // should allocate 8 bytes = 2 double words, // To overflow, need more than 8 bytes... char buffer[5]; // If more than 8 characters input // by user, there will be access // violation, segmentation fault // a prompt how to execute the program... if (argc < 2) { printf(\"strcpy() NOT executed....\\n\"); printf(\"Syntax: %s <characters>\\n\", argv[0]); exit(0); } // copy the user input to mybuffer, without any // bound checking a secure version is strcpy_s() strcpy(buffer, argv[1]); printf(\"buffer content= %s\\n\", buffer); // you may want to try strcpy_s() printf(\"strcpy() executed...\\n\"); return 0;}", "e": 26617, "s": 25639, "text": null }, { "code": null, "e": 26694, "s": 26617, "text": "Compile this program in Linux and for output use command output_file INPUT " }, { "code": null, "e": 26750, "s": 26694, "text": " Input : 12345678 (8 bytes), the program run smoothly." }, { "code": null, "e": 26854, "s": 26750, "text": " Input : 123456789 (9 bytes)\n\"Segmentation fault\" message will be displayed and the program terminates." }, { "code": null, "e": 28166, "s": 26854, "text": "The vulnerability exists because the buffer could be overflowed if the user input (argv[1]) bigger than 8 bytes. Why 8 bytes? For 32 bit (4 bytes) system, we must fill up a double word (32 bits) memory. Character (char) size is 1 byte, so if we request buffer with 5 bytes, the system will allocate 2 double words (8 bytes). That is why when you input more than 8 bytes; the mybuffer will be over flowedSimilar standard functions that are technically less vulnerable, such as strncpy(), strncat(), and memcpy(), do exist. But the problem with these functions is that it is the programmer responsibility to assert the size of the buffer, not the compiler.Every C/C++ coder or programmer must know the buffer overflow problem before they do the coding. A lot of bugs generated, in most cases can be exploited as a result of buffer overflow.REFERENCES Wikipedia BufferOverflow c++BufferOverflowThis article is contributed by Akash Sharan. 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": 28178, "s": 28166, "text": "kk773572498" }, { "code": null, "e": 28192, "s": 28178, "text": "secure-coding" }, { "code": null, "e": 28218, "s": 28192, "text": "Advanced Computer Subject" }, { "code": null, "e": 28222, "s": 28218, "text": "C++" }, { "code": null, "e": 28241, "s": 28222, "text": "Technical Scripter" }, { "code": null, "e": 28245, "s": 28241, "text": "CPP" }, { "code": null, "e": 28343, "s": 28245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28352, "s": 28343, "text": "Comments" }, { "code": null, "e": 28365, "s": 28352, "text": "Old Comments" }, { "code": null, "e": 28388, "s": 28365, "text": "ML | Linear Regression" }, { "code": null, "e": 28432, "s": 28388, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 28455, "s": 28432, "text": "System Design Tutorial" }, { "code": null, "e": 28493, "s": 28455, "text": "Python | Decision tree implementation" }, { "code": null, "e": 28527, "s": 28493, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 28543, "s": 28527, "text": "Arrays in C/C++" }, { "code": null, "e": 28589, "s": 28543, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 28632, "s": 28589, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 28651, "s": 28632, "text": "Inheritance in C++" } ]
MongoDB query to fetch date records (ISODate format) in a range
Let us create a collection with documents − > db.demo178.insertOne({"DueDate":new ISODate("2019-01-10T06:18:20.474Z")}); { "acknowledged" : true, "insertedId" : ObjectId("5e397bd89e4f06af551997f5") } > db.demo178.insertOne({"DueDate":new ISODate("2020-11-10T18:05:11.474Z")}); { "acknowledged" : true, "insertedId" : ObjectId("5e397bf39e4f06af551997f6") } > db.demo178.insertOne({"DueDate":new ISODate("2020-03-15T07:05:10.474Z")}); { "acknowledged" : true, "insertedId" : ObjectId("5e397c039e4f06af551997f7") } > db.demo178.insertOne({"DueDate":new ISODate("2020-06-11T16:05:10.474Z")}); { "acknowledged" : true, "insertedId" : ObjectId("5e397c0f9e4f06af551997f8") } Display all documents from a collection with the help of find() method − > db.demo178.find(); This will produce the following output − { "_id" : ObjectId("5e397bd89e4f06af551997f5"), "DueDate" : ISODate("2019-01-10T06:18:20.474Z") } { "_id" : ObjectId("5e397bf39e4f06af551997f6"), "DueDate" : ISODate("2020-11-10T18:05:11.474Z") } { "_id" : ObjectId("5e397c039e4f06af551997f7"), "DueDate" : ISODate("2020-03-15T07:05:10.474Z") } { "_id" : ObjectId("5e397c0f9e4f06af551997f8"), "DueDate" : ISODate("2020-06-11T16:05:10.474Z") } Following is the query to fetch date records in a range − > db.demo178.aggregate([ ...{ ... "$redact": { ... "$cond": { ... "if": { ... "$and": [ ... { "$gt": [ {"$hour": "$DueDate"}, 5] }, ... { "$lt": [ {"$hour": "$DueDate"}, 9] } ... ] ... }, ... "then": "$$KEEP", ... "else": "$$PRUNE" ... } ... } ... } ...]) This will produce the following output − { "_id" : ObjectId("5e397bd89e4f06af551997f5"), "DueDate" : ISODate("2019-01-10T06:18:20.474Z") } { "_id" : ObjectId("5e397c039e4f06af551997f7"), "DueDate" : ISODate("2020-03-15T07:05:10.474Z") }
[ { "code": null, "e": 1106, "s": 1062, "text": "Let us create a collection with documents −" }, { "code": null, "e": 1754, "s": 1106, "text": "> db.demo178.insertOne({\"DueDate\":new ISODate(\"2019-01-10T06:18:20.474Z\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e397bd89e4f06af551997f5\")\n}\n> db.demo178.insertOne({\"DueDate\":new ISODate(\"2020-11-10T18:05:11.474Z\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e397bf39e4f06af551997f6\")\n}\n> db.demo178.insertOne({\"DueDate\":new ISODate(\"2020-03-15T07:05:10.474Z\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e397c039e4f06af551997f7\")\n}\n> db.demo178.insertOne({\"DueDate\":new ISODate(\"2020-06-11T16:05:10.474Z\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e397c0f9e4f06af551997f8\")\n}" }, { "code": null, "e": 1827, "s": 1754, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1848, "s": 1827, "text": "> db.demo178.find();" }, { "code": null, "e": 1889, "s": 1848, "text": "This will produce the following output −" }, { "code": null, "e": 2281, "s": 1889, "text": "{ \"_id\" : ObjectId(\"5e397bd89e4f06af551997f5\"), \"DueDate\" : ISODate(\"2019-01-10T06:18:20.474Z\") }\n{ \"_id\" : ObjectId(\"5e397bf39e4f06af551997f6\"), \"DueDate\" : ISODate(\"2020-11-10T18:05:11.474Z\") }\n{ \"_id\" : ObjectId(\"5e397c039e4f06af551997f7\"), \"DueDate\" : ISODate(\"2020-03-15T07:05:10.474Z\") }\n{ \"_id\" : ObjectId(\"5e397c0f9e4f06af551997f8\"), \"DueDate\" : ISODate(\"2020-06-11T16:05:10.474Z\") }" }, { "code": null, "e": 2339, "s": 2281, "text": "Following is the query to fetch date records in a range −" }, { "code": null, "e": 2699, "s": 2339, "text": "> db.demo178.aggregate([\n...{\n... \"$redact\": {\n... \"$cond\": {\n... \"if\": {\n... \"$and\": [\n... { \"$gt\": [ {\"$hour\": \"$DueDate\"}, 5] },\n... { \"$lt\": [ {\"$hour\": \"$DueDate\"}, 9] }\n... ]\n... },\n... \"then\": \"$$KEEP\",\n... \"else\": \"$$PRUNE\"\n... }\n... }\n... }\n...])" }, { "code": null, "e": 2740, "s": 2699, "text": "This will produce the following output −" }, { "code": null, "e": 2936, "s": 2740, "text": "{ \"_id\" : ObjectId(\"5e397bd89e4f06af551997f5\"), \"DueDate\" : ISODate(\"2019-01-10T06:18:20.474Z\") }\n{ \"_id\" : ObjectId(\"5e397c039e4f06af551997f7\"), \"DueDate\" : ISODate(\"2020-03-15T07:05:10.474Z\") }" } ]
Arrow functions in Javascript
According to MDN, An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill-suited as methods, and they cannot be used as constructors. There are 3 subtle differences in regular functions and arrow functions in JavaScript. No own this bindingArrow functions do not have their own value. The value of this inside an arrow function is always inherited from the enclosing scope. No own this binding Arrow functions do not have their own value. The value of this inside an arrow function is always inherited from the enclosing scope. this.a = 100; let arrowFunc = () => {this.a = 150}; function regFunc() { this.a = 200; } console.log(this.a) arrowFunc() console.log(this.a) regFunc() console.log(this.a) This will give the output − 100 150 150 See that the arrow function changed this object outside its scope. The regular function just made the changes within its own. Arrow functions do not have a arguments array In JS arguments array in functions is a special object that can be used to get all the arguments passed to the function. Similar to this, arrow functions do not have their own binding to a arguments object, they are bound to arguments of enclosing scope. Arrow functions are callable but not constructible If a function is constructible, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call). Functions created through function declarations / expressions are both constructible and callable. Arrow functions (and methods) are only callable. class constructors are only constructible. If you are trying to call a non-callable function or to construct a nonconstructive function, you will get a runtime error. let arrowFunc = () => {} new arrowFunc() This code gives the error − arrowFunc is not a constructor
[ { "code": null, "e": 1366, "s": 1062, "text": "According to MDN, An arrow function expression is a syntactically compact\nalternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill-suited as methods, and they cannot be used as constructors." }, { "code": null, "e": 1453, "s": 1366, "text": "There are 3 subtle differences in regular functions and arrow functions\nin JavaScript." }, { "code": null, "e": 1606, "s": 1453, "text": "No own this bindingArrow functions do not have their own value. The value of this inside an arrow function is always inherited from the enclosing scope." }, { "code": null, "e": 1626, "s": 1606, "text": "No own this binding" }, { "code": null, "e": 1760, "s": 1626, "text": "Arrow functions do not have their own value. The value of this inside an arrow function is always inherited from the enclosing scope." }, { "code": null, "e": 1934, "s": 1760, "text": "this.a = 100;\nlet arrowFunc = () => {this.a = 150};\nfunction regFunc() {\n this.a = 200;\n}\nconsole.log(this.a)\narrowFunc()\nconsole.log(this.a)\nregFunc()\nconsole.log(this.a)" }, { "code": null, "e": 1962, "s": 1934, "text": "This will give the output −" }, { "code": null, "e": 1974, "s": 1962, "text": "100\n150\n150" }, { "code": null, "e": 2100, "s": 1974, "text": "See that the arrow function changed this object outside its scope. The regular function just made the changes within its own." }, { "code": null, "e": 2401, "s": 2100, "text": "Arrow functions do not have a arguments array In JS arguments array in functions is a special object that can be used to get all the arguments passed to the function. Similar to this, arrow functions do not have their own binding to a arguments object, they are bound to arguments of enclosing scope." }, { "code": null, "e": 2613, "s": 2401, "text": "Arrow functions are callable but not constructible If a function is constructible, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call)." }, { "code": null, "e": 2712, "s": 2613, "text": "Functions created through function declarations / expressions are both\nconstructible and callable." }, { "code": null, "e": 2804, "s": 2712, "text": "Arrow functions (and methods) are only callable. class constructors are only constructible." }, { "code": null, "e": 2928, "s": 2804, "text": "If you are trying to call a non-callable function or to construct a nonconstructive function, you will get a runtime error." }, { "code": null, "e": 2969, "s": 2928, "text": "let arrowFunc = () => {}\nnew arrowFunc()" }, { "code": null, "e": 2997, "s": 2969, "text": "This code gives the error −" }, { "code": null, "e": 3028, "s": 2997, "text": "arrowFunc is not a constructor" } ]
How to create a plot for the response variable grouped by two columns using ggplot2 in R?
When two categorical variables make an impact on the response variable together then it is necessary to visualize their effect graphically because this graph helps us to understand the variation in the effect. Therefore, we can create a plot for the response variable that changes with one or both of the categorical independent variables. This can be done with the help of using interaction function in ggplot2. Consider the below data frame − > set.seed(1) > y<-rpois(30,2) > Group1<-rep(c(letters[1:5]),times=6) > Group2<-rep(c("Ph1","Ph2","Ph3"),each=10) > df<-data.frame(y,Group1,Group2) > head(df,20) y Group1 Group2 1 1 a Ph1 2 1 b Ph1 3 2 c Ph1 4 4 d Ph1 5 1 e Ph1 6 4 a Ph1 7 4 b Ph1 8 2 c Ph1 9 2 d Ph1 10 0 e Ph1 11 1 a Ph2 12 1 b Ph2 13 3 c Ph2 14 1 d Ph2 15 3 e Ph2 16 2 a Ph2 17 3 b Ph2 18 6 c Ph2 19 1 d Ph2 20 3 e Ph2 Loading ggplot2 package − > library(ggplot2) Creating the plot with interaction > qplot(Group1, y, data=df, group=Group2, color=Group2, geom='line')+ + geom_smooth(aes(group=interaction(Group1, Group2))) `geom_smooth()` using method = 'loess' and formula 'y ~ x' Here, we can see that all the lines are crossing each other therefore there exists an interaction effect of independent variables, which means at least one level combination of both the independent variables (Group1 and Group2) has different mean that the others.
[ { "code": null, "e": 1475, "s": 1062, "text": "When two categorical variables make an impact on the response variable together then it is necessary to visualize their effect graphically because this graph helps us to understand the variation in the effect. Therefore, we can create a plot for the response variable that changes with one or both of the categorical independent variables. This can be done with the help of using interaction function in ggplot2." }, { "code": null, "e": 1507, "s": 1475, "text": "Consider the below data frame −" }, { "code": null, "e": 1945, "s": 1507, "text": "> set.seed(1)\n> y<-rpois(30,2)\n> Group1<-rep(c(letters[1:5]),times=6)\n> Group2<-rep(c(\"Ph1\",\"Ph2\",\"Ph3\"),each=10)\n> df<-data.frame(y,Group1,Group2)\n> head(df,20)\ny Group1 Group2\n1 1 a Ph1\n2 1 b Ph1\n3 2 c Ph1\n4 4 d Ph1\n5 1 e Ph1\n6 4 a Ph1\n7 4 b Ph1\n8 2 c Ph1\n9 2 d Ph1\n10 0 e Ph1\n11 1 a Ph2\n12 1 b Ph2\n13 3 c Ph2\n14 1 d Ph2\n15 3 e Ph2\n16 2 a Ph2\n17 3 b Ph2\n18 6 c Ph2\n19 1 d Ph2\n20 3 e Ph2" }, { "code": null, "e": 1971, "s": 1945, "text": "Loading ggplot2 package −" }, { "code": null, "e": 1990, "s": 1971, "text": "> library(ggplot2)" }, { "code": null, "e": 2025, "s": 1990, "text": "Creating the plot with interaction" }, { "code": null, "e": 2208, "s": 2025, "text": "> qplot(Group1, y, data=df, group=Group2, color=Group2, geom='line')+\n+ geom_smooth(aes(group=interaction(Group1, Group2)))\n`geom_smooth()` using method = 'loess' and formula 'y ~ x'" }, { "code": null, "e": 2472, "s": 2208, "text": "Here, we can see that all the lines are crossing each other therefore there exists an interaction effect of independent variables, which means at least one level combination of both the independent variables (Group1 and Group2) has different mean that the others." } ]
How to create interactive map plots with Plotly | by Emma Grimaldi | Towards Data Science
One of my favorite part of working with data is without a doubt creating visualizations. Images are the best tool to convey information: they are immediate, the brain can in fact process them thousands of times faster than words. Images are also universal, and they tend to stick longer in our minds. Finally, we are lazy animals and for this reason we pay more attention to visuals, rather than words. How many times did you meet someone new and afterwards you struggled remembering their name, while their face was crystal clear in your head? I realized how much I love creating visuals while working as a researcher in academia: as much as I liked running experiments and numerical simulations, I was really looking forward to the moment of the project when I would be able to process all my findings and create those pretty yet powerful graphs. Yes, I also had to write papers to describe all the process, the workflow and theoretical reasoning behind the research, but being able to communicate months of work with just few images was just incredible! All this intro was to convince you that images are important, in case you didn’t think so already. And especially for a Data Scientist, who needs to be efficient in conveying information to non-technical audiences, from time to time. In the last week or so, I have been working on my capstone project regarding storm events in the US while dealing with a dataset of ~11,000 observations containing geospatial information. My first thought was to plot all this data on a map so I could see at a glance what are the areas that are mostly affected by such events. Since I work in Python, Geopandas would be the immediate library of choice, however, I wanted something more interactive. What if I want to change the style of the map? Or, what if I want to see only the thunderstorms or only the hails? I did a little bit of research and found out that plotly was what I needed. I could not find any nice tutorial to walk me through the process, so I looked at a number of examples online trying to deductively understand how this works, with a lot of trial and error. This is the reason why I decided to write this post, together with the fact that I am training and bunch of neural networks for the same project and I have idle time while all those epochs go back and forth. Note: to do something like what I am about to describe, you will need an account with plotly as well as mapbox. Particularly because you will need an access token, that can be created here, and a username and API key that can be generated here. All this is free. I would also recommend that you are very well versed with Python dictionaries, since they are fundamental to create map plots like these, as you will notice. I gathered data from the National Climatic Data Center about storm events in the US from year 2000 up to now. As usual I had to do a lot of cleaning, deal with missing data and engineer some features. At this link you can find the .csv file used for this purpose, and for my capstone project in general. The data has information about the latitude and longitude of the phenomenon, which is fundamental for us in order to plot on a map. It also indicates whether it was a thunderstorm, hail, flash flood, etc for a total of seven different categories. The magnitude of the storm event, in which State, and when it happened Before working on the actual plot, we need to import and assign a few things. Here is where we need our access token from Mapbox, as well as username and api key from Plotly. import plotly.plotly as pyimport plotly.graph_objs as goimport plotlyimport pandas as pd# setting user, api key and access tokenplotly.tools.set_credentials_file(username='your_username_here', api_key='your_api_key_here')mapbox_access_token = 'your_access_token_here' In order to generate our figure, we will need two things: data and layout. Our variable data will be a list of seven dictionaries (one per event type), where each one contains the latitude and longitude values, as well as the name of the storm type and the marker characteristics for the plot. The variable layout is a dictionary containing everything concerning the image that is no directly connected with the data: the drop-down menus, the annotations, how we want to format them and where we want to place them. After reading and assigning the dataframe to a df variable, I created a list containing the names of the seven different storm categories and named it event_types. I for-looped over this list and used it to filter the dataframe, creating a dictionary for each event type and appending it to the data list. This way I have my list of dictionaries, data. The reason why I assigned an opacity value of 0.5 to the markers is because, most likely, there will be areas with more points than others. Giving some sort of transparency to the points, will allow us to see different shades of the same color on the map, corresponding to different frequencies of the same phenomenon in different areas. We are done with data, and now it’s layout’s turn, which will definitively require more work. Let’s set the basic settings of the map. Now we can start adding things to the map to customize it and make interactive as we like. Let’s say I want to put a black box with white text on it, that specifies that my points represent only storm events from year 2000 up to now, that caused more than $50k of economic damage. Some static prompt like this, will fall under the annotation key of the layout dictionary: the value corresponding to annotation will need to be a list of dictionaries and in this specific case, a list containing only one dictionary since I want to put only one annotation on my map. It seems cumbersome in words, but doing it is definitely easier than explaining it. Now it’s time for the drop-down menus, which will need to be assigned to the updatemenus key of the layout dictionary. I want to add two drop-down menus: one to select the type of storm event to visualize, in case we want to look at only of type instead of all of them, while the other drop-down will allow us to change the type of map on the background, which is dark by default. The name and the styles of the available maps can be found on Mapbox. Every drop-down menu is defined again through a dictionary, and all these dictionaries will be contained into a list that we will assign to layout['updatemenus']. If you want, you can easily assign a title to your plot. I did so just by doing layout['title'] = 'Storm Events'. Once we have our data and layout in order, we can generate the plot just by running: figure = dict(data = data, layout = layout)py.iplot(figure, filename = 'put_your_name_here') Et voilà! You can zoom in, zoom out, select what you want to visualize from the top menu, and change the map type from the menu on the bottom. Pretty cool! I look forward to work on some other plots like this, now that I learned how to do it. Hopefully you found this useful as well! Feel free to check out: the Github repository of this code my other Medium posts. my LinkedIn profile. Thank you for reading!
[ { "code": null, "e": 717, "s": 172, "text": "One of my favorite part of working with data is without a doubt creating visualizations. Images are the best tool to convey information: they are immediate, the brain can in fact process them thousands of times faster than words. Images are also universal, and they tend to stick longer in our minds. Finally, we are lazy animals and for this reason we pay more attention to visuals, rather than words. How many times did you meet someone new and afterwards you struggled remembering their name, while their face was crystal clear in your head?" }, { "code": null, "e": 1463, "s": 717, "text": "I realized how much I love creating visuals while working as a researcher in academia: as much as I liked running experiments and numerical simulations, I was really looking forward to the moment of the project when I would be able to process all my findings and create those pretty yet powerful graphs. Yes, I also had to write papers to describe all the process, the workflow and theoretical reasoning behind the research, but being able to communicate months of work with just few images was just incredible! All this intro was to convince you that images are important, in case you didn’t think so already. And especially for a Data Scientist, who needs to be efficient in conveying information to non-technical audiences, from time to time." }, { "code": null, "e": 2501, "s": 1463, "text": "In the last week or so, I have been working on my capstone project regarding storm events in the US while dealing with a dataset of ~11,000 observations containing geospatial information. My first thought was to plot all this data on a map so I could see at a glance what are the areas that are mostly affected by such events. Since I work in Python, Geopandas would be the immediate library of choice, however, I wanted something more interactive. What if I want to change the style of the map? Or, what if I want to see only the thunderstorms or only the hails? I did a little bit of research and found out that plotly was what I needed. I could not find any nice tutorial to walk me through the process, so I looked at a number of examples online trying to deductively understand how this works, with a lot of trial and error. This is the reason why I decided to write this post, together with the fact that I am training and bunch of neural networks for the same project and I have idle time while all those epochs go back and forth." }, { "code": null, "e": 2922, "s": 2501, "text": "Note: to do something like what I am about to describe, you will need an account with plotly as well as mapbox. Particularly because you will need an access token, that can be created here, and a username and API key that can be generated here. All this is free. I would also recommend that you are very well versed with Python dictionaries, since they are fundamental to create map plots like these, as you will notice." }, { "code": null, "e": 3544, "s": 2922, "text": "I gathered data from the National Climatic Data Center about storm events in the US from year 2000 up to now. As usual I had to do a lot of cleaning, deal with missing data and engineer some features. At this link you can find the .csv file used for this purpose, and for my capstone project in general. The data has information about the latitude and longitude of the phenomenon, which is fundamental for us in order to plot on a map. It also indicates whether it was a thunderstorm, hail, flash flood, etc for a total of seven different categories. The magnitude of the storm event, in which State, and when it happened" }, { "code": null, "e": 3719, "s": 3544, "text": "Before working on the actual plot, we need to import and assign a few things. Here is where we need our access token from Mapbox, as well as username and api key from Plotly." }, { "code": null, "e": 3987, "s": 3719, "text": "import plotly.plotly as pyimport plotly.graph_objs as goimport plotlyimport pandas as pd# setting user, api key and access tokenplotly.tools.set_credentials_file(username='your_username_here', api_key='your_api_key_here')mapbox_access_token = 'your_access_token_here'" }, { "code": null, "e": 4503, "s": 3987, "text": "In order to generate our figure, we will need two things: data and layout. Our variable data will be a list of seven dictionaries (one per event type), where each one contains the latitude and longitude values, as well as the name of the storm type and the marker characteristics for the plot. The variable layout is a dictionary containing everything concerning the image that is no directly connected with the data: the drop-down menus, the annotations, how we want to format them and where we want to place them." }, { "code": null, "e": 4856, "s": 4503, "text": "After reading and assigning the dataframe to a df variable, I created a list containing the names of the seven different storm categories and named it event_types. I for-looped over this list and used it to filter the dataframe, creating a dictionary for each event type and appending it to the data list. This way I have my list of dictionaries, data." }, { "code": null, "e": 5194, "s": 4856, "text": "The reason why I assigned an opacity value of 0.5 to the markers is because, most likely, there will be areas with more points than others. Giving some sort of transparency to the points, will allow us to see different shades of the same color on the map, corresponding to different frequencies of the same phenomenon in different areas." }, { "code": null, "e": 5288, "s": 5194, "text": "We are done with data, and now it’s layout’s turn, which will definitively require more work." }, { "code": null, "e": 5329, "s": 5288, "text": "Let’s set the basic settings of the map." }, { "code": null, "e": 5420, "s": 5329, "text": "Now we can start adding things to the map to customize it and make interactive as we like." }, { "code": null, "e": 5978, "s": 5420, "text": "Let’s say I want to put a black box with white text on it, that specifies that my points represent only storm events from year 2000 up to now, that caused more than $50k of economic damage. Some static prompt like this, will fall under the annotation key of the layout dictionary: the value corresponding to annotation will need to be a list of dictionaries and in this specific case, a list containing only one dictionary since I want to put only one annotation on my map. It seems cumbersome in words, but doing it is definitely easier than explaining it." }, { "code": null, "e": 6097, "s": 5978, "text": "Now it’s time for the drop-down menus, which will need to be assigned to the updatemenus key of the layout dictionary." }, { "code": null, "e": 6429, "s": 6097, "text": "I want to add two drop-down menus: one to select the type of storm event to visualize, in case we want to look at only of type instead of all of them, while the other drop-down will allow us to change the type of map on the background, which is dark by default. The name and the styles of the available maps can be found on Mapbox." }, { "code": null, "e": 6592, "s": 6429, "text": "Every drop-down menu is defined again through a dictionary, and all these dictionaries will be contained into a list that we will assign to layout['updatemenus']." }, { "code": null, "e": 6706, "s": 6592, "text": "If you want, you can easily assign a title to your plot. I did so just by doing layout['title'] = 'Storm Events'." }, { "code": null, "e": 6791, "s": 6706, "text": "Once we have our data and layout in order, we can generate the plot just by running:" }, { "code": null, "e": 6884, "s": 6791, "text": "figure = dict(data = data, layout = layout)py.iplot(figure, filename = 'put_your_name_here')" }, { "code": null, "e": 6895, "s": 6884, "text": "Et voilà!" }, { "code": null, "e": 7169, "s": 6895, "text": "You can zoom in, zoom out, select what you want to visualize from the top menu, and change the map type from the menu on the bottom. Pretty cool! I look forward to work on some other plots like this, now that I learned how to do it. Hopefully you found this useful as well!" }, { "code": null, "e": 7193, "s": 7169, "text": "Feel free to check out:" }, { "code": null, "e": 7228, "s": 7193, "text": "the Github repository of this code" }, { "code": null, "e": 7251, "s": 7228, "text": "my other Medium posts." }, { "code": null, "e": 7272, "s": 7251, "text": "my LinkedIn profile." } ]
Bank Institution Term Deposit Predictive Model | by Glory Odeyemi | Towards Data Science
Courtesy of the 10 Academy training program, I’ve been introduced to many data science concepts by working on different projects, each of them challenging in their own way. Bank Institution Term Deposit Predictive Model is a project I found interesting. Its main objective is to build a model that predicts the customers that would or would not subscribe to bank term deposits, and this article aims at sharing my step by step approach of building the model. The Data Exploratory Data Analysis Data Preprocessing Machine Learning Model Comparing Results Prediction Conclusion Further Study The dataset (Bank-additional-full.csv) used in this project contains bank customers’ data. The dataset, together with its information, can be gotten here. The first step to take when performing data analysis is to import the necessary libraries and the dataset to get you going. # importing the necessary librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport matplotlib as mplimport seaborn as snsimport warningswarnings.filterwarnings('ignore')#importing the datasetdataset = pd.read_csv('bank-additional-full.csv', sep=';')dataset.name = 'dataset'dataset.head() EDA is an essential part of machine learning model development because it helps us in understanding our data and extract useful insights that will help in feature engineering. Some of the EDA performed in this project includes but not limited to the following; Shape and size of dataset # function to check the shape of a datasetdef data_shape(data): print(data.name,'shape:',data.shape)# function to check the size of a datasetdef data_size(data): print(data.name,'size:',data.size)# Getting the shape of the datasetdata_shape(dataset)# Getting the size of the datasetdata_size(dataset) dataset shape: (41188, 21)dataset size: 864948 .shape returns the number of rows and columns of the dataset. .size returns the number of elements in the data i.e the number of rows times number of columns. Information and Statistical summary # function to ckeck the information of a datasetdef data_info(data): print(data.name,'information:') print('---------------------------------------------') print(data.info()) print('---------------------------------------------')# Getting the information of the datasetdata_info(dataset) .info() is used to get concise summary of the dataset. # Getting the statistical summarydataset.describe().T .describe() is used to view some basic statistical details like percentile, mean, std etc. of numerical columns in the dataset. Unique and missing values # function to get all unique values in the categorical variablesdef unique_val(data): cols = data.columns for i in cols: if data[i].dtype == 'O': print('Unique values in',i,'are',data[i].unique()) print('----------------------------------------------')# Getting the unique values in the categorical columnsunique_val(dataset) .unique() returns the unique values in a categorical column of the dataset. # function to check for missing valuesdef missing_val(data): print('Sum of missing values in', data.name) print('------------------------------') print(data.isnull().sum()) print('------------------------------')# Getting the missing values in the datasetmissing_val(dataset) .isnull().sum() returns the sum of missing values in each column of the dataset. Luckily for us, our dataset does not have missing values. Categorical and numerical variables # Categorical variablescat_data = dataset.select_dtypes(exclude='number')cat_data.head()# Numerical variablesnum_data = dataset.select_dtypes(include='number')num_data.head() .select_dtypes(exclude=’number) returns all the columns that does not have a numerical data type. .select_dtypes(exclude=’number) returns all the columns that has a numerical data type. Univariate and Bivariate Analysis I made use of tableau (a data visualization tool) for the univariate and bivariate analysis and the tableau story can be found here. Correlation # using heatmap to visualize correlation between the columnsfig_size(20,10)ax = sns.heatmap(dataset.corr(), annot=True, fmt='.1g', vmin=-1, vmax=1, center= 0)# setting the parametersfig_att(ax, "Heatmap correlation between Data Features", "Features", "Features", 35, 25, "bold")plt.show() Correlation shows the relationship between variables in the dataset. Outliers Seaborn boxplot is one of the ways of checking a dataset for outliers. # Using boxplot to identify outliersfor col in num_data: ax = sns.boxplot(num_data[col]) save(f"{col}") plt.show() The code above visualizes the numerical columns in the dataset and outliers detected were treated using the Interquartile Range (IQR) method. The code can be found in this GitHub repository. In the course of the EDA, I found out that our target variable ‘y’ — has the client subscribed to a term deposit? (binary: ‘yes’,’no’), is highly imbalanced and that can affect our prediction model. This will be taken care of shortly and this article gives justice to some techniques of dealing with class imbalance. When building a machine learning model, it is important to preprocess the data to have an efficient model. # create list containing categorical columnscat_cols = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome']# create list containing numerical columnsnum_cols = ['duration', 'campaign', 'emp.var.rate',"pdays","age", 'cons.price.idx', 'cons.conf.idx', 'euribor3m', 'nr.employed', 'previous'] The following preprocessing was done in this stage: Encoding Categorical columns Machine learning algorithms only read numerical values, which is why we need to change our categorical values to numerical values. I made use of pandas get_dummies method and type-casting to one-hot encode the columns. # function to encode categorical columnsdef encode(data): cat_var_enc = pd.get_dummies(data[cat_cols], drop_first=False) return cat_var_enc# defining output variable for classificationdataset_new['subscribed'] = (dataset_new.y == 'yes').astype('int') Rescaling Numerical columns Another data preprocessing method is to rescale our numerical columns; this helps to normalize our data within a particular range. Sklearn preprocessing StandardScaler() was used here. # import library for rescalingfrom sklearn.preprocessing import StandardScaler# function to rescale numerical columnsdef rescale(data): # creating an instance of the scaler object scaler = StandardScaler() data[num_cols] = scaler.fit_transform(data[num_cols]) return data Specifying Dependent and Independent Variables To proceed in building our prediction model, we have to specify our dependent and independent variables. Independent variables — are the input for a process that is being analyzed. Dependent variable — Dependent variable is the output of the process. X = data.drop(columns=[ "subscribed", 'duration'])y = data["subscribed"] The column ‘duration’ was dropped because it highly affects the output target (e.g., if duration=0 then y=’no’). Splitting the Dataset It is reasonable to always split the dataset into train and test set when building a machine learning model because it helps us to evaluate the performance of the model. # import library for splitting datasetfrom sklearn.model_selection import train_test_split# split the dataX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.1,random_state=1) Dimensionality Reduction In a case whereby we have a large number of variables, it is advisable to consider reducing these variables by keeping the most important ones, and there are various techniques for doing this, such as; PCA, TSNE, autoencoders, etc. For this project, we will be considering PCA. # import PCAfrom sklearn.decomposition import PCA# create an instance of pcapca = PCA(n_components=20) # fit pca to our datapca.fit(X_train)pca_train = pca.transform(X_train)X_train_reduced = pd.DataFrame(pca_train) Class Imbalance As earlier stated, we have a highly imbalanced class, and this can affect our prediction if not treated. In this project, I made use of SMOTE (Synthetic Minority Oversampling Technique) for dealing with class imbalance. # importing the necessary function from imblearn.over_sampling import SMOTE# creating an instancesm = SMOTE(random_state=27)# applying it to the training setX_train_smote, y_train_smote = sm.fit_sample(X_train_reduced, y_train) Note: It is advisable to use SMOTE on the training data. Whew!, we finally made it to building the model; data preprocessing can be such a handful when trying to build a machine learning model. Let’s not waste any time and dive right in. The machine learning algorithm that was considered in this project includes; Logistic Regression XGBoost Multi Layer Perceptron and the cross validation (this is essential especially in our case where we have an imbalanced class) method used includes; K-Fold: K-Fold splits a given data set into a K number of sections/folds where each fold is used as a testing set at some point. Stratified K-Fold: This is a variation of K-Fold that returns stratified folds. The folds are made by preserving the percentage of samples for each class. # import machine learning model librariesfrom sklearn.linear_model import LogisticRegressionfrom xgboost import XGBClassifierfrom sklearn.neural_network import MLPClassifier# import libraries for cross validationfrom sklearn.model_selection import KFoldfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.model_selection import cross_validatemetrics = ['accuracy', 'roc_auc', f1', 'precision', 'recall']# function to build machine learning modelsdef model(model, cv_method, metrics, X_train, X_test, y_train): if (model == 'LR'): # creating an instance of the regression model_inst = LogisticRegression() print('Logistic Regression\n----------------------') elif (model == 'XGB'): # creating an instance of the classifier model_inst = XGBClassifier() print('XGBoost\n----------------------') elif (model == 'MLP'): # creating an instance of the classifier model_inst = MLPClassifier() print('Multi Layer Perceptron\n----------------------') # cross validation if (cv_method == 'KFold'): print('Cross validation: KFold\n--------------------------') cv = KFold(n_splits=10, random_state=100) elif (cv_method == 'StratifiedKFold'): print('Cross validation: StratifiedKFold\n-----------------') cv = StratifiedKFold(n_splits=10, random_state=100) else: print('Cross validation method not found!') try: cv_scores = cross_validate(model_inst, X_train, y_train, cv=cv, scoring=metrics) # displaying evaluation metric scores cv_metric = cv_scores.keys() for metric in cv_metric: mean_score = cv_scores[metric].mean()*100 print(metric+':', '%.2f%%' % mean_score) print('') except: metrics = ['accuracy', 'f1', 'precision', 'recall'] cv_scores = cross_validate(model_inst, X_train, y_train, cv=cv, scoring=metrics) # displaying evaluation metric scores cv_metric = cv_scores.keys() for metric in cv_metric: mean_score = cv_scores[metric].mean()*100 print(metric+':', '%.2f%%' % mean_score) print('') return model_inst Evaluation Metrics Accuracy: The number of correctly predicted data points. This can be a misleading metric for an imbalanced dataset. Therefore, it is advisable to consider other evaluation metrics. AUC (Area under the ROC Curve): It provides an aggregate measure of performance across all possible classification thresholds. Precision: It is calculated as the ratio of correctly predicted positive examples divided by the total number of positive examples that were predicted. Recall: It refers to the percentage of total relevant results correctly classified by your algorithm. F1 score: This is the weighted average of Precision and Recall. K-Fold vs Stratified K-Fold As can be seen from the table above, Stratified K-Fold presented a much better result compared to the K-Fold cross validation. The K-Fold cross validation failed to provide the AUC score for the Logistic Regression and XGBoost model. Therefore, for further comparison, Stratified K-Fold results would be used. Machine Learning Models From the result gotten, XGBoost proves to be a better prediction model than Logistic Regression and MLP because it has the highest percentage values in 4/5 of the evaluation metrics. XGboost, being the best performing model, is used for prediction. # fitting the model to the train datamodel_xgb = xgb.fit(X_train_smote, y_train_smote)# make predictionsy_pred = xgb.predict(X_test_pca) The main objective of this project is to build a model that predicts customers that would subscribe to a bank term deposit, and we were able to achieve that by considering three different models and using the best one for the prediction. We also went through rigorous steps of preparing our data for the model and choosing various evaluation metrics to measure the performance of our models. In the result gotten, we observe that XGBoost was the best model with high percentage values in 4/5 of the evaluation metrics. In this project, I used only three machine learning algorithms. However, algorithms such as; SVM, Random Forest, Decision Trees, etc. can be explored. A detailed code for this project can be found in this GitHub repository. I know this was a very long ride, but thank you for sticking with me to the end. I also appreciate 10 Academy once again, and my fellow learners for the wonderful opportunity to partake in this project. Grammar checker Class Imbalance Dataset Feature Engineering Principal Component Analysis (PCA) Tableau Machine Learning Algorithms
[ { "code": null, "e": 344, "s": 171, "text": "Courtesy of the 10 Academy training program, I’ve been introduced to many data science concepts by working on different projects, each of them challenging in their own way." }, { "code": null, "e": 630, "s": 344, "text": "Bank Institution Term Deposit Predictive Model is a project I found interesting. Its main objective is to build a model that predicts the customers that would or would not subscribe to bank term deposits, and this article aims at sharing my step by step approach of building the model." }, { "code": null, "e": 639, "s": 630, "text": "The Data" }, { "code": null, "e": 665, "s": 639, "text": "Exploratory Data Analysis" }, { "code": null, "e": 684, "s": 665, "text": "Data Preprocessing" }, { "code": null, "e": 707, "s": 684, "text": "Machine Learning Model" }, { "code": null, "e": 725, "s": 707, "text": "Comparing Results" }, { "code": null, "e": 736, "s": 725, "text": "Prediction" }, { "code": null, "e": 747, "s": 736, "text": "Conclusion" }, { "code": null, "e": 761, "s": 747, "text": "Further Study" }, { "code": null, "e": 1040, "s": 761, "text": "The dataset (Bank-additional-full.csv) used in this project contains bank customers’ data. The dataset, together with its information, can be gotten here. The first step to take when performing data analysis is to import the necessary libraries and the dataset to get you going." }, { "code": null, "e": 1355, "s": 1040, "text": "# importing the necessary librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport matplotlib as mplimport seaborn as snsimport warningswarnings.filterwarnings('ignore')#importing the datasetdataset = pd.read_csv('bank-additional-full.csv', sep=';')dataset.name = 'dataset'dataset.head()" }, { "code": null, "e": 1616, "s": 1355, "text": "EDA is an essential part of machine learning model development because it helps us in understanding our data and extract useful insights that will help in feature engineering. Some of the EDA performed in this project includes but not limited to the following;" }, { "code": null, "e": 1642, "s": 1616, "text": "Shape and size of dataset" }, { "code": null, "e": 1949, "s": 1642, "text": "# function to check the shape of a datasetdef data_shape(data): print(data.name,'shape:',data.shape)# function to check the size of a datasetdef data_size(data): print(data.name,'size:',data.size)# Getting the shape of the datasetdata_shape(dataset)# Getting the size of the datasetdata_size(dataset)" }, { "code": null, "e": 1996, "s": 1949, "text": "dataset shape: (41188, 21)dataset size: 864948" }, { "code": null, "e": 2058, "s": 1996, "text": ".shape returns the number of rows and columns of the dataset." }, { "code": null, "e": 2155, "s": 2058, "text": ".size returns the number of elements in the data i.e the number of rows times number of columns." }, { "code": null, "e": 2191, "s": 2155, "text": "Information and Statistical summary" }, { "code": null, "e": 2491, "s": 2191, "text": "# function to ckeck the information of a datasetdef data_info(data): print(data.name,'information:') print('---------------------------------------------') print(data.info()) print('---------------------------------------------')# Getting the information of the datasetdata_info(dataset)" }, { "code": null, "e": 2546, "s": 2491, "text": ".info() is used to get concise summary of the dataset." }, { "code": null, "e": 2600, "s": 2546, "text": "# Getting the statistical summarydataset.describe().T" }, { "code": null, "e": 2728, "s": 2600, "text": ".describe() is used to view some basic statistical details like percentile, mean, std etc. of numerical columns in the dataset." }, { "code": null, "e": 2754, "s": 2728, "text": "Unique and missing values" }, { "code": null, "e": 3115, "s": 2754, "text": "# function to get all unique values in the categorical variablesdef unique_val(data): cols = data.columns for i in cols: if data[i].dtype == 'O': print('Unique values in',i,'are',data[i].unique()) print('----------------------------------------------')# Getting the unique values in the categorical columnsunique_val(dataset)" }, { "code": null, "e": 3191, "s": 3115, "text": ".unique() returns the unique values in a categorical column of the dataset." }, { "code": null, "e": 3479, "s": 3191, "text": "# function to check for missing valuesdef missing_val(data): print('Sum of missing values in', data.name) print('------------------------------') print(data.isnull().sum()) print('------------------------------')# Getting the missing values in the datasetmissing_val(dataset)" }, { "code": null, "e": 3618, "s": 3479, "text": ".isnull().sum() returns the sum of missing values in each column of the dataset. Luckily for us, our dataset does not have missing values." }, { "code": null, "e": 3654, "s": 3618, "text": "Categorical and numerical variables" }, { "code": null, "e": 3829, "s": 3654, "text": "# Categorical variablescat_data = dataset.select_dtypes(exclude='number')cat_data.head()# Numerical variablesnum_data = dataset.select_dtypes(include='number')num_data.head()" }, { "code": null, "e": 3927, "s": 3829, "text": ".select_dtypes(exclude=’number) returns all the columns that does not have a numerical data type." }, { "code": null, "e": 4015, "s": 3927, "text": ".select_dtypes(exclude=’number) returns all the columns that has a numerical data type." }, { "code": null, "e": 4049, "s": 4015, "text": "Univariate and Bivariate Analysis" }, { "code": null, "e": 4182, "s": 4049, "text": "I made use of tableau (a data visualization tool) for the univariate and bivariate analysis and the tableau story can be found here." }, { "code": null, "e": 4194, "s": 4182, "text": "Correlation" }, { "code": null, "e": 4508, "s": 4194, "text": "# using heatmap to visualize correlation between the columnsfig_size(20,10)ax = sns.heatmap(dataset.corr(), annot=True, fmt='.1g', vmin=-1, vmax=1, center= 0)# setting the parametersfig_att(ax, \"Heatmap correlation between Data Features\", \"Features\", \"Features\", 35, 25, \"bold\")plt.show()" }, { "code": null, "e": 4577, "s": 4508, "text": "Correlation shows the relationship between variables in the dataset." }, { "code": null, "e": 4586, "s": 4577, "text": "Outliers" }, { "code": null, "e": 4657, "s": 4586, "text": "Seaborn boxplot is one of the ways of checking a dataset for outliers." }, { "code": null, "e": 4781, "s": 4657, "text": "# Using boxplot to identify outliersfor col in num_data: ax = sns.boxplot(num_data[col]) save(f\"{col}\") plt.show()" }, { "code": null, "e": 4972, "s": 4781, "text": "The code above visualizes the numerical columns in the dataset and outliers detected were treated using the Interquartile Range (IQR) method. The code can be found in this GitHub repository." }, { "code": null, "e": 5289, "s": 4972, "text": "In the course of the EDA, I found out that our target variable ‘y’ — has the client subscribed to a term deposit? (binary: ‘yes’,’no’), is highly imbalanced and that can affect our prediction model. This will be taken care of shortly and this article gives justice to some techniques of dealing with class imbalance." }, { "code": null, "e": 5396, "s": 5289, "text": "When building a machine learning model, it is important to preprocess the data to have an efficient model." }, { "code": null, "e": 5759, "s": 5396, "text": "# create list containing categorical columnscat_cols = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome']# create list containing numerical columnsnum_cols = ['duration', 'campaign', 'emp.var.rate',\"pdays\",\"age\", 'cons.price.idx', 'cons.conf.idx', 'euribor3m', 'nr.employed', 'previous']" }, { "code": null, "e": 5811, "s": 5759, "text": "The following preprocessing was done in this stage:" }, { "code": null, "e": 5840, "s": 5811, "text": "Encoding Categorical columns" }, { "code": null, "e": 6059, "s": 5840, "text": "Machine learning algorithms only read numerical values, which is why we need to change our categorical values to numerical values. I made use of pandas get_dummies method and type-casting to one-hot encode the columns." }, { "code": null, "e": 6316, "s": 6059, "text": "# function to encode categorical columnsdef encode(data): cat_var_enc = pd.get_dummies(data[cat_cols], drop_first=False) return cat_var_enc# defining output variable for classificationdataset_new['subscribed'] = (dataset_new.y == 'yes').astype('int')" }, { "code": null, "e": 6344, "s": 6316, "text": "Rescaling Numerical columns" }, { "code": null, "e": 6529, "s": 6344, "text": "Another data preprocessing method is to rescale our numerical columns; this helps to normalize our data within a particular range. Sklearn preprocessing StandardScaler() was used here." }, { "code": null, "e": 6813, "s": 6529, "text": "# import library for rescalingfrom sklearn.preprocessing import StandardScaler# function to rescale numerical columnsdef rescale(data): # creating an instance of the scaler object scaler = StandardScaler() data[num_cols] = scaler.fit_transform(data[num_cols]) return data" }, { "code": null, "e": 6860, "s": 6813, "text": "Specifying Dependent and Independent Variables" }, { "code": null, "e": 6965, "s": 6860, "text": "To proceed in building our prediction model, we have to specify our dependent and independent variables." }, { "code": null, "e": 7041, "s": 6965, "text": "Independent variables — are the input for a process that is being analyzed." }, { "code": null, "e": 7111, "s": 7041, "text": "Dependent variable — Dependent variable is the output of the process." }, { "code": null, "e": 7184, "s": 7111, "text": "X = data.drop(columns=[ \"subscribed\", 'duration'])y = data[\"subscribed\"]" }, { "code": null, "e": 7297, "s": 7184, "text": "The column ‘duration’ was dropped because it highly affects the output target (e.g., if duration=0 then y=’no’)." }, { "code": null, "e": 7319, "s": 7297, "text": "Splitting the Dataset" }, { "code": null, "e": 7489, "s": 7319, "text": "It is reasonable to always split the dataset into train and test set when building a machine learning model because it helps us to evaluate the performance of the model." }, { "code": null, "e": 7680, "s": 7489, "text": "# import library for splitting datasetfrom sklearn.model_selection import train_test_split# split the dataX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.1,random_state=1)" }, { "code": null, "e": 7705, "s": 7680, "text": "Dimensionality Reduction" }, { "code": null, "e": 7983, "s": 7705, "text": "In a case whereby we have a large number of variables, it is advisable to consider reducing these variables by keeping the most important ones, and there are various techniques for doing this, such as; PCA, TSNE, autoencoders, etc. For this project, we will be considering PCA." }, { "code": null, "e": 8204, "s": 7983, "text": "# import PCAfrom sklearn.decomposition import PCA# create an instance of pcapca = PCA(n_components=20) # fit pca to our datapca.fit(X_train)pca_train = pca.transform(X_train)X_train_reduced = pd.DataFrame(pca_train)" }, { "code": null, "e": 8220, "s": 8204, "text": "Class Imbalance" }, { "code": null, "e": 8325, "s": 8220, "text": "As earlier stated, we have a highly imbalanced class, and this can affect our prediction if not treated." }, { "code": null, "e": 8440, "s": 8325, "text": "In this project, I made use of SMOTE (Synthetic Minority Oversampling Technique) for dealing with class imbalance." }, { "code": null, "e": 8668, "s": 8440, "text": "# importing the necessary function from imblearn.over_sampling import SMOTE# creating an instancesm = SMOTE(random_state=27)# applying it to the training setX_train_smote, y_train_smote = sm.fit_sample(X_train_reduced, y_train)" }, { "code": null, "e": 8725, "s": 8668, "text": "Note: It is advisable to use SMOTE on the training data." }, { "code": null, "e": 8906, "s": 8725, "text": "Whew!, we finally made it to building the model; data preprocessing can be such a handful when trying to build a machine learning model. Let’s not waste any time and dive right in." }, { "code": null, "e": 8983, "s": 8906, "text": "The machine learning algorithm that was considered in this project includes;" }, { "code": null, "e": 9003, "s": 8983, "text": "Logistic Regression" }, { "code": null, "e": 9011, "s": 9003, "text": "XGBoost" }, { "code": null, "e": 9034, "s": 9011, "text": "Multi Layer Perceptron" }, { "code": null, "e": 9158, "s": 9034, "text": "and the cross validation (this is essential especially in our case where we have an imbalanced class) method used includes;" }, { "code": null, "e": 9287, "s": 9158, "text": "K-Fold: K-Fold splits a given data set into a K number of sections/folds where each fold is used as a testing set at some point." }, { "code": null, "e": 9442, "s": 9287, "text": "Stratified K-Fold: This is a variation of K-Fold that returns stratified folds. The folds are made by preserving the percentage of samples for each class." }, { "code": null, "e": 11708, "s": 9442, "text": "# import machine learning model librariesfrom sklearn.linear_model import LogisticRegressionfrom xgboost import XGBClassifierfrom sklearn.neural_network import MLPClassifier# import libraries for cross validationfrom sklearn.model_selection import KFoldfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.model_selection import cross_validatemetrics = ['accuracy', 'roc_auc', f1', 'precision', 'recall']# function to build machine learning modelsdef model(model, cv_method, metrics, X_train, X_test, y_train): if (model == 'LR'): # creating an instance of the regression model_inst = LogisticRegression() print('Logistic Regression\\n----------------------') elif (model == 'XGB'): # creating an instance of the classifier model_inst = XGBClassifier() print('XGBoost\\n----------------------') elif (model == 'MLP'): # creating an instance of the classifier model_inst = MLPClassifier() print('Multi Layer Perceptron\\n----------------------') # cross validation if (cv_method == 'KFold'): print('Cross validation: KFold\\n--------------------------') cv = KFold(n_splits=10, random_state=100) elif (cv_method == 'StratifiedKFold'): print('Cross validation: StratifiedKFold\\n-----------------') cv = StratifiedKFold(n_splits=10, random_state=100) else: print('Cross validation method not found!') try: cv_scores = cross_validate(model_inst, X_train, y_train, cv=cv, scoring=metrics) # displaying evaluation metric scores cv_metric = cv_scores.keys() for metric in cv_metric: mean_score = cv_scores[metric].mean()*100 print(metric+':', '%.2f%%' % mean_score) print('') except: metrics = ['accuracy', 'f1', 'precision', 'recall'] cv_scores = cross_validate(model_inst, X_train, y_train, cv=cv, scoring=metrics) # displaying evaluation metric scores cv_metric = cv_scores.keys() for metric in cv_metric: mean_score = cv_scores[metric].mean()*100 print(metric+':', '%.2f%%' % mean_score) print('') return model_inst" }, { "code": null, "e": 11727, "s": 11708, "text": "Evaluation Metrics" }, { "code": null, "e": 11908, "s": 11727, "text": "Accuracy: The number of correctly predicted data points. This can be a misleading metric for an imbalanced dataset. Therefore, it is advisable to consider other evaluation metrics." }, { "code": null, "e": 12035, "s": 11908, "text": "AUC (Area under the ROC Curve): It provides an aggregate measure of performance across all possible classification thresholds." }, { "code": null, "e": 12187, "s": 12035, "text": "Precision: It is calculated as the ratio of correctly predicted positive examples divided by the total number of positive examples that were predicted." }, { "code": null, "e": 12289, "s": 12187, "text": "Recall: It refers to the percentage of total relevant results correctly classified by your algorithm." }, { "code": null, "e": 12353, "s": 12289, "text": "F1 score: This is the weighted average of Precision and Recall." }, { "code": null, "e": 12381, "s": 12353, "text": "K-Fold vs Stratified K-Fold" }, { "code": null, "e": 12691, "s": 12381, "text": "As can be seen from the table above, Stratified K-Fold presented a much better result compared to the K-Fold cross validation. The K-Fold cross validation failed to provide the AUC score for the Logistic Regression and XGBoost model. Therefore, for further comparison, Stratified K-Fold results would be used." }, { "code": null, "e": 12715, "s": 12691, "text": "Machine Learning Models" }, { "code": null, "e": 12898, "s": 12715, "text": "From the result gotten, XGBoost proves to be a better prediction model than Logistic Regression and MLP because it has the highest percentage values in 4/5 of the evaluation metrics." }, { "code": null, "e": 12964, "s": 12898, "text": "XGboost, being the best performing model, is used for prediction." }, { "code": null, "e": 13101, "s": 12964, "text": "# fitting the model to the train datamodel_xgb = xgb.fit(X_train_smote, y_train_smote)# make predictionsy_pred = xgb.predict(X_test_pca)" }, { "code": null, "e": 13493, "s": 13101, "text": "The main objective of this project is to build a model that predicts customers that would subscribe to a bank term deposit, and we were able to achieve that by considering three different models and using the best one for the prediction. We also went through rigorous steps of preparing our data for the model and choosing various evaluation metrics to measure the performance of our models." }, { "code": null, "e": 13620, "s": 13493, "text": "In the result gotten, we observe that XGBoost was the best model with high percentage values in 4/5 of the evaluation metrics." }, { "code": null, "e": 13771, "s": 13620, "text": "In this project, I used only three machine learning algorithms. However, algorithms such as; SVM, Random Forest, Decision Trees, etc. can be explored." }, { "code": null, "e": 13844, "s": 13771, "text": "A detailed code for this project can be found in this GitHub repository." }, { "code": null, "e": 14047, "s": 13844, "text": "I know this was a very long ride, but thank you for sticking with me to the end. I also appreciate 10 Academy once again, and my fellow learners for the wonderful opportunity to partake in this project." }, { "code": null, "e": 14063, "s": 14047, "text": "Grammar checker" }, { "code": null, "e": 14079, "s": 14063, "text": "Class Imbalance" }, { "code": null, "e": 14087, "s": 14079, "text": "Dataset" }, { "code": null, "e": 14107, "s": 14087, "text": "Feature Engineering" }, { "code": null, "e": 14142, "s": 14107, "text": "Principal Component Analysis (PCA)" }, { "code": null, "e": 14150, "s": 14142, "text": "Tableau" } ]
C Program for Merge Sort - GeeksforGeeks
13 Feb, 2018 Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. /* C program for Merge Sort */#include<stdlib.h>#include<stdio.h> // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l+(r-l)/2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m+1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */void printArray(int A[], int size){ int i; for (i=0; i < size; i++) printf("%d ", A[i]); printf("\n");} /* Driver program to test above functions */int main(){ int arr[] = {12, 11, 13, 5, 6, 7}; int arr_size = sizeof(arr)/sizeof(arr[0]); printf("Given array is \n"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); printf("\nSorted array is \n"); printArray(arr, arr_size); return 0;} Please refer complete article on Merge Sort for more details! Merge Sort C Programs Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File How to Append a Character to a String in C Producer Consumer Problem in C Program to calculate First and Follow sets of given grammar time() function in C Program to find Prime Numbers Between given Interval C Program to Swap two Numbers C program to find the length of a string Flex (Fast Lexical Analyzer Generator ) Set, Clear and Toggle a given bit of a number in C
[ { "code": null, "e": 24774, "s": 24746, "text": "\n13 Feb, 2018" }, { "code": null, "e": 25123, "s": 24774, "text": "Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one." }, { "code": "/* C program for Merge Sort */#include<stdlib.h>#include<stdio.h> // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l+(r-l)/2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m+1, r); merge(arr, l, m, r); }} /* UTILITY FUNCTIONS *//* Function to print an array */void printArray(int A[], int size){ int i; for (i=0; i < size; i++) printf(\"%d \", A[i]); printf(\"\\n\");} /* Driver program to test above functions */int main(){ int arr[] = {12, 11, 13, 5, 6, 7}; int arr_size = sizeof(arr)/sizeof(arr[0]); printf(\"Given array is \\n\"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); printf(\"\\nSorted array is \\n\"); printArray(arr, arr_size); return 0;}", "e": 27168, "s": 25123, "text": null }, { "code": null, "e": 27230, "s": 27168, "text": "Please refer complete article on Merge Sort for more details!" }, { "code": null, "e": 27241, "s": 27230, "text": "Merge Sort" }, { "code": null, "e": 27252, "s": 27241, "text": "C Programs" }, { "code": null, "e": 27263, "s": 27252, "text": "Merge Sort" }, { "code": null, "e": 27361, "s": 27263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27402, "s": 27361, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27445, "s": 27402, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 27476, "s": 27445, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 27536, "s": 27476, "text": "Program to calculate First and Follow sets of given grammar" }, { "code": null, "e": 27557, "s": 27536, "text": "time() function in C" }, { "code": null, "e": 27610, "s": 27557, "text": "Program to find Prime Numbers Between given Interval" }, { "code": null, "e": 27640, "s": 27610, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 27681, "s": 27640, "text": "C program to find the length of a string" }, { "code": null, "e": 27721, "s": 27681, "text": "Flex (Fast Lexical Analyzer Generator )" } ]
Python – Assigning Subsequent Rows to Matrix first row elements
30 Dec, 2020 Given a (N + 1) * N Matrix, assign each column of 1st row of matrix, the subsequent row of Matrix. Input : test_list = [[5, 8, 10], [2, 0, 9], [5, 4, 2], [2, 3, 9]]Output : {5: [2, 0, 9], 8: [5, 4, 2], 10: [2, 3, 9]}Explanation : 5 paired with 2nd row, 8 with 3rd and 10 with 4th Input : test_list = [[5, 8], [2, 0], [5, 4]]Output : {5: [2, 0], 8: [5, 4]}Explanation : 5 paired with 2nd row, 8 with 3rd. Method #1 : Using dictionary comprehension This is one of the ways in which this task can be performed. In this, we iterate for rows and corresponding columns using loop and assign value list accordingly in one-liner way using dictionary comprehension. Python3 # Python3 code to demonstrate working of # Assigning Subsequent Rows to Matrix first row elements# Using dictionary comprehension # initializing listtest_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]] # printing original listprint("The original list : " + str(test_list)) # pairing each 1st col with next rows in Matrixres = {test_list[0][ele] : test_list[ele + 1] for ele in range(len(test_list) - 1)} # printing result print("The Assigned Matrix : " + str(res)) The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]] The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]} Method #2 : Using zip() + list slicing + dict() This is yet another way in which this task can be performed. In this, we slice elements to be first row and subsequent rows using list slicing and zip() performs the task of required grouping. Returned Python3 # Python3 code to demonstrate working of # Assigning Subsequent Rows to Matrix first row elements# Using zip() + list slicing + dict() # initializing listtest_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]] # printing original listprint("The original list : " + str(test_list)) # dict() to convert back to dict type # slicing and pairing using zip() and list slicingres = dict(zip(test_list[0], test_list[1:])) # printing result print("The Assigned Matrix : " + str(res)) The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]] The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]} Python list-programs Python matrix-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Dec, 2020" }, { "code": null, "e": 152, "s": 53, "text": "Given a (N + 1) * N Matrix, assign each column of 1st row of matrix, the subsequent row of Matrix." }, { "code": null, "e": 333, "s": 152, "text": "Input : test_list = [[5, 8, 10], [2, 0, 9], [5, 4, 2], [2, 3, 9]]Output : {5: [2, 0, 9], 8: [5, 4, 2], 10: [2, 3, 9]}Explanation : 5 paired with 2nd row, 8 with 3rd and 10 with 4th" }, { "code": null, "e": 457, "s": 333, "text": "Input : test_list = [[5, 8], [2, 0], [5, 4]]Output : {5: [2, 0], 8: [5, 4]}Explanation : 5 paired with 2nd row, 8 with 3rd." }, { "code": null, "e": 500, "s": 457, "text": "Method #1 : Using dictionary comprehension" }, { "code": null, "e": 710, "s": 500, "text": "This is one of the ways in which this task can be performed. In this, we iterate for rows and corresponding columns using loop and assign value list accordingly in one-liner way using dictionary comprehension." }, { "code": null, "e": 718, "s": 710, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Assigning Subsequent Rows to Matrix first row elements# Using dictionary comprehension # initializing listtest_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]] # printing original listprint(\"The original list : \" + str(test_list)) # pairing each 1st col with next rows in Matrixres = {test_list[0][ele] : test_list[ele + 1] for ele in range(len(test_list) - 1)} # printing result print(\"The Assigned Matrix : \" + str(res))", "e": 1192, "s": 718, "text": null }, { "code": null, "e": 1323, "s": 1192, "text": "The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]\nThe Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}\n" }, { "code": null, "e": 1371, "s": 1323, "text": "Method #2 : Using zip() + list slicing + dict()" }, { "code": null, "e": 1574, "s": 1371, "text": "This is yet another way in which this task can be performed. In this, we slice elements to be first row and subsequent rows using list slicing and zip() performs the task of required grouping. Returned " }, { "code": null, "e": 1582, "s": 1574, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Assigning Subsequent Rows to Matrix first row elements# Using zip() + list slicing + dict() # initializing listtest_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]] # printing original listprint(\"The original list : \" + str(test_list)) # dict() to convert back to dict type # slicing and pairing using zip() and list slicingres = dict(zip(test_list[0], test_list[1:])) # printing result print(\"The Assigned Matrix : \" + str(res))", "e": 2062, "s": 1582, "text": null }, { "code": null, "e": 2193, "s": 2062, "text": "The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]\nThe Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}\n" }, { "code": null, "e": 2214, "s": 2193, "text": "Python list-programs" }, { "code": null, "e": 2236, "s": 2214, "text": "Python matrix-program" }, { "code": null, "e": 2243, "s": 2236, "text": "Python" }, { "code": null, "e": 2259, "s": 2243, "text": "Python Programs" }, { "code": null, "e": 2357, "s": 2259, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2389, "s": 2357, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2416, "s": 2389, "text": "Python Classes and Objects" }, { "code": null, "e": 2437, "s": 2416, "text": "Python OOPs Concepts" }, { "code": null, "e": 2460, "s": 2437, "text": "Introduction To PYTHON" }, { "code": null, "e": 2491, "s": 2460, "text": "Python | os.path.join() method" }, { "code": null, "e": 2513, "s": 2491, "text": "Defaultdict in Python" }, { "code": null, "e": 2552, "s": 2513, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2590, "s": 2552, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2639, "s": 2590, "text": "Python | Convert string dictionary to dictionary" } ]
Difference between Pandas VS NumPy
09 Jun, 2022 Pandas is an open-source, BSD-licensed library written in Python Language. Pandas provide high performance, fast, easy-to-use data structures, and data analysis tools for manipulating numeric data and time series. Pandas is built on the numpy library and written in languages like Python, Cython, and C. In pandas, we can import data from various file formats like JSON, SQL, Microsoft Excel, etc. Example: Python3 # Importing pandas libraryimport pandas as pd # Creating and initializing a nested listage = [['Aman', 95.5, "Male"], ['Sunny', 65.7, "Female"], ['Monty', 85.1, "Male"], ['toni', 75.4, "Male"]] # Creating a pandas dataframedf = pd.DataFrame(age, columns=['Name', 'Marks', 'Gender']) # Printing dataframedf Output: Numpy: It is the fundamental library of python, used to perform scientific computing. It provides high-performance multidimensional arrays and tools to deal with them. A numpy array is a grid of values (of the same type) that are indexed by a tuple of positive integers, numpy arrays are fast, easy to understand, and give users the right to perform calculations across arrays. Example: Python3 # Importing Numpy packageimport numpy as np # Creating a 3-D numpy array using np.array()org_array = np.array([[23, 46, 85], [43, 56, 99], [11, 34, 55]]) # Printing the Numpy arrayprint(org_array) Output: a [23 46 85] [43 56 99] [11 34 55]] Table of Differences Between Pandas VS NumPy is as follows: PANDAS NUMPY siddharthredhu01 Python-numpy Python-pandas Difference Between Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM Difference between Clustered and Non-clustered index Difference between Process and Thread Read JSON file using Python Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2022" }, { "code": null, "e": 450, "s": 52, "text": "Pandas is an open-source, BSD-licensed library written in Python Language. Pandas provide high performance, fast, easy-to-use data structures, and data analysis tools for manipulating numeric data and time series. Pandas is built on the numpy library and written in languages like Python, Cython, and C. In pandas, we can import data from various file formats like JSON, SQL, Microsoft Excel, etc." }, { "code": null, "e": 459, "s": 450, "text": "Example:" }, { "code": null, "e": 467, "s": 459, "text": "Python3" }, { "code": "# Importing pandas libraryimport pandas as pd # Creating and initializing a nested listage = [['Aman', 95.5, \"Male\"], ['Sunny', 65.7, \"Female\"], ['Monty', 85.1, \"Male\"], ['toni', 75.4, \"Male\"]] # Creating a pandas dataframedf = pd.DataFrame(age, columns=['Name', 'Marks', 'Gender']) # Printing dataframedf", "e": 779, "s": 467, "text": null }, { "code": null, "e": 787, "s": 779, "text": "Output:" }, { "code": null, "e": 1165, "s": 787, "text": "Numpy: It is the fundamental library of python, used to perform scientific computing. It provides high-performance multidimensional arrays and tools to deal with them. A numpy array is a grid of values (of the same type) that are indexed by a tuple of positive integers, numpy arrays are fast, easy to understand, and give users the right to perform calculations across arrays." }, { "code": null, "e": 1174, "s": 1165, "text": "Example:" }, { "code": null, "e": 1182, "s": 1174, "text": "Python3" }, { "code": "# Importing Numpy packageimport numpy as np # Creating a 3-D numpy array using np.array()org_array = np.array([[23, 46, 85], [43, 56, 99], [11, 34, 55]]) # Printing the Numpy arrayprint(org_array)", "e": 1421, "s": 1182, "text": null }, { "code": null, "e": 1429, "s": 1421, "text": "Output:" }, { "code": null, "e": 1465, "s": 1429, "text": "a [23 46 85]\n[43 56 99]\n[11 34 55]]" }, { "code": null, "e": 1526, "s": 1465, "text": "Table of Differences Between Pandas VS NumPy is as follows: " }, { "code": null, "e": 1533, "s": 1526, "text": "PANDAS" }, { "code": null, "e": 1539, "s": 1533, "text": "NUMPY" }, { "code": null, "e": 1556, "s": 1539, "text": "siddharthredhu01" }, { "code": null, "e": 1569, "s": 1556, "text": "Python-numpy" }, { "code": null, "e": 1583, "s": 1569, "text": "Python-pandas" }, { "code": null, "e": 1602, "s": 1583, "text": "Difference Between" }, { "code": null, "e": 1609, "s": 1602, "text": "Python" }, { "code": null, "e": 1707, "s": 1609, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1768, "s": 1707, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1836, "s": 1768, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 1873, "s": 1836, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 1926, "s": 1873, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 1964, "s": 1926, "text": "Difference between Process and Thread" }, { "code": null, "e": 1992, "s": 1964, "text": "Read JSON file using Python" }, { "code": null, "e": 2014, "s": 1992, "text": "Python map() function" }, { "code": null, "e": 2058, "s": 2014, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2076, "s": 2058, "text": "Python Dictionary" } ]
Get tag name using Beautifulsoup in Python
11 Oct, 2020 Prerequisite: Beautifulsoup Installation Name property is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. Name object corresponds to the name of an XML or HTML tag in the original document. Syntax: tag.name Parameters: This function doesn’t accept any parameter. Implementation:Example 1: Program to extract name of a XML tag. Python3 # Import modulefrom bs4 import BeautifulSoup # Initialize the object with a XMLsoup = BeautifulSoup(''' <root> <name_of_tag>the first strong tag</name_of_tag> </root> ''', "lxml") # Get the tagtag = soup.name_of_tag # Get the tag namename = tag.name # Print the outputprint(name) Output: name_of_tag Example 2: Program that explains the above functionality for a HTML tag. Python3 # Import modulefrom bs4 import BeautifulSoup # Initialize the object with a HTML pagesoup = BeautifulSoup(''' <html> <h2> Heading 1 </h2> <h1> Heading 2 </h1> </html> ''', "lxml") # Get the whole h2 tagtag = soup.h2 # Get the name of the tagname = tag.name # Print the outputprint(name) Output: h2 Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2020" }, { "code": null, "e": 69, "s": 28, "text": "Prerequisite: Beautifulsoup Installation" }, { "code": null, "e": 357, "s": 69, "text": "Name property is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. Name object corresponds to the name of an XML or HTML tag in the original document." }, { "code": null, "e": 365, "s": 357, "text": "Syntax:" }, { "code": null, "e": 374, "s": 365, "text": "tag.name" }, { "code": null, "e": 430, "s": 374, "text": "Parameters: This function doesn’t accept any parameter." }, { "code": null, "e": 494, "s": 430, "text": "Implementation:Example 1: Program to extract name of a XML tag." }, { "code": null, "e": 502, "s": 494, "text": "Python3" }, { "code": "# Import modulefrom bs4 import BeautifulSoup # Initialize the object with a XMLsoup = BeautifulSoup(''' <root> <name_of_tag>the first strong tag</name_of_tag> </root> ''', \"lxml\") # Get the tagtag = soup.name_of_tag # Get the tag namename = tag.name # Print the outputprint(name)", "e": 802, "s": 502, "text": null }, { "code": null, "e": 810, "s": 802, "text": "Output:" }, { "code": null, "e": 823, "s": 810, "text": "name_of_tag\n" }, { "code": null, "e": 896, "s": 823, "text": "Example 2: Program that explains the above functionality for a HTML tag." }, { "code": null, "e": 904, "s": 896, "text": "Python3" }, { "code": "# Import modulefrom bs4 import BeautifulSoup # Initialize the object with a HTML pagesoup = BeautifulSoup(''' <html> <h2> Heading 1 </h2> <h1> Heading 2 </h1> </html> ''', \"lxml\") # Get the whole h2 tagtag = soup.h2 # Get the name of the tagname = tag.name # Print the outputprint(name)", "e": 1218, "s": 904, "text": null }, { "code": null, "e": 1226, "s": 1218, "text": "Output:" }, { "code": null, "e": 1229, "s": 1226, "text": "h2" }, { "code": null, "e": 1242, "s": 1229, "text": "Web-scraping" }, { "code": null, "e": 1249, "s": 1242, "text": "Python" } ]
Errors V/s Exceptions In Java
13 Jun, 2022 In java, both Errors and Exceptions are the subclasses of java.lang.Throwable class. Error refers to an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. It is of three types: Compile-time Run-time Logical Whereas exceptions in java refer to an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Now let us discuss various types of errors in order to get a better understanding over arrays. As discussed in the header an error indicates serious problems that a reasonable application should not try to catch. Errors are conditions that cannot get recovered by any handling techniques. It surely causes termination of the program abnormally. Errors belong to unchecked type and mostly occur at runtime. Some of the examples of errors are Out of memory errors or System crash errors. Example 1 Compile-time Error Java // Java Program to Illustrate Error// Stack overflow error via infinite recursion // Class 1class StackOverflow { // method of this class public static void test(int i) { // No correct as base condition leads to // non-stop recursion. if (i == 0) return; else { test(i++); } }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Testing for error by passing // custom integer as an argument StackOverflow.test(5); }} Output: Example 2 Java // Java Program to Illustrate Run-time Errors // Main classclass GFG { // Main driver method public static void main(String args[]) { // Declaring and initializing numbers int a = 2, b = 8, c = 6; if (a > b && a > c) System.out.println(a + " is the largest Number"); else if (b > a && b > c) System.out.println(b + " is the smallest Number"); // The correct message should have been // System.out.println // (b+" is the largest Number"); to make logic else System.out.println(c + " is the largest Number"); }} 8 is the smallest Number Now let us dwell onto Exceptions which indicates conditions that a reasonable application might want to catch. Exceptions are the conditions that occur at runtime and may cause the termination of the program. But they are recoverable using try, catch and throw keywords. Exceptions are divided into two categories: Checked exceptions Unchecked exceptions Checked exceptions like IOException known to the compiler at compile time while unchecked exceptions like ArrayIndexOutOfBoundException known to the compiler at runtime. It is mostly caused by the program written by the programmer. Example Exception Java // Java program illustrating exception thrown// by Arithmetic Exception class // Main classclass GFG { // main driver method public static void main(String[] args) { int a = 5, b = 0; // Try-catch block to check and handle exceptions try { // Attempting to divide by zero int c = a / b; } catch (ArithmeticException e) { // Displaying line number where exception occurred // using printStackTrace() method e.printStackTrace(); } }} Output: Finally now wrapping-off the article by plotting the differences out between them in a tabular format as provided below as follows: Errors can occur at compile time as well as run time. Compile Time: eg Syntax Error Run Time: Logical Error. clintra utkr98jais anikakapoor as5853535 nupurgupta3 nikhatkhan11 simmytarika5 Java-Exception Handling Java-Exceptions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Stack Class in Java Set in Java Introduction to Java Initialize an ArrayList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 494, "s": 52, "text": "In java, both Errors and Exceptions are the subclasses of java.lang.Throwable class. Error refers to an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. It is of three types:" }, { "code": null, "e": 507, "s": 494, "text": "Compile-time" }, { "code": null, "e": 516, "s": 507, "text": "Run-time" }, { "code": null, "e": 524, "s": 516, "text": "Logical" }, { "code": null, "e": 718, "s": 524, "text": "Whereas exceptions in java refer to an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions." }, { "code": null, "e": 1205, "s": 718, "text": "Now let us discuss various types of errors in order to get a better understanding over arrays. As discussed in the header an error indicates serious problems that a reasonable application should not try to catch. Errors are conditions that cannot get recovered by any handling techniques. It surely causes termination of the program abnormally. Errors belong to unchecked type and mostly occur at runtime. Some of the examples of errors are Out of memory errors or System crash errors. " }, { "code": null, "e": 1234, "s": 1205, "text": "Example 1 Compile-time Error" }, { "code": null, "e": 1239, "s": 1234, "text": "Java" }, { "code": "// Java Program to Illustrate Error// Stack overflow error via infinite recursion // Class 1class StackOverflow { // method of this class public static void test(int i) { // No correct as base condition leads to // non-stop recursion. if (i == 0) return; else { test(i++); } }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Testing for error by passing // custom integer as an argument StackOverflow.test(5); }}", "e": 1817, "s": 1239, "text": null }, { "code": null, "e": 1826, "s": 1817, "text": "Output: " }, { "code": null, "e": 1836, "s": 1826, "text": "Example 2" }, { "code": null, "e": 1841, "s": 1836, "text": "Java" }, { "code": "// Java Program to Illustrate Run-time Errors // Main classclass GFG { // Main driver method public static void main(String args[]) { // Declaring and initializing numbers int a = 2, b = 8, c = 6; if (a > b && a > c) System.out.println(a + \" is the largest Number\"); else if (b > a && b > c) System.out.println(b + \" is the smallest Number\"); // The correct message should have been // System.out.println // (b+\" is the largest Number\"); to make logic else System.out.println(c + \" is the largest Number\"); }}", "e": 2546, "s": 1841, "text": null }, { "code": null, "e": 2571, "s": 2546, "text": "8 is the smallest Number" }, { "code": null, "e": 2886, "s": 2571, "text": "Now let us dwell onto Exceptions which indicates conditions that a reasonable application might want to catch. Exceptions are the conditions that occur at runtime and may cause the termination of the program. But they are recoverable using try, catch and throw keywords. Exceptions are divided into two categories:" }, { "code": null, "e": 2905, "s": 2886, "text": "Checked exceptions" }, { "code": null, "e": 2926, "s": 2905, "text": "Unchecked exceptions" }, { "code": null, "e": 3158, "s": 2926, "text": "Checked exceptions like IOException known to the compiler at compile time while unchecked exceptions like ArrayIndexOutOfBoundException known to the compiler at runtime. It is mostly caused by the program written by the programmer." }, { "code": null, "e": 3176, "s": 3158, "text": "Example Exception" }, { "code": null, "e": 3181, "s": 3176, "text": "Java" }, { "code": "// Java program illustrating exception thrown// by Arithmetic Exception class // Main classclass GFG { // main driver method public static void main(String[] args) { int a = 5, b = 0; // Try-catch block to check and handle exceptions try { // Attempting to divide by zero int c = a / b; } catch (ArithmeticException e) { // Displaying line number where exception occurred // using printStackTrace() method e.printStackTrace(); } }}", "e": 3726, "s": 3181, "text": null }, { "code": null, "e": 3735, "s": 3726, "text": "Output: " }, { "code": null, "e": 3867, "s": 3735, "text": "Finally now wrapping-off the article by plotting the differences out between them in a tabular format as provided below as follows:" }, { "code": null, "e": 3951, "s": 3867, "text": "Errors can occur at compile time as well as run time. Compile Time: eg Syntax Error" }, { "code": null, "e": 3976, "s": 3951, "text": "Run Time: Logical Error." }, { "code": null, "e": 3984, "s": 3976, "text": "clintra" }, { "code": null, "e": 3995, "s": 3984, "text": "utkr98jais" }, { "code": null, "e": 4007, "s": 3995, "text": "anikakapoor" }, { "code": null, "e": 4017, "s": 4007, "text": "as5853535" }, { "code": null, "e": 4029, "s": 4017, "text": "nupurgupta3" }, { "code": null, "e": 4042, "s": 4029, "text": "nikhatkhan11" }, { "code": null, "e": 4055, "s": 4042, "text": "simmytarika5" }, { "code": null, "e": 4079, "s": 4055, "text": "Java-Exception Handling" }, { "code": null, "e": 4095, "s": 4079, "text": "Java-Exceptions" }, { "code": null, "e": 4100, "s": 4095, "text": "Java" }, { "code": null, "e": 4105, "s": 4100, "text": "Java" }, { "code": null, "e": 4203, "s": 4105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4222, "s": 4203, "text": "Interfaces in Java" }, { "code": null, "e": 4240, "s": 4222, "text": "ArrayList in Java" }, { "code": null, "e": 4255, "s": 4240, "text": "Stream In Java" }, { "code": null, "e": 4275, "s": 4255, "text": "Collections in Java" }, { "code": null, "e": 4299, "s": 4275, "text": "Singleton Class in Java" }, { "code": null, "e": 4331, "s": 4299, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4351, "s": 4331, "text": "Stack Class in Java" }, { "code": null, "e": 4363, "s": 4351, "text": "Set in Java" }, { "code": null, "e": 4384, "s": 4363, "text": "Introduction to Java" } ]
How to Calculate Correlation Between Multiple Variables in R?
19 Dec, 2021 In this article, we will discuss how to calculate Correlation between Multiple variables in R Programming Language. Correlation is used to get the relation between two or more variables: The result is 0 if there is no correlation between two variables The result is 1 if there is a positive correlation between two variables The result is -1 if there is a negative correlation between two variables Let’s create an initial dataframe: R # create the dataframe with 4 columnsdata=data.frame(col1=c(1:10),col2=c(11:20), col3=c(21:30),col4=c(1:10)) # displaydata Output: col1 col2 col3 col4 1 1 11 21 1 2 2 12 22 2 3 3 13 23 3 4 4 14 24 4 5 5 15 25 5 6 6 16 26 6 7 7 17 27 7 8 8 18 28 8 9 9 19 29 9 10 10 20 30 10 In this method to calculate the correlation between two variables, the user has to simply call the corr() function from the base R, passed with the required parameters which will be the name of the variables whose correlation is needed to be calculated and further this will be returning the correlation detail between the given two variables in the R programming language. Syntax: cor(dataframe$column1, dataframe$column1) where, dataframe is the input dataframe column1 is the column1 correlated with column2 Example: Here, in this example, we are going to create the dataframe with 4 columns with 10 rows and find the correlation between col1 and col2,correlation between col1 and col3,correlation between col1 and col4 and correlation between col3 and col4 using the cor() function in the R programming language. R # create the dataframe with 4 columnsdata=data.frame(col1=c(1:10),col2=c(11:20), col3=c(21:30),col4=c(1:10)) # correlation between col1 and col2print(cor(data$col1,data$col2)) # correlation between col1 and col3print(cor(data$col1,data$col3)) # correlation between col1 and col4print(cor(data$col1,data$col4)) # correlation between col3 and col4print(cor(data$col3,data$col4)) Output: 1 1 1 1 In this method, the user has to call the cor() function and then within this function the user has to pass the name of the multiple variables in the form of vector as its parameter to get the correlation among multiple variables by specifying multiple column names in the R programming language. Syntax: cor(dataframe[, c('column1','column2',.,'column n')]) Example: In this example, we will find the correlation between using cor() function of col1,col3, and col2,col1,col4 and col2, and col2,col3, and col4 in the R programming language. R # create the dataframe with 4 columnsdata=data.frame(col1=c(1:10),col2=c(11:20), col3=c(21:30), col4=c(1:5,34,56,32,23,45)) # correlation between col1,col3 and col2print(cor(data[, c('col1','col3','col2')])) # correlation between col1,col4 and col2print(cor(data[, c('col1','col4','col2')])) # correlation between col2,col3 and col4print(cor(data[, c('col2','col3','col4')])) Output: col1 col3 col2 col1 1 1 1 col3 1 1 1 col2 1 1 1 col1 col4 col2 col1 1.000000 0.787662 1.000000 col4 0.787662 1.000000 0.787662 col2 1.000000 0.787662 1.000000 col2 col3 col4 col2 1.000000 1.000000 0.787662 col3 1.000000 1.000000 0.787662 col4 0.787662 0.787662 1.000000 In this method to compute the correlation between all the variables in the given data frame, the user needs to call the cor() function with the entire data frame passed as its parameter to get the correlation between all variables of the given data frame in the R programming language. Syntax: cor(dataframe) Example: In this example, we are going to find the correlation between all the columns of the given data frame in the R programming language. R # create the dataframe with 4 columnsdata=data.frame(col1=c(1:10),col2=c(11:20), col3=c(21:30), col4=c(1:5,34,56,32,23,45)) # correlation in entire dataframeprint(cor(data)) Output: col1 col2 col3 col4 col1 1.000000 1.000000 1.000000 0.787662 col2 1.000000 1.000000 1.000000 0.787662 col3 1.000000 1.000000 1.000000 0.787662 col4 0.787662 0.787662 0.787662 1.0000 Picked 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": "\n19 Dec, 2021" }, { "code": null, "e": 215, "s": 28, "text": "In this article, we will discuss how to calculate Correlation between Multiple variables in R Programming Language. Correlation is used to get the relation between two or more variables:" }, { "code": null, "e": 280, "s": 215, "text": "The result is 0 if there is no correlation between two variables" }, { "code": null, "e": 353, "s": 280, "text": "The result is 1 if there is a positive correlation between two variables" }, { "code": null, "e": 428, "s": 353, "text": "The result is -1 if there is a negative correlation between two variables" }, { "code": null, "e": 463, "s": 428, "text": "Let’s create an initial dataframe:" }, { "code": null, "e": 465, "s": 463, "text": "R" }, { "code": "# create the dataframe with 4 columnsdata=data.frame(col1=c(1:10),col2=c(11:20), col3=c(21:30),col4=c(1:10)) # displaydata", "e": 604, "s": 465, "text": null }, { "code": null, "e": 612, "s": 604, "text": "Output:" }, { "code": null, "e": 865, "s": 612, "text": " col1 col2 col3 col4\n1 1 11 21 1\n2 2 12 22 2\n3 3 13 23 3\n4 4 14 24 4\n5 5 15 25 5\n6 6 16 26 6\n7 7 17 27 7\n8 8 18 28 8\n9 9 19 29 9\n10 10 20 30 10" }, { "code": null, "e": 1239, "s": 865, "text": "In this method to calculate the correlation between two variables, the user has to simply call the corr() function from the base R, passed with the required parameters which will be the name of the variables whose correlation is needed to be calculated and further this will be returning the correlation detail between the given two variables in the R programming language." }, { "code": null, "e": 1247, "s": 1239, "text": "Syntax:" }, { "code": null, "e": 1289, "s": 1247, "text": "cor(dataframe$column1, dataframe$column1)" }, { "code": null, "e": 1296, "s": 1289, "text": "where," }, { "code": null, "e": 1329, "s": 1296, "text": "dataframe is the input dataframe" }, { "code": null, "e": 1376, "s": 1329, "text": "column1 is the column1 correlated with column2" }, { "code": null, "e": 1385, "s": 1376, "text": "Example:" }, { "code": null, "e": 1682, "s": 1385, "text": "Here, in this example, we are going to create the dataframe with 4 columns with 10 rows and find the correlation between col1 and col2,correlation between col1 and col3,correlation between col1 and col4 and correlation between col3 and col4 using the cor() function in the R programming language." }, { "code": null, "e": 1684, "s": 1682, "text": "R" }, { "code": "# create the dataframe with 4 columnsdata=data.frame(col1=c(1:10),col2=c(11:20), col3=c(21:30),col4=c(1:10)) # correlation between col1 and col2print(cor(data$col1,data$col2)) # correlation between col1 and col3print(cor(data$col1,data$col3)) # correlation between col1 and col4print(cor(data$col1,data$col4)) # correlation between col3 and col4print(cor(data$col3,data$col4))", "e": 2080, "s": 1684, "text": null }, { "code": null, "e": 2088, "s": 2080, "text": "Output:" }, { "code": null, "e": 2096, "s": 2088, "text": "1\n1\n1\n1" }, { "code": null, "e": 2392, "s": 2096, "text": "In this method, the user has to call the cor() function and then within this function the user has to pass the name of the multiple variables in the form of vector as its parameter to get the correlation among multiple variables by specifying multiple column names in the R programming language." }, { "code": null, "e": 2400, "s": 2392, "text": "Syntax:" }, { "code": null, "e": 2454, "s": 2400, "text": "cor(dataframe[, c('column1','column2',.,'column n')])" }, { "code": null, "e": 2463, "s": 2454, "text": "Example:" }, { "code": null, "e": 2637, "s": 2463, "text": "In this example, we will find the correlation between using cor() function of col1,col3, and col2,col1,col4 and col2, and col2,col3, and col4 in the R programming language. " }, { "code": null, "e": 2639, "s": 2637, "text": "R" }, { "code": "# create the dataframe with 4 columnsdata=data.frame(col1=c(1:10),col2=c(11:20), col3=c(21:30), col4=c(1:5,34,56,32,23,45)) # correlation between col1,col3 and col2print(cor(data[, c('col1','col3','col2')])) # correlation between col1,col4 and col2print(cor(data[, c('col1','col4','col2')])) # correlation between col2,col3 and col4print(cor(data[, c('col2','col3','col4')]))", "e": 3048, "s": 2639, "text": null }, { "code": null, "e": 3056, "s": 3048, "text": "Output:" }, { "code": null, "e": 3394, "s": 3056, "text": " col1 col3 col2\ncol1 1 1 1\ncol3 1 1 1\ncol2 1 1 1\n\n col1 col4 col2\ncol1 1.000000 0.787662 1.000000\ncol4 0.787662 1.000000 0.787662\ncol2 1.000000 0.787662 1.000000\n\n col2 col3 col4\ncol2 1.000000 1.000000 0.787662\ncol3 1.000000 1.000000 0.787662\ncol4 0.787662 0.787662 1.000000" }, { "code": null, "e": 3680, "s": 3394, "text": "In this method to compute the correlation between all the variables in the given data frame, the user needs to call the cor() function with the entire data frame passed as its parameter to get the correlation between all variables of the given data frame in the R programming language." }, { "code": null, "e": 3688, "s": 3680, "text": "Syntax:" }, { "code": null, "e": 3703, "s": 3688, "text": "cor(dataframe)" }, { "code": null, "e": 3712, "s": 3703, "text": "Example:" }, { "code": null, "e": 3845, "s": 3712, "text": "In this example, we are going to find the correlation between all the columns of the given data frame in the R programming language." }, { "code": null, "e": 3847, "s": 3845, "text": "R" }, { "code": "# create the dataframe with 4 columnsdata=data.frame(col1=c(1:10),col2=c(11:20), col3=c(21:30), col4=c(1:5,34,56,32,23,45)) # correlation in entire dataframeprint(cor(data))", "e": 4052, "s": 3847, "text": null }, { "code": null, "e": 4060, "s": 4052, "text": "Output:" }, { "code": null, "e": 4263, "s": 4060, "text": " col1 col2 col3 col4\ncol1 1.000000 1.000000 1.000000 0.787662\ncol2 1.000000 1.000000 1.000000 0.787662\ncol3 1.000000 1.000000 1.000000 0.787662\ncol4 0.787662 0.787662 0.787662 1.0000" }, { "code": null, "e": 4270, "s": 4263, "text": "Picked" }, { "code": null, "e": 4283, "s": 4270, "text": "R-Statistics" }, { "code": null, "e": 4294, "s": 4283, "text": "R Language" } ]
GATE | GATE-CS-2016 (Set 1) | Question 10
28 Jun, 2021 In a process, the number of cycles to failure decreases exponentially with an increase in load. At a load of 80 units, it takes 100 cycles for failure. When the load is halved, it takes 10000 cycles for failure. The load for which the failure will happen in 5000 cycles is ________. (A) 40.00 (B) 46.02(C) 60.01(D) 92.02Answer: (B)Explanation: For exponential dependence we must have functions of form f(x) = a.(k power x) : a,k are constants and f(0)=a Let us assume: C = cycles for failure ; L = Load; a, k = constants according to question C is an exponential function of L Hence we can say, 1) C = a x (k^L) ---- > in case C is increasing exponentially 2) C = a / (k^L) ---- > in case C is decreasing exponentially we take 2nd equation and apply log to both side we get: log C + L x (log k) = log a ...... by logarithmic property given (C=100 for L=80) and (C=10000 for L=40) apply these to values to above equation, this gives us 2 equations and 2 variables: log a = log 100 + (80 x log k)...............(1) log a = log 10000 + (40 x log k)...........(2) we have 2 variables and 2 equations hence we find log a = 6 log k= 1/20 now find, [ L = (log a - log C) / (log k) ] for C=5000 cycles => L = (6 - log 5000)*20 = 46.0206 ~ 46.02 => [ANS] Quiz of this Question GATE-CS-2016 (Set 1) GATE-GATE-CS-2016 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2008 | Question 40 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE CS 1996 | Question 63 GATE | GATE-CS-2004 | Question 31 GATE | GATE CS 2011 | Question 49
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 337, "s": 54, "text": "In a process, the number of cycles to failure decreases exponentially with an increase in load. At a load of 80 units, it takes 100 cycles for failure. When the load is halved, it takes 10000 cycles for failure. The load for which the failure will happen in 5000 cycles is ________." }, { "code": null, "e": 347, "s": 337, "text": "(A) 40.00" }, { "code": null, "e": 398, "s": 347, "text": "(B) 46.02(C) 60.01(D) 92.02Answer: (B)Explanation:" }, { "code": null, "e": 1310, "s": 398, "text": "For exponential dependence we must have functions of form\nf(x) = a.(k power x) : a,k are constants and f(0)=a\n\nLet us assume: C = cycles for failure ; L = Load; a, k = constants\naccording to question C is an exponential function of L\nHence we can say,\n\n1) C = a x (k^L) ---- > in case C is increasing exponentially\n2) C = a / (k^L) ---- > in case C is decreasing exponentially\n\nwe take 2nd equation and apply log to both side we get:\n\nlog C + L x (log k) = log a ...... by logarithmic property\n\ngiven (C=100 for L=80) and (C=10000 for L=40)\napply these to values to above equation, this gives us 2 equations\nand 2 variables:\n\nlog a = log 100 + (80 x log k)...............(1)\nlog a = log 10000 + (40 x log k)...........(2)\n\nwe have 2 variables and 2 equations hence we find\nlog a = 6\nlog k= 1/20\n\nnow find, [ L = (log a - log C) / (log k) ] for C=5000 cycles\n\n=> L = (6 - log 5000)*20 = 46.0206 ~ 46.02 => [ANS]\n" }, { "code": null, "e": 1332, "s": 1310, "text": "Quiz of this Question" }, { "code": null, "e": 1353, "s": 1332, "text": "GATE-CS-2016 (Set 1)" }, { "code": null, "e": 1379, "s": 1353, "text": "GATE-GATE-CS-2016 (Set 1)" }, { "code": null, "e": 1384, "s": 1379, "text": "GATE" }, { "code": null, "e": 1482, "s": 1384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1524, "s": 1482, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1586, "s": 1524, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1620, "s": 1586, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1662, "s": 1620, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1696, "s": 1662, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 1738, "s": 1696, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1780, "s": 1738, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 1814, "s": 1780, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 1848, "s": 1814, "text": "GATE | GATE-CS-2004 | Question 31" } ]
Split a String into columns using regex in pandas DataFrame
08 Jan, 2019 Given some mixed data containing multiple values as a string, let’s see how can we divide the strings using regex and make multiple columns in Pandas DataFrame. Method #1:In this method we will use re.search(pattern, string, flags=0). Here pattern refers to the pattern that we want to search. It takes in a string with the following values: \w matches alphanumeric characters \d matches digits, which means 0-9 \s matches whitespace characters \S matches non-whitespace characters . matches any character except the new line character \n * matches 0 or more instances of a pattern # import the regex libraryimport pandas as pdimport re # Create a list with all the stringsmovie_data = ["Name: The_Godfather Year: 1972 Rating: 9.2", "Name: Bird_Box Year: 2018 Rating: 6.8", "Name: Fight_Club Year: 1999 Rating: 8.8"] # Create a dictionary with the required columns # Used later to convert to DataFramemovies = {"Name":[], "Year":[], "Rating":[]} for item in movie_data: # For Name field name_field = re.search("Name: .*",item) if name_field is not None: name = re.search('\w*\s\w*',name_field.group()) else: name = None movies["Name"].append(name.group()) # For Year field year_field = re.search("Year: .*",item) if year_field is not None: year = re.search('\s\d\d\d\d',year_field.group()) else: year = None movies["Year"].append(year.group().strip()) # For rating field rating_field = re.search("Rating: .*",item) if rating_field is not None: rating = re.search('\s\d.\d',rating_field.group()) else: rating - None movies["Rating"].append(rating.group().strip()) # Creating DataFramedf = pd.DataFrame(movies)print(df) Output: Explanation: In the code above, we use a for loop to iterate through movie data so we can work with each movie in turn. We create a dictionary, movies, that will hold all the details of each detail, such as the rating and name. We then find the entire Name field using the re.search() function. The . means any character except \n, and * extends it to the end of the line. Assign this to the variable name_field. But, data isn’t always straightforward. It can contain surprises. For instance, what if there’s no Name: field? The script would throw an error and break. We pre-empt errors from this scenario and check for a not None case. Again we use the re.search() function to extract the final required string from the name_field. For the name we use \w* to represent the first word, \s to represent the space in between and \w* for the second word. Do the same for year and rating and get the final required dictionary. Method #2:To break up the string we will use Series.str.extract(pat, flags=0, expand=True) function. Here pat refers to the pattern that we want to search for. import pandas as pd dict = {'movie_data':['The Godfather 1972 9.2', 'Bird Box 2018 6.8', 'Fight Club 1999 8.8'] } # Convert the dictionary to a dataframedf = pd.DataFrame(dict) # Extract name from the string df['Name'] = df['movie_data'].str.extract('(\w*\s\w*)', expand=True) # Extract year from the string df['Year'] = df['movie_data'].str.extract('(\d\d\d\d)', expand=True) # Extract rating from the string df['Rating'] = df['movie_data'].str.extract('(\d\.\d)', expand=True)print(df) Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jan, 2019" }, { "code": null, "e": 215, "s": 54, "text": "Given some mixed data containing multiple values as a string, let’s see how can we divide the strings using regex and make multiple columns in Pandas DataFrame." }, { "code": null, "e": 396, "s": 215, "text": "Method #1:In this method we will use re.search(pattern, string, flags=0). Here pattern refers to the pattern that we want to search. It takes in a string with the following values:" }, { "code": null, "e": 431, "s": 396, "text": "\\w matches alphanumeric characters" }, { "code": null, "e": 466, "s": 431, "text": "\\d matches digits, which means 0-9" }, { "code": null, "e": 499, "s": 466, "text": "\\s matches whitespace characters" }, { "code": null, "e": 536, "s": 499, "text": "\\S matches non-whitespace characters" }, { "code": null, "e": 593, "s": 536, "text": ". matches any character except the new line character \\n" }, { "code": null, "e": 636, "s": 593, "text": "* matches 0 or more instances of a pattern" }, { "code": "# import the regex libraryimport pandas as pdimport re # Create a list with all the stringsmovie_data = [\"Name: The_Godfather Year: 1972 Rating: 9.2\", \"Name: Bird_Box Year: 2018 Rating: 6.8\", \"Name: Fight_Club Year: 1999 Rating: 8.8\"] # Create a dictionary with the required columns # Used later to convert to DataFramemovies = {\"Name\":[], \"Year\":[], \"Rating\":[]} for item in movie_data: # For Name field name_field = re.search(\"Name: .*\",item) if name_field is not None: name = re.search('\\w*\\s\\w*',name_field.group()) else: name = None movies[\"Name\"].append(name.group()) # For Year field year_field = re.search(\"Year: .*\",item) if year_field is not None: year = re.search('\\s\\d\\d\\d\\d',year_field.group()) else: year = None movies[\"Year\"].append(year.group().strip()) # For rating field rating_field = re.search(\"Rating: .*\",item) if rating_field is not None: rating = re.search('\\s\\d.\\d',rating_field.group()) else: rating - None movies[\"Rating\"].append(rating.group().strip()) # Creating DataFramedf = pd.DataFrame(movies)print(df)", "e": 1811, "s": 636, "text": null }, { "code": null, "e": 1819, "s": 1811, "text": "Output:" }, { "code": null, "e": 1832, "s": 1819, "text": "Explanation:" }, { "code": null, "e": 2047, "s": 1832, "text": "In the code above, we use a for loop to iterate through movie data so we can work with each movie in turn. We create a dictionary, movies, that will hold all the details of each detail, such as the rating and name." }, { "code": null, "e": 2232, "s": 2047, "text": "We then find the entire Name field using the re.search() function. The . means any character except \\n, and * extends it to the end of the line. Assign this to the variable name_field." }, { "code": null, "e": 2456, "s": 2232, "text": "But, data isn’t always straightforward. It can contain surprises. For instance, what if there’s no Name: field? The script would throw an error and break. We pre-empt errors from this scenario and check for a not None case." }, { "code": null, "e": 2671, "s": 2456, "text": "Again we use the re.search() function to extract the final required string from the name_field. For the name we use \\w* to represent the first word, \\s to represent the space in between and \\w* for the second word." }, { "code": null, "e": 2742, "s": 2671, "text": "Do the same for year and rating and get the final required dictionary." }, { "code": null, "e": 2903, "s": 2742, "text": " Method #2:To break up the string we will use Series.str.extract(pat, flags=0, expand=True) function. Here pat refers to the pattern that we want to search for." }, { "code": "import pandas as pd dict = {'movie_data':['The Godfather 1972 9.2', 'Bird Box 2018 6.8', 'Fight Club 1999 8.8'] } # Convert the dictionary to a dataframedf = pd.DataFrame(dict) # Extract name from the string df['Name'] = df['movie_data'].str.extract('(\\w*\\s\\w*)', expand=True) # Extract year from the string df['Year'] = df['movie_data'].str.extract('(\\d\\d\\d\\d)', expand=True) # Extract rating from the string df['Rating'] = df['movie_data'].str.extract('(\\d\\.\\d)', expand=True)print(df)", "e": 3435, "s": 2903, "text": null }, { "code": null, "e": 3443, "s": 3435, "text": "Output:" }, { "code": null, "e": 3468, "s": 3443, "text": "pandas-dataframe-program" }, { "code": null, "e": 3475, "s": 3468, "text": "Picked" }, { "code": null, "e": 3499, "s": 3475, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3513, "s": 3499, "text": "Python-pandas" }, { "code": null, "e": 3537, "s": 3513, "text": "Technical Scripter 2018" }, { "code": null, "e": 3544, "s": 3537, "text": "Python" }, { "code": null, "e": 3563, "s": 3544, "text": "Technical Scripter" } ]
How to Implement Swipe Down to Refresh in Android
17 Feb, 2021 Certain applications show real-time data to the users, such as stock prices, availability of a product on online stores, etc. Showing real-time data requires continuous syncing of the application, and could be possible by implementing a program such as a thread. A Thread could be initiated by the application and update the real-time information implicitly or explicitly. The deal here is continuously updating the data (maybe from the servers) at the cost of additional RAM, Cache, and Battery of the device resulting in low-performance, as a Thread that runs forever occupies some space and requires power. To avoid using such programs, developers explicitly developed a feature for refreshing the application, so that the user can perform it whenever necessary. This brings us to conclude that manual refreshing has advantages such as: RAM OptimizationCache Memory OptimizationBattery Life OptimizationAvoiding Unnecessary Callbacks. RAM Optimization Cache Memory Optimization Battery Life Optimization Avoiding Unnecessary Callbacks. For example in the following image when the user will swipe down the screen then the string “Swipe to refresh” will be changed to “Refreshed”. Step 1: Before start writing the code it is essential to add a Swipe Refresh Layout dependency into the build.Gradle of the application to enable swipe layouts. This dependency is: implementation “androidx.swiperefreshlayout:swiperefreshlayout:1.1.0” Step 2: It is important to start with the Front-End “activity_main.xml“. Create a SwipeRefreshLayout to refresh the Layout and add a TextView to display the string on the screen and provide them with certain IDs. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Swipe Refresh Layout --> <androidx.swiperefreshlayout.widget.SwipeRefreshLayout android:id="@+id/refreshLayout" android:layout_width="match_parent" android:layout_height="match_parent"> <!--TextView --> <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Swipe to refresh" /> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout> </RelativeLayout> Step 3: Coming to the “MainActivity” file, a preview of the same is provided below. In this file connect the swipeRefreshLayout and textView to its XML file by using the findViewById() method. And also call the setOnRefreshListener() to change the text after the user swipe down the screen. The users can also write the required codes as their needs inside this method. Kotlin Java import android.annotation.SuppressLintimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport androidx.swiperefreshlayout.widget.SwipeRefreshLayoutimport org.w3c.dom.Text class MainActivity : AppCompatActivity() { @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring a layout (changes are to be made to this) // Declaring a textview (which is inside the layout) val swipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.refreshLayout) val textView = findViewById<TextView>(R.id.tv1) // Refresh function for the layout swipeRefreshLayout.setOnRefreshListener{ // Your code goes here // In this code, we are just changing the text in the // textbox textView.text = "Refreshed" // This line is important as it explicitly refreshes only once // If "true" it implicitly refreshes forever swipeRefreshLayout.isRefreshing = false } }} import android.annotation.SuppressLintimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport androidx.swiperefreshlayout.widget.SwipeRefreshLayoutimport org.w3c.dom.Text public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Declaring a layout (changes are to be made to this) // Declaring a textview (which is inside the layout) SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.refreshLayout); TextView textView = (TextView)findViewById(R.id.tv1); // Refresh the layout swipeRefreshLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Your code goes here // In this code, we are just // changing the text in the textbox textView.text = "Refreshed" // This line is important as it explicitly // refreshes only once // If "true" it implicitly refreshes forever swipeRefreshLayout.setRefreshing(false); } } ); }} Of course, it’s not just the users who benefit. Assuming an application, where the information is fetched directly from a cloud repository. For every callback request (towards the cloud), the developer who owns such a repository pays a minimal amount towards the service, may it be Google Cloud Platform (GCP), Amazon Web Services (AWS), or any other thing. onlyklohan android Java Kotlin Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Feb, 2021" }, { "code": null, "e": 892, "s": 52, "text": "Certain applications show real-time data to the users, such as stock prices, availability of a product on online stores, etc. Showing real-time data requires continuous syncing of the application, and could be possible by implementing a program such as a thread. A Thread could be initiated by the application and update the real-time information implicitly or explicitly. The deal here is continuously updating the data (maybe from the servers) at the cost of additional RAM, Cache, and Battery of the device resulting in low-performance, as a Thread that runs forever occupies some space and requires power. To avoid using such programs, developers explicitly developed a feature for refreshing the application, so that the user can perform it whenever necessary. This brings us to conclude that manual refreshing has advantages such as:" }, { "code": null, "e": 990, "s": 892, "text": "RAM OptimizationCache Memory OptimizationBattery Life OptimizationAvoiding Unnecessary Callbacks." }, { "code": null, "e": 1007, "s": 990, "text": "RAM Optimization" }, { "code": null, "e": 1033, "s": 1007, "text": "Cache Memory Optimization" }, { "code": null, "e": 1059, "s": 1033, "text": "Battery Life Optimization" }, { "code": null, "e": 1091, "s": 1059, "text": "Avoiding Unnecessary Callbacks." }, { "code": null, "e": 1234, "s": 1091, "text": "For example in the following image when the user will swipe down the screen then the string “Swipe to refresh” will be changed to “Refreshed”." }, { "code": null, "e": 1415, "s": 1234, "text": "Step 1: Before start writing the code it is essential to add a Swipe Refresh Layout dependency into the build.Gradle of the application to enable swipe layouts. This dependency is:" }, { "code": null, "e": 1485, "s": 1415, "text": "implementation “androidx.swiperefreshlayout:swiperefreshlayout:1.1.0”" }, { "code": null, "e": 1699, "s": 1485, "text": "Step 2: It is important to start with the Front-End “activity_main.xml“. Create a SwipeRefreshLayout to refresh the Layout and add a TextView to display the string on the screen and provide them with certain IDs. " }, { "code": null, "e": 1703, "s": 1699, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Swipe Refresh Layout --> <androidx.swiperefreshlayout.widget.SwipeRefreshLayout android:id=\"@+id/refreshLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--TextView --> <TextView android:id=\"@+id/tv1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Swipe to refresh\" /> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout> </RelativeLayout>", "e": 2528, "s": 1703, "text": null }, { "code": null, "e": 2900, "s": 2528, "text": " Step 3: Coming to the “MainActivity” file, a preview of the same is provided below. In this file connect the swipeRefreshLayout and textView to its XML file by using the findViewById() method. And also call the setOnRefreshListener() to change the text after the user swipe down the screen. The users can also write the required codes as their needs inside this method. " }, { "code": null, "e": 2907, "s": 2900, "text": "Kotlin" }, { "code": null, "e": 2912, "s": 2907, "text": "Java" }, { "code": "import android.annotation.SuppressLintimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport androidx.swiperefreshlayout.widget.SwipeRefreshLayoutimport org.w3c.dom.Text class MainActivity : AppCompatActivity() { @SuppressLint(\"SetTextI18n\") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring a layout (changes are to be made to this) // Declaring a textview (which is inside the layout) val swipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.refreshLayout) val textView = findViewById<TextView>(R.id.tv1) // Refresh function for the layout swipeRefreshLayout.setOnRefreshListener{ // Your code goes here // In this code, we are just changing the text in the // textbox textView.text = \"Refreshed\" // This line is important as it explicitly refreshes only once // If \"true\" it implicitly refreshes forever swipeRefreshLayout.isRefreshing = false } }}", "e": 4037, "s": 2912, "text": null }, { "code": "import android.annotation.SuppressLintimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport androidx.swiperefreshlayout.widget.SwipeRefreshLayoutimport org.w3c.dom.Text public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Declaring a layout (changes are to be made to this) // Declaring a textview (which is inside the layout) SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.refreshLayout); TextView textView = (TextView)findViewById(R.id.tv1); // Refresh the layout swipeRefreshLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Your code goes here // In this code, we are just // changing the text in the textbox textView.text = \"Refreshed\" // This line is important as it explicitly // refreshes only once // If \"true\" it implicitly refreshes forever swipeRefreshLayout.setRefreshing(false); } } ); }}", "e": 5301, "s": 4037, "text": null }, { "code": null, "e": 5660, "s": 5301, "text": "Of course, it’s not just the users who benefit. Assuming an application, where the information is fetched directly from a cloud repository. For every callback request (towards the cloud), the developer who owns such a repository pays a minimal amount towards the service, may it be Google Cloud Platform (GCP), Amazon Web Services (AWS), or any other thing. " }, { "code": null, "e": 5671, "s": 5660, "text": "onlyklohan" }, { "code": null, "e": 5679, "s": 5671, "text": "android" }, { "code": null, "e": 5684, "s": 5679, "text": "Java" }, { "code": null, "e": 5691, "s": 5684, "text": "Kotlin" }, { "code": null, "e": 5696, "s": 5691, "text": "Java" } ]
p5.js | ellipse() Function
24 Oct, 2018 The ellipse() function is an inbuilt function in p5.js which is used to draw an ellipse. Syntax: ellipse(x, y, w, h) ellipse(x, y, w, h, detail) Parameters: This function accepts five parameters as mentioned above and described below: x: This parameter takes the x-coordinate of the ellipse. y: This parameter takes the y-coordinate of the ellipse. w: This parameter takes the width of the ellipse. h: This parameter takes the height of the ellipse. detail: It is the optional parameter which takes the number of radial sectors to draw as integer. Below program illustrates the ellipse() function in P5.js: function setup() { createCanvas(400, 400);} function draw() { background(220); fill('yellow'); // An ellipse at 150, 150 with radius 280 ellipse(150, 150, 280, 180) } Output: Reference: https://p5js.org/reference/#/p5/ellipse JavaScript-p5.js Technical Scripter 2018 JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request 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": "\n24 Oct, 2018" }, { "code": null, "e": 143, "s": 54, "text": "The ellipse() function is an inbuilt function in p5.js which is used to draw an ellipse." }, { "code": null, "e": 151, "s": 143, "text": "Syntax:" }, { "code": null, "e": 200, "s": 151, "text": "ellipse(x, y, w, h)\nellipse(x, y, w, h, detail)\n" }, { "code": null, "e": 290, "s": 200, "text": "Parameters: This function accepts five parameters as mentioned above and described below:" }, { "code": null, "e": 347, "s": 290, "text": "x: This parameter takes the x-coordinate of the ellipse." }, { "code": null, "e": 404, "s": 347, "text": "y: This parameter takes the y-coordinate of the ellipse." }, { "code": null, "e": 454, "s": 404, "text": "w: This parameter takes the width of the ellipse." }, { "code": null, "e": 505, "s": 454, "text": "h: This parameter takes the height of the ellipse." }, { "code": null, "e": 603, "s": 505, "text": "detail: It is the optional parameter which takes the number of radial sectors to draw as integer." }, { "code": null, "e": 662, "s": 603, "text": "Below program illustrates the ellipse() function in P5.js:" }, { "code": "function setup() { createCanvas(400, 400);} function draw() { background(220); fill('yellow'); // An ellipse at 150, 150 with radius 280 ellipse(150, 150, 280, 180) } ", "e": 852, "s": 662, "text": null }, { "code": null, "e": 860, "s": 852, "text": "Output:" }, { "code": null, "e": 911, "s": 860, "text": "Reference: https://p5js.org/reference/#/p5/ellipse" }, { "code": null, "e": 928, "s": 911, "text": "JavaScript-p5.js" }, { "code": null, "e": 952, "s": 928, "text": "Technical Scripter 2018" }, { "code": null, "e": 963, "s": 952, "text": "JavaScript" }, { "code": null, "e": 982, "s": 963, "text": "Technical Scripter" }, { "code": null, "e": 999, "s": 982, "text": "Web Technologies" }, { "code": null, "e": 1097, "s": 999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1158, "s": 1097, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1230, "s": 1158, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1270, "s": 1230, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1323, "s": 1270, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1364, "s": 1323, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1397, "s": 1364, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1459, "s": 1397, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1520, "s": 1459, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1570, "s": 1520, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to set the Name of the Button in C#?
26 Jun, 2019 A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In Button, you are allowed to set the name of your button by using Name property. You can use this property in two different methods: 1. Design-Time: It is the easiest method to set the name of the button using the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the Button control to set the Name property of the Button.Output: Output: Run-Time: It is a little bit trickier than the above method. In this method, you can set the Name property of the Button programmatically with the help of given syntax: public string Name { get; set; } Here, the string is used to represent the name of the button. Following steps are used to set the Name property of the Button: Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class Button MyButton = new Button(); // Creating Button using Button class Button MyButton = new Button(); Step 2: After creating Button, set the Name property of the Button provided by the Button class.// Set the name of the button Mybutton.Name = "First_button"; // Set the name of the button Mybutton.Name = "First_button"; Step 3: And last add this button control to form using Add() method.// Add this Button to form this.Controls.Add(Mybutton); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Name = "First_button"; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Name = "Second_button"; // Adding this button to form this.Controls.Add(Mybutton1); }}}Output: // Add this Button to form this.Controls.Add(Mybutton); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this form?"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Name = "First_button"; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Name = "Second_button"; // Adding this button to form this.Controls.Add(Mybutton1); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Partial Classes in C# Lambda Expressions in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jun, 2019" }, { "code": null, "e": 301, "s": 28, "text": "A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In Button, you are allowed to set the name of your button by using Name property. You can use this property in two different methods:" }, { "code": null, "e": 399, "s": 301, "text": "1. Design-Time: It is the easiest method to set the name of the button using the following steps:" }, { "code": null, "e": 515, "s": 399, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 692, "s": 515, "text": "Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need." }, { "code": null, "e": 819, "s": 692, "text": "Step 3: After drag and drop you will go to the properties of the Button control to set the Name property of the Button.Output:" }, { "code": null, "e": 827, "s": 819, "text": "Output:" }, { "code": null, "e": 996, "s": 827, "text": "Run-Time: It is a little bit trickier than the above method. In this method, you can set the Name property of the Button programmatically with the help of given syntax:" }, { "code": null, "e": 1029, "s": 996, "text": "public string Name { get; set; }" }, { "code": null, "e": 1156, "s": 1029, "text": "Here, the string is used to represent the name of the button. Following steps are used to set the Name property of the Button:" }, { "code": null, "e": 1314, "s": 1156, "text": "Step 1: Create a button using the Button() constructor is provided by the Button class.// Creating Button using Button class\nButton MyButton = new Button();\n" }, { "code": null, "e": 1385, "s": 1314, "text": "// Creating Button using Button class\nButton MyButton = new Button();\n" }, { "code": null, "e": 1544, "s": 1385, "text": "Step 2: After creating Button, set the Name property of the Button provided by the Button class.// Set the name of the button\nMybutton.Name = \"First_button\";\n" }, { "code": null, "e": 1607, "s": 1544, "text": "// Set the name of the button\nMybutton.Name = \"First_button\";\n" }, { "code": null, "e": 3254, "s": 1607, "text": "Step 3: And last add this button control to form using Add() method.// Add this Button to form\nthis.Controls.Add(Mybutton);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Name = \"First_button\"; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Name = \"Second_button\"; // Adding this button to form this.Controls.Add(Mybutton1); }}}Output:" }, { "code": null, "e": 3311, "s": 3254, "text": "// Add this Button to form\nthis.Controls.Add(Mybutton);\n" }, { "code": null, "e": 3320, "s": 3311, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = \"Do you want to submit this form?\"; l.Location = new Point(222, 145); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = \"Submit\"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Name = \"First_button\"; // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(438, 198); Mybutton1.Text = \"Cancel\"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Name = \"Second_button\"; // Adding this button to form this.Controls.Add(Mybutton1); }}}", "e": 4828, "s": 3320, "text": null }, { "code": null, "e": 4836, "s": 4828, "text": "Output:" }, { "code": null, "e": 4839, "s": 4836, "text": "C#" }, { "code": null, "e": 4937, "s": 4839, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4980, "s": 4937, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 5029, "s": 4980, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 5052, "s": 5029, "text": "Extension Method in C#" }, { "code": null, "e": 5068, "s": 5052, "text": "C# | List Class" }, { "code": null, "e": 5096, "s": 5068, "text": "HashSet in C# with Examples" }, { "code": null, "e": 5157, "s": 5096, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 5180, "s": 5157, "text": "Switch Statement in C#" }, { "code": null, "e": 5202, "s": 5180, "text": "Partial Classes in C#" }, { "code": null, "e": 5227, "s": 5202, "text": "Lambda Expressions in C#" } ]
io.Copy() Function in Golang with Examples
05 May, 2020 In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The Copy() function in Go language is used to copy from the stated src i.e, source to the dst i.e, destination till either the EOF i.e, end of file is attained on src or an error is thrown. Here, when src is implemented by WriterTo interface then the copy is implemented by a call to src.WriteTo(dst). else, if dst is implemented by the ReaderFrom interface then the copy is implemented by a call to dst.ReadFrom(src). Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions. Syntax: func Copy(dst Writer, src Reader) (written int64, err error) Here, “dst” is the destination and “src” is the source from where the content is copied to the destination.Return value: It returns the total number of bytes of type int64 that are copied to the “dst” and also returns the first error that is faced while copying from src to dst, if any. And if there is no error in copying then “nil” is returned. Below examples illustrates the use of above method: Example 1: // Golang program to illustrate the usage of// io.Copy() function // Including main packagepackage main // Importing fmt, io, os, and stringsimport ( "fmt" "io" "os" "strings") // Calling mainfunc main() { // Defining source src := strings.NewReader("GeeksforGeeks\n") // Defining destination using Stdout dst := os.Stdout // Calling Copy method with its parameters bytes, err := io.Copy(dst, src) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("The number of bytes are: %d\n", bytes)} Output: GeeksforGeeks The number of bytes are: 14 Example 2: // Golang program to illustrate the usage of// io.Copy() function // Including main packagepackage main // Importing fmt, io, os, and stringsimport ( "fmt" "io" "os" "strings") // Calling mainfunc main() { // Defining source src := strings.NewReader("Nidhi: F\nRahul: M\nNisha: F\n") // Defining destination using Stdout dst := os.Stdout // Calling Copy method with its parameters bytes, err := io.Copy(dst, src) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("The number of bytes are: %d\n", bytes)} Output: Nidhi: F Rahul: M Nisha: F The number of bytes are: 27 Here, in the above example NewReader() method of strings is used from where the content to be copied is read. And “Stdout” is used here in order to create a default file descriptor where the copied content is written. Golang-io Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Golang Maps Arrays in Go fmt.Sprintf() Function in Golang With Examples How to copy one slice into another slice in Golang? Time Durations in Golang How to convert a string in lower case in Golang? Interfaces in Golang Inheritance in GoLang Check if the String starts with specified prefix in Golang strings.Replace() Function in Golang With Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n05 May, 2020" }, { "code": null, "e": 752, "s": 28, "text": "In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The Copy() function in Go language is used to copy from the stated src i.e, source to the dst i.e, destination till either the EOF i.e, end of file is attained on src or an error is thrown. Here, when src is implemented by WriterTo interface then the copy is implemented by a call to src.WriteTo(dst). else, if dst is implemented by the ReaderFrom interface then the copy is implemented by a call to dst.ReadFrom(src). Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions." }, { "code": null, "e": 760, "s": 752, "text": "Syntax:" }, { "code": null, "e": 822, "s": 760, "text": "func Copy(dst Writer, src Reader) (written int64, err error)\n" }, { "code": null, "e": 1169, "s": 822, "text": "Here, “dst” is the destination and “src” is the source from where the content is copied to the destination.Return value: It returns the total number of bytes of type int64 that are copied to the “dst” and also returns the first error that is faced while copying from src to dst, if any. And if there is no error in copying then “nil” is returned." }, { "code": null, "e": 1221, "s": 1169, "text": "Below examples illustrates the use of above method:" }, { "code": null, "e": 1232, "s": 1221, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// io.Copy() function // Including main packagepackage main // Importing fmt, io, os, and stringsimport ( \"fmt\" \"io\" \"os\" \"strings\") // Calling mainfunc main() { // Defining source src := strings.NewReader(\"GeeksforGeeks\\n\") // Defining destination using Stdout dst := os.Stdout // Calling Copy method with its parameters bytes, err := io.Copy(dst, src) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"The number of bytes are: %d\\n\", bytes)}", "e": 1828, "s": 1232, "text": null }, { "code": null, "e": 1836, "s": 1828, "text": "Output:" }, { "code": null, "e": 1879, "s": 1836, "text": "GeeksforGeeks\nThe number of bytes are: 14\n" }, { "code": null, "e": 1890, "s": 1879, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// io.Copy() function // Including main packagepackage main // Importing fmt, io, os, and stringsimport ( \"fmt\" \"io\" \"os\" \"strings\") // Calling mainfunc main() { // Defining source src := strings.NewReader(\"Nidhi: F\\nRahul: M\\nNisha: F\\n\") // Defining destination using Stdout dst := os.Stdout // Calling Copy method with its parameters bytes, err := io.Copy(dst, src) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"The number of bytes are: %d\\n\", bytes)}", "e": 2501, "s": 1890, "text": null }, { "code": null, "e": 2509, "s": 2501, "text": "Output:" }, { "code": null, "e": 2565, "s": 2509, "text": "Nidhi: F\nRahul: M\nNisha: F\nThe number of bytes are: 27\n" }, { "code": null, "e": 2783, "s": 2565, "text": "Here, in the above example NewReader() method of strings is used from where the content to be copied is read. And “Stdout” is used here in order to create a default file descriptor where the copied content is written." }, { "code": null, "e": 2793, "s": 2783, "text": "Golang-io" }, { "code": null, "e": 2805, "s": 2793, "text": "Go Language" }, { "code": null, "e": 2903, "s": 2805, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2915, "s": 2903, "text": "Golang Maps" }, { "code": null, "e": 2928, "s": 2915, "text": "Arrays in Go" }, { "code": null, "e": 2975, "s": 2928, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 3027, "s": 2975, "text": "How to copy one slice into another slice in Golang?" }, { "code": null, "e": 3052, "s": 3027, "text": "Time Durations in Golang" }, { "code": null, "e": 3101, "s": 3052, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 3122, "s": 3101, "text": "Interfaces in Golang" }, { "code": null, "e": 3144, "s": 3122, "text": "Inheritance in GoLang" }, { "code": null, "e": 3203, "s": 3144, "text": "Check if the String starts with specified prefix in Golang" } ]
Python program to generate a list of alphabets in lexical order
11 Oct, 2020 Prerequisite: chr() The following methods explain how a python list with alphabets in lexical(alphabetic) order can be generated dynamically using chr() method. Approach: The core of the concept in both methods is almost same, they only differ in implementation: Validate size of alphabet list(size=26).If size>26, change to 26.If size≤0, no meaning left to the function and to make it meaningful set size to 26.Use chr() to produce the list using any of following methods. Validate size of alphabet list(size=26). If size>26, change to 26. If size≤0, no meaning left to the function and to make it meaningful set size to 26. Use chr() to produce the list using any of following methods. Method 1: Using loop Python3 # function to get the list of alphabetsdef generateAlphabetListDynamically(size = 26): size = 26 if (size > 26 or size <= 0) else size # Empty list alphabetList = [] # Looping from 0 to required size for i in range(size): alphabetList.append(chr(65 + i)) # return the generated list return alphabetList alphabetList = generateAlphabetListDynamically()print('The alphabets in the list are:', *alphabetList) Output: The alphabets in the list are: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Method 2: using list comprehension Python3 def generateAlphabetListDynamically(size=26): size = 26 if (size > 26 or size <= 0) else size # Here we are looping from 0 to upto specified size # 65 is added because it is ascii equivalent of 'A' alphabetList = [chr(i+65) for i in range(size)] # returning the list return alphabetList # Calling the function to get the alphabetsalphabetList = generateAlphabetListDynamically()print('The alphabets in the list are:', *alphabetList) Output: The alphabets in the list are: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Python string-programs Python Python Programs 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2020" }, { "code": null, "e": 48, "s": 28, "text": "Prerequisite: chr()" }, { "code": null, "e": 189, "s": 48, "text": "The following methods explain how a python list with alphabets in lexical(alphabetic) order can be generated dynamically using chr() method." }, { "code": null, "e": 199, "s": 189, "text": "Approach:" }, { "code": null, "e": 291, "s": 199, "text": "The core of the concept in both methods is almost same, they only differ in implementation:" }, { "code": null, "e": 502, "s": 291, "text": "Validate size of alphabet list(size=26).If size>26, change to 26.If size≤0, no meaning left to the function and to make it meaningful set size to 26.Use chr() to produce the list using any of following methods." }, { "code": null, "e": 543, "s": 502, "text": "Validate size of alphabet list(size=26)." }, { "code": null, "e": 569, "s": 543, "text": "If size>26, change to 26." }, { "code": null, "e": 654, "s": 569, "text": "If size≤0, no meaning left to the function and to make it meaningful set size to 26." }, { "code": null, "e": 716, "s": 654, "text": "Use chr() to produce the list using any of following methods." }, { "code": null, "e": 737, "s": 716, "text": "Method 1: Using loop" }, { "code": null, "e": 745, "s": 737, "text": "Python3" }, { "code": "# function to get the list of alphabetsdef generateAlphabetListDynamically(size = 26): size = 26 if (size > 26 or size <= 0) else size # Empty list alphabetList = [] # Looping from 0 to required size for i in range(size): alphabetList.append(chr(65 + i)) # return the generated list return alphabetList alphabetList = generateAlphabetListDynamically()print('The alphabets in the list are:', *alphabetList)", "e": 1178, "s": 745, "text": null }, { "code": null, "e": 1186, "s": 1178, "text": "Output:" }, { "code": null, "e": 1269, "s": 1186, "text": "The alphabets in the list are: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" }, { "code": null, "e": 1304, "s": 1269, "text": "Method 2: using list comprehension" }, { "code": null, "e": 1312, "s": 1304, "text": "Python3" }, { "code": "def generateAlphabetListDynamically(size=26): size = 26 if (size > 26 or size <= 0) else size # Here we are looping from 0 to upto specified size # 65 is added because it is ascii equivalent of 'A' alphabetList = [chr(i+65) for i in range(size)] # returning the list return alphabetList # Calling the function to get the alphabetsalphabetList = generateAlphabetListDynamically()print('The alphabets in the list are:', *alphabetList)", "e": 1770, "s": 1312, "text": null }, { "code": null, "e": 1778, "s": 1770, "text": "Output:" }, { "code": null, "e": 1861, "s": 1778, "text": "The alphabets in the list are: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" }, { "code": null, "e": 1884, "s": 1861, "text": "Python string-programs" }, { "code": null, "e": 1891, "s": 1884, "text": "Python" }, { "code": null, "e": 1907, "s": 1891, "text": "Python Programs" }, { "code": null, "e": 2005, "s": 1907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2037, "s": 2005, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2064, "s": 2037, "text": "Python Classes and Objects" }, { "code": null, "e": 2085, "s": 2064, "text": "Python OOPs Concepts" }, { "code": null, "e": 2108, "s": 2085, "text": "Introduction To PYTHON" }, { "code": null, "e": 2164, "s": 2108, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2186, "s": 2164, "text": "Defaultdict in Python" }, { "code": null, "e": 2225, "s": 2186, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2263, "s": 2225, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2312, "s": 2263, "text": "Python | Convert string dictionary to dictionary" } ]
How to create a dynamic JSON file by fetching data from localserver database ?
22 Jun, 2020 JSON stands for JavaScript Object Notation and is a structured format used for storing and transporting data. It acts as an interface between a server and a web page. It is a lightweight data-interchange format. It is language independent and easy to understand. It is derived from Javascript. JSON objects can be converted to javascript objects and vice-versa using functions like stringify() and parse().Here, before going through the program, we need to create a MySQL database in our localhost server. PHP is used to connect with the localhost server and to fetch the data from the database table present in our localhost server by evaluating the MySQL queries. Wampserver helps to start Apache and MySQL and connect them with the PHP file. In our PHP code, we are going to make an array of data fetched from the database and then convert them into JSON. A dynamic JSON file will be created to store the array of JSON objects. Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails.json by converting them into an array of JSON objects. Creating Database: Example: <?php // PHP program to connect with// localserver database$user = 'root';$password = ''; $database = 'gfg'; $servername ='localhost:3308'; $mysqli = new mysqli($servername, $user, $password, $database); if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);} // SQL query to select data// from database$sql2 = "SELECT * FROM userdata";$result = $mysqli->query($sql2); // Fetching data from the database// and storing in array of objectswhile($row = $result->fetch_array()) { $studentdata[] = array( "GFG_User_Name" => $row["username"], "No_Of_Problems" => $row["problems"], "Total_Score" => $row["score"], "Articles" => $row["articles"], );} // Creating a dynamic JSON file$file = "gfguserdetails.json"; // Converting data into JSON and putting// into the file// Checking for its creationif(file_put_contents($file, json_encode($studentdata))) echo("File created");else echo("Failed"); // Closing the database$mysqli->close(); ?> Output: The dynamic JSON file created after running the code on the browser: PHP-Misc PHP PHP Programs Web Technologies Web technologies Questions PHP 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": 959, "s": 28, "text": "JSON stands for JavaScript Object Notation and is a structured format used for storing and transporting data. It acts as an interface between a server and a web page. It is a lightweight data-interchange format. It is language independent and easy to understand. It is derived from Javascript. JSON objects can be converted to javascript objects and vice-versa using functions like stringify() and parse().Here, before going through the program, we need to create a MySQL database in our localhost server. PHP is used to connect with the localhost server and to fetch the data from the database table present in our localhost server by evaluating the MySQL queries. Wampserver helps to start Apache and MySQL and connect them with the PHP file. In our PHP code, we are going to make an array of data fetched from the database and then convert them into JSON. A dynamic JSON file will be created to store the array of JSON objects." }, { "code": null, "e": 1184, "s": 959, "text": "Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails.json by converting them into an array of JSON objects." }, { "code": null, "e": 1203, "s": 1184, "text": "Creating Database:" }, { "code": null, "e": 1212, "s": 1203, "text": "Example:" }, { "code": "<?php // PHP program to connect with// localserver database$user = 'root';$password = ''; $database = 'gfg'; $servername ='localhost:3308'; $mysqli = new mysqli($servername, $user, $password, $database); if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);} // SQL query to select data// from database$sql2 = \"SELECT * FROM userdata\";$result = $mysqli->query($sql2); // Fetching data from the database// and storing in array of objectswhile($row = $result->fetch_array()) { $studentdata[] = array( \"GFG_User_Name\" => $row[\"username\"], \"No_Of_Problems\" => $row[\"problems\"], \"Total_Score\" => $row[\"score\"], \"Articles\" => $row[\"articles\"], );} // Creating a dynamic JSON file$file = \"gfguserdetails.json\"; // Converting data into JSON and putting// into the file// Checking for its creationif(file_put_contents($file, json_encode($studentdata))) echo(\"File created\");else echo(\"Failed\"); // Closing the database$mysqli->close(); ?>", "e": 2279, "s": 1212, "text": null }, { "code": null, "e": 2287, "s": 2279, "text": "Output:" }, { "code": null, "e": 2356, "s": 2287, "text": "The dynamic JSON file created after running the code on the browser:" }, { "code": null, "e": 2365, "s": 2356, "text": "PHP-Misc" }, { "code": null, "e": 2369, "s": 2365, "text": "PHP" }, { "code": null, "e": 2382, "s": 2369, "text": "PHP Programs" }, { "code": null, "e": 2399, "s": 2382, "text": "Web Technologies" }, { "code": null, "e": 2426, "s": 2399, "text": "Web technologies Questions" }, { "code": null, "e": 2430, "s": 2426, "text": "PHP" } ]
TCL script to simulate link state routing in ns2
13 Apr, 2021 In this article we will know how to write a TCL script for the simulation of one of the routing protocols link state routing (also called dijkstra’s algorithm) using the Network Simulator. To understand more about the basics of TCL scripts you can check out this article https://www.geeksforgeeks.org/basics-of-ns2-and-otcltcl-script/. TCL script to simulate link state routing in ns2 :To implement TCL script to simulate link state routing in ns2, we will go through the various steps in simulating LS (Link State) routing, each with several lines of code as follows. Step-1: Initializing the network :The first step is to initialize the network simulator, and we do so by creating a network simulator object. After that, we initialize rtproto (routing protocol) to Link State (LS). set ns [new Simulator] $ns rtproto LS Step-2: Creating number of nodes :We next create a random number of nodes, let’s say 7. We use the node instance to create these nodes as follows. set node1 [$ns node] set node2 [$ns node] set node3 [$ns node] set node4 [$ns node] set node5 [$ns node] set node6 [$ns node] set node7 [$ns node] Step-3: Creating the trace file :Our next step is to create the trace file and nam file. The nam file is used to view simulator output whereas the trace file traces all the routing information in the process. For this we create trace file and nam file objects and then open the files in write mode. The trace-all instance is used to trace all routing information into the trace file and similarly namtrace-all for the nam file. set tf [open out.tr w] $ns trace-all $tf set nf [open out.nam w] $ns namtrace-all $nf Step-4: Labeling the nodes :In the next step we can label the nodes if we wish to. Here we are labeling them from node 0 to node 6. We can also customize the labels by assigning different colors to them and thus viewing the simulation much more clearly. Here we will use red and blue. $node1 label "node 1" $node1 label "node 2" $node1 label "node 3" $node1 label "node 4" $node1 label "node 5" $node1 label "node 6" $node1 label "node 7" $node1 label-color blue $node2 label-color red $node3 label-color red $node4 label-color blue $node5 label-color blue $node6 label-color blue $node7 label-color blue Step-5: Creating duplex links :The next step is to create duplex links between the nodes forming a ring in the end. This can be achieved by using the duplex-link instance along with specifying three parameters: data rate (1.5Mb), delay (10ms) and kind of queue (DropTail). $ns duplex-link $node1 $node2 1.5Mb 10ms DropTail $ns duplex-link $node2 $node3 1.5Mb 10ms DropTail $ns duplex-link $node3 $node4 1.5Mb 10ms DropTail $ns duplex-link $node4 $node5 1.5Mb 10ms DropTail $ns duplex-link $node5 $node6 1.5Mb 10ms DropTail $ns duplex-link $node6 $node7 1.5Mb 10ms DropTail $ns duplex-link $node7 $node1 1.5Mb 10ms DropTail Step-6: Orient the links between the nodes :Now we need to orient the links between the nodes appropriately to obtain proper alignment. The duplex-link-op instance is used for the same. $ns duplex-link-op $node1 $node2 orient left-down $ns duplex-link-op $node2 $node3 orient left-down $ns duplex-link-op $node3 $node4 orient right-down $ns duplex-link-op $node4 $node5 orient right $ns duplex-link-op $node5 $node6 orient right-up $ns duplex-link-op $node6 $node7 orient left-up $ns duplex-link-op $node7 $node1 orient left-up Step-7: Attaching TCP agents :The next step is to attach TCP agents (using attach-agent) at two nodes let’s say node 1 and node 4. We can do this creating the source and sink objects and connecting them using connect instance. set tcp2 [new Agent/TCP] $ns attach-agent $node1 $tcp2 set sink2 [new Agent/TCPSink] $ns attach-agent $node4 $sink2 $ns connect $tcp2 $sink2 Step-8: Creating FTP traffic :Our next step is to create FTP traffic and attach to TCP source. The traffic then flows across node 1 and node 4. We can do this by creating an FTP agent and attaching it to tcp2. set traffic_ftp2 [new Application/FTP] $traffic_ftp2 attach-agent $tcp2 Step-9: Adding a finish procedure :The next step is to add a finish procedure to flush all data into trace file and then and then run the nam file. proc finish{} { global ns nf $ns flush-trace close $nf exec nam out.nam & exit 0 } Step-10: Scheduling the FTP :The final step is to schedule the FTP traffic at the required time intervals. We can also disable the link between any pair of nodes at a certain timestamp using rtmodel-at instance and then enable it after a certain time. This is majorly done for testing purposes. Here we have disabled the link between nodes 2 and 3. The program ends with the run command. $ns at 0.5 "traffic_ftp2 start" $ns rtmodel-at 1.0 down $node2 $node3 $ns rtmodel-at 2.0 up $node2 $node3 $ns at 3.0 "traffic_ftp2 start" $ns at 4.0 "traffic_ftp2 stop" $ns at 5.0 "finish" $ns run Output :The final output can be visualized as follows. Simulation before disabling the link As shown in the figure above there is a normal flow of packets from node 1 to node 4. We now disable the link between nodes 2 and 3 at time 1 and the simulations changes as shown below. The disabled link is shown in red and the packet flow this time changes direction rather than the original route to node 4. Simulation when link between node2 and node3 is disabled Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Introduction of Mobile Ad hoc Network (MANET) Advanced Encryption Standard (AES) Bluetooth Intrusion Detection System (IDS) Cryptography and its Types Difference between FDMA, TDMA and CDMA
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2021" }, { "code": null, "e": 365, "s": 28, "text": "In this article we will know how to write a TCL script for the simulation of one of the routing protocols link state routing (also called dijkstra’s algorithm) using the Network Simulator. To understand more about the basics of TCL scripts you can check out this article https://www.geeksforgeeks.org/basics-of-ns2-and-otcltcl-script/. " }, { "code": null, "e": 598, "s": 365, "text": "TCL script to simulate link state routing in ns2 :To implement TCL script to simulate link state routing in ns2, we will go through the various steps in simulating LS (Link State) routing, each with several lines of code as follows." }, { "code": null, "e": 813, "s": 598, "text": "Step-1: Initializing the network :The first step is to initialize the network simulator, and we do so by creating a network simulator object. After that, we initialize rtproto (routing protocol) to Link State (LS)." }, { "code": null, "e": 851, "s": 813, "text": "set ns [new Simulator]\n$ns rtproto LS" }, { "code": null, "e": 998, "s": 851, "text": "Step-2: Creating number of nodes :We next create a random number of nodes, let’s say 7. We use the node instance to create these nodes as follows." }, { "code": null, "e": 1145, "s": 998, "text": "set node1 [$ns node]\nset node2 [$ns node]\nset node3 [$ns node]\nset node4 [$ns node]\nset node5 [$ns node]\nset node6 [$ns node]\nset node7 [$ns node]" }, { "code": null, "e": 1573, "s": 1145, "text": "Step-3: Creating the trace file :Our next step is to create the trace file and nam file. The nam file is used to view simulator output whereas the trace file traces all the routing information in the process. For this we create trace file and nam file objects and then open the files in write mode. The trace-all instance is used to trace all routing information into the trace file and similarly namtrace-all for the nam file." }, { "code": null, "e": 1659, "s": 1573, "text": "set tf [open out.tr w]\n$ns trace-all $tf\nset nf [open out.nam w]\n$ns namtrace-all $nf" }, { "code": null, "e": 1944, "s": 1659, "text": "Step-4: Labeling the nodes :In the next step we can label the nodes if we wish to. Here we are labeling them from node 0 to node 6. We can also customize the labels by assigning different colors to them and thus viewing the simulation much more clearly. Here we will use red and blue." }, { "code": null, "e": 2264, "s": 1944, "text": "$node1 label \"node 1\"\n$node1 label \"node 2\"\n$node1 label \"node 3\"\n$node1 label \"node 4\"\n$node1 label \"node 5\"\n$node1 label \"node 6\"\n$node1 label \"node 7\"\n$node1 label-color blue\n$node2 label-color red\n$node3 label-color red\n$node4 label-color blue\n$node5 label-color blue\n$node6 label-color blue\n$node7 label-color blue" }, { "code": null, "e": 2537, "s": 2264, "text": "Step-5: Creating duplex links :The next step is to create duplex links between the nodes forming a ring in the end. This can be achieved by using the duplex-link instance along with specifying three parameters: data rate (1.5Mb), delay (10ms) and kind of queue (DropTail)." }, { "code": null, "e": 2887, "s": 2537, "text": "$ns duplex-link $node1 $node2 1.5Mb 10ms DropTail\n$ns duplex-link $node2 $node3 1.5Mb 10ms DropTail\n$ns duplex-link $node3 $node4 1.5Mb 10ms DropTail\n$ns duplex-link $node4 $node5 1.5Mb 10ms DropTail\n$ns duplex-link $node5 $node6 1.5Mb 10ms DropTail\n$ns duplex-link $node6 $node7 1.5Mb 10ms DropTail\n$ns duplex-link $node7 $node1 1.5Mb 10ms DropTail" }, { "code": null, "e": 3073, "s": 2887, "text": "Step-6: Orient the links between the nodes :Now we need to orient the links between the nodes appropriately to obtain proper alignment. The duplex-link-op instance is used for the same." }, { "code": null, "e": 3415, "s": 3073, "text": "$ns duplex-link-op $node1 $node2 orient left-down\n$ns duplex-link-op $node2 $node3 orient left-down\n$ns duplex-link-op $node3 $node4 orient right-down\n$ns duplex-link-op $node4 $node5 orient right\n$ns duplex-link-op $node5 $node6 orient right-up\n$ns duplex-link-op $node6 $node7 orient left-up\n$ns duplex-link-op $node7 $node1 orient left-up" }, { "code": null, "e": 3642, "s": 3415, "text": "Step-7: Attaching TCP agents :The next step is to attach TCP agents (using attach-agent) at two nodes let’s say node 1 and node 4. We can do this creating the source and sink objects and connecting them using connect instance." }, { "code": null, "e": 3783, "s": 3642, "text": "set tcp2 [new Agent/TCP]\n$ns attach-agent $node1 $tcp2\nset sink2 [new Agent/TCPSink]\n$ns attach-agent $node4 $sink2\n$ns connect $tcp2 $sink2" }, { "code": null, "e": 3993, "s": 3783, "text": "Step-8: Creating FTP traffic :Our next step is to create FTP traffic and attach to TCP source. The traffic then flows across node 1 and node 4. We can do this by creating an FTP agent and attaching it to tcp2." }, { "code": null, "e": 4065, "s": 3993, "text": "set traffic_ftp2 [new Application/FTP]\n$traffic_ftp2 attach-agent $tcp2" }, { "code": null, "e": 4213, "s": 4065, "text": "Step-9: Adding a finish procedure :The next step is to add a finish procedure to flush all data into trace file and then and then run the nam file." }, { "code": null, "e": 4299, "s": 4213, "text": "proc finish{} {\n\nglobal ns nf\n$ns flush-trace\nclose $nf\nexec nam out.nam &\nexit 0\n \n}" }, { "code": null, "e": 4687, "s": 4299, "text": "Step-10: Scheduling the FTP :The final step is to schedule the FTP traffic at the required time intervals. We can also disable the link between any pair of nodes at a certain timestamp using rtmodel-at instance and then enable it after a certain time. This is majorly done for testing purposes. Here we have disabled the link between nodes 2 and 3. The program ends with the run command." }, { "code": null, "e": 4884, "s": 4687, "text": "$ns at 0.5 \"traffic_ftp2 start\"\n$ns rtmodel-at 1.0 down $node2 $node3\n$ns rtmodel-at 2.0 up $node2 $node3\n$ns at 3.0 \"traffic_ftp2 start\"\n$ns at 4.0 \"traffic_ftp2 stop\"\n$ns at 5.0 \"finish\"\n$ns run" }, { "code": null, "e": 4939, "s": 4884, "text": "Output :The final output can be visualized as follows." }, { "code": null, "e": 4976, "s": 4939, "text": "Simulation before disabling the link" }, { "code": null, "e": 5286, "s": 4976, "text": "As shown in the figure above there is a normal flow of packets from node 1 to node 4. We now disable the link between nodes 2 and 3 at time 1 and the simulations changes as shown below. The disabled link is shown in red and the packet flow this time changes direction rather than the original route to node 4." }, { "code": null, "e": 5343, "s": 5286, "text": "Simulation when link between node2 and node3 is disabled" }, { "code": null, "e": 5361, "s": 5343, "text": "Computer Networks" }, { "code": null, "e": 5379, "s": 5361, "text": "Computer Networks" }, { "code": null, "e": 5477, "s": 5379, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5507, "s": 5477, "text": "GSM in Wireless Communication" }, { "code": null, "e": 5533, "s": 5507, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 5563, "s": 5533, "text": "Wireless Application Protocol" }, { "code": null, "e": 5603, "s": 5563, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 5649, "s": 5603, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 5684, "s": 5649, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 5694, "s": 5684, "text": "Bluetooth" }, { "code": null, "e": 5727, "s": 5694, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 5754, "s": 5727, "text": "Cryptography and its Types" } ]
MuleSoft - Endpoints
Endpoints basically include those components that trigger or initiate the processing in a working flow of Mule application. They are called Source in Anypoint Studio and Triggers in the Design Center of Mule. One important endpoint in Mule 4 is Scheduler component. This component works on time-based conditions, which means, it enables us to trigger a flow whenever a time-based condition is met. For example, a scheduler can trigger an event to start a Mule working flow every, say 10 seconds. We can also use flexible Cron expression to trigger a Scheduler Endpoint. While using Scheduler event, we need to take care of some important points as given below − Scheduler Endpoint follows the time-zone of the machine where Mule runtime is running. Scheduler Endpoint follows the time-zone of the machine where Mule runtime is running. Suppose if a Mule application is running in CloudHub, the Scheduler will follow the time-zone of the region in which the CloudHub worker is running. Suppose if a Mule application is running in CloudHub, the Scheduler will follow the time-zone of the region in which the CloudHub worker is running. At any given time, only one flow triggered by the Scheduler Endpoint can be active. At any given time, only one flow triggered by the Scheduler Endpoint can be active. In Mule runtime cluster, the Scheduler Endpoint runs or triggers only on primary node. In Mule runtime cluster, the Scheduler Endpoint runs or triggers only on primary node. As discussed above, we can configure a scheduler endpoint to be triggered at a fixed interval or we can also give a Cron expression. Following are the parameters to set a scheduler to trigger a flow at regular intervals − Frequency − It basically describes at which frequency the Scheduler Endpoint will trigger the Mule flow. Unit of time for this can be selected from the Time Unit field. In case you do not provide any values for this, it will use the default value which is 1000. On the other side, if you provide 0 or a negative value, then also it uses the default value. Start Delay − It is the amount of time we must wait before triggering the Mule flow for the first time once the application is started. The value of Start delay is expressed in the same unit of time as the frequency. Its default value is 0. Time Unit − It describes the time unit for both Frequency and Start Delay. The possible values of time unit are Milliseconds, Seconds, Minute, Hours, Days. The default value is Milliseconds. Actually, Cron is a standard used for describing time and date information. In case you use the flexible Cron expression to make Scheduler trigger, the Scheduler Endpoint keeps track of every second and creates a Mule event whenever the Quartz Cron expression matches the time-date setting. With Cron expression, the event can be triggered just once or at regular intervals. Following table gives the date-time expression of six required settings − Some examples of Quartz Cron expressions supported by the Scheduler Endpoint are given below − 1⁄2 * * * * ? − means that the scheduler runs every 2 seconds of the day, every day. 1⁄2 * * * * ? − means that the scheduler runs every 2 seconds of the day, every day. 0 0/5 16 ** ? − means that the scheduler runs every 5 minutes starting at 4 pm and ending at 4:55 pm, every day. 0 0/5 16 ** ? − means that the scheduler runs every 5 minutes starting at 4 pm and ending at 4:55 pm, every day. 1 1 1 1, 5 * ? − means that the scheduler runs the first day of January and the first day of April, every year. 1 1 1 1, 5 * ? − means that the scheduler runs the first day of January and the first day of April, every year. The following code logs the message “hi” every second − <flow name = "cronFlow" doc:id = "ae257a5d-6b4f-4006-80c8-e7c76d2f67a0"> <doc:name = "Scheduler" doc:id = "e7b6scheduler8ccb-c6d8-4567-87af-aa7904a50359"> <scheduling-strategy> <cron expression = "* * * * * ?" timeZone = "America/Los_Angeles"/> </scheduling-strategy> </scheduler> <logger level = "INFO" doc:name = "Logger" doc:id = "e2626dbb-54a9-4791-8ffa-b7c9a23e88a1" message = '"hi"'/>
[ { "code": null, "e": 2468, "s": 2202, "text": "Endpoints basically include those components that trigger or initiate the processing in a working flow of Mule application. They are called Source in Anypoint Studio and Triggers in the Design Center of Mule. One important endpoint in Mule 4 is Scheduler component." }, { "code": null, "e": 2772, "s": 2468, "text": "This component works on time-based conditions, which means, it enables us to trigger a flow whenever a time-based condition is met. For example, a scheduler can trigger an event to start a Mule working flow every, say 10 seconds. We can also use flexible Cron expression to trigger a Scheduler Endpoint." }, { "code": null, "e": 2864, "s": 2772, "text": "While using Scheduler event, we need to take care of some important points as given below −" }, { "code": null, "e": 2951, "s": 2864, "text": "Scheduler Endpoint follows the time-zone of the machine where Mule runtime is running." }, { "code": null, "e": 3038, "s": 2951, "text": "Scheduler Endpoint follows the time-zone of the machine where Mule runtime is running." }, { "code": null, "e": 3187, "s": 3038, "text": "Suppose if a Mule application is running in CloudHub, the Scheduler will follow the time-zone of the region in which the CloudHub worker is running." }, { "code": null, "e": 3336, "s": 3187, "text": "Suppose if a Mule application is running in CloudHub, the Scheduler will follow the time-zone of the region in which the CloudHub worker is running." }, { "code": null, "e": 3420, "s": 3336, "text": "At any given time, only one flow triggered by the Scheduler Endpoint can be active." }, { "code": null, "e": 3504, "s": 3420, "text": "At any given time, only one flow triggered by the Scheduler Endpoint can be active." }, { "code": null, "e": 3591, "s": 3504, "text": "In Mule runtime cluster, the Scheduler Endpoint runs or triggers only on primary node." }, { "code": null, "e": 3678, "s": 3591, "text": "In Mule runtime cluster, the Scheduler Endpoint runs or triggers only on primary node." }, { "code": null, "e": 3811, "s": 3678, "text": "As discussed above, we can configure a scheduler endpoint to be triggered at a fixed interval or we can also give a Cron expression." }, { "code": null, "e": 3900, "s": 3811, "text": "Following are the parameters to set a scheduler to trigger a flow at regular intervals −" }, { "code": null, "e": 4256, "s": 3900, "text": "Frequency − It basically describes at which frequency the Scheduler Endpoint will trigger the Mule flow. Unit of time for this can be selected from the Time Unit field. In case you do not provide any values for this, it will use the default value which is 1000. On the other side, if you provide 0 or a negative value, then also it uses the default value." }, { "code": null, "e": 4497, "s": 4256, "text": "Start Delay − It is the amount of time we must wait before triggering the Mule flow for the first time once the application is started. The value of Start delay is expressed in the same unit of time as the frequency. Its default value is 0." }, { "code": null, "e": 4688, "s": 4497, "text": "Time Unit − It describes the time unit for both Frequency and Start Delay. The possible values of time unit are Milliseconds, Seconds, Minute, Hours, Days. The default value is Milliseconds." }, { "code": null, "e": 5063, "s": 4688, "text": "Actually, Cron is a standard used for describing time and date information. In case you use the flexible Cron expression to make Scheduler trigger, the Scheduler Endpoint keeps track of every second and creates a Mule event whenever the Quartz Cron expression matches the time-date setting. With Cron expression, the event can be triggered just once or at regular intervals." }, { "code": null, "e": 5137, "s": 5063, "text": "Following table gives the date-time expression of six required settings −" }, { "code": null, "e": 5232, "s": 5137, "text": "Some examples of Quartz Cron expressions supported by the Scheduler Endpoint are given below −" }, { "code": null, "e": 5317, "s": 5232, "text": "1⁄2 * * * * ? − means that the scheduler runs every 2 seconds of the day, every day." }, { "code": null, "e": 5402, "s": 5317, "text": "1⁄2 * * * * ? − means that the scheduler runs every 2 seconds of the day, every day." }, { "code": null, "e": 5515, "s": 5402, "text": "0 0/5 16 ** ? − means that the scheduler runs every 5 minutes starting at 4 pm and ending at 4:55 pm, every day." }, { "code": null, "e": 5628, "s": 5515, "text": "0 0/5 16 ** ? − means that the scheduler runs every 5 minutes starting at 4 pm and ending at 4:55 pm, every day." }, { "code": null, "e": 5740, "s": 5628, "text": "1 1 1 1, 5 * ? − means that the scheduler runs the first day of January and the first day of April, every year." }, { "code": null, "e": 5852, "s": 5740, "text": "1 1 1 1, 5 * ? − means that the scheduler runs the first day of January and the first day of April, every year." }, { "code": null, "e": 5908, "s": 5852, "text": "The following code logs the message “hi” every second −" } ]
How to ORDER BY FIELD with GROUP BY in a single MySQL query?
For this, let us first create a table − mysql> create table DemoTable ( Message text ); Query OK, 0 rows affected (1.15 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('Good'); Query OK, 1 row affected (0.43 sec) mysql> insert into DemoTable values('Bye'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Awesome'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Bye'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values('Good'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('Amazing'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Awesome'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Bye'); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +---------+ | Message | +---------+ | Good | | Bye | | Awesome | | Bye | | Good | | Amazing | | Awesome | | Bye | +---------+ 8 rows in set (0.00 sec) Following is the query to ORDER BY FIELD with GROUP BY in a single MySQL query − mysql> select *from DemoTable group by Message order by field(Message,'Amazing','Awesome','Good','Bye'); This will produce the following output − +---------+ | Message | +---------+ | Amazing | | Awesome | | Good | | Bye | +---------+ 4 rows in set (0.04 sec)
[ { "code": null, "e": 1227, "s": 1187, "text": "For this, let us first create a table −" }, { "code": null, "e": 1315, "s": 1227, "text": "mysql> create table DemoTable\n(\n Message text\n);\nQuery OK, 0 rows affected (1.15 sec)" }, { "code": null, "e": 1371, "s": 1315, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2025, "s": 1371, "text": "mysql> insert into DemoTable values('Good');\nQuery OK, 1 row affected (0.43 sec)\nmysql> insert into DemoTable values('Bye');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('Awesome');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values('Bye');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable values('Good');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable values('Amazing');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values('Awesome');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values('Bye');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2085, "s": 2025, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2116, "s": 2085, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2157, "s": 2116, "text": "This will produce the following output −" }, { "code": null, "e": 2326, "s": 2157, "text": "+---------+\n| Message |\n+---------+\n| Good |\n| Bye |\n| Awesome |\n| Bye |\n| Good |\n| Amazing |\n| Awesome |\n| Bye |\n+---------+\n8 rows in set (0.00 sec)" }, { "code": null, "e": 2407, "s": 2326, "text": "Following is the query to ORDER BY FIELD with GROUP BY in a single MySQL query −" }, { "code": null, "e": 2518, "s": 2407, "text": "mysql> select *from DemoTable\n group by Message\n order by field(Message,'Amazing','Awesome','Good','Bye');" }, { "code": null, "e": 2559, "s": 2518, "text": "This will produce the following output −" }, { "code": null, "e": 2680, "s": 2559, "text": "+---------+\n| Message |\n+---------+\n| Amazing |\n| Awesome |\n| Good |\n| Bye |\n+---------+\n4 rows in set (0.04 sec)" } ]
How to set cell padding in HTML?
Cell padding is the space between cell borders and the content within a cell. To set cell padding in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <table> tag, with the CSS property padding. HTML5 do not support the cellpadding attribute of <table>, so the CSS property padding is used with the style attribute to set cell padding. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try to run the following code to set cell padding in HTML. We’re also using the <style> tag and the style attribute to style the table <!DOCTYPE html> <html> <head> <style> table, th, td { border: 1px solid black; } </style> </head> <body> <h1>Programming Language</h1> <table> <tr> <th style="padding:10px">Language</th> </tr> <tr> <td style="padding:10px">Ruby</td> </tr> </table> </body> </html>
[ { "code": null, "e": 1461, "s": 1187, "text": "Cell padding is the space between cell borders and the content within a cell. To set cell padding in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <table> tag, with the CSS property padding." }, { "code": null, "e": 1602, "s": 1461, "text": "HTML5 do not support the cellpadding attribute of <table>, so the CSS property padding is used with the style attribute to set cell padding." }, { "code": null, "e": 1764, "s": 1602, "text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1907, "s": 1764, "text": "You can try to run the following code to set cell padding in HTML. We’re also using the <style> tag and the style attribute to style the table" }, { "code": null, "e": 2304, "s": 1907, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n table, th, td {\n border: 1px solid black;\n }\n </style>\n </head>\n\n <body>\n <h1>Programming Language</h1>\n <table>\n <tr>\n <th style=\"padding:10px\">Language</th>\n </tr>\n <tr>\n <td style=\"padding:10px\">Ruby</td>\n </tr>\n </table>\n </body>\n</html>" } ]