title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Memset in C++ - GeeksforGeeks | 08 Dec, 2021
Memset() is a C++ function. It copies a single character for a specified number of times to an object. It is defined in <cstring> header file.
Syntax:
void* memset( void* str, int ch, size_t n);
Memset() converts the value ch to unsigned char and copies it into each of the first n characters of the object pointed to by str[]. If the object is not trivially-copyable (e.g., scalar, array, or a C-compatible struct), the behavior is undefined. If n is greater than the size of the object pointed to by str, the behavior is undefined.
Parameters:
str[] : Pointer to the object to copy the character.
ch : The character to copy.
n : Number of bytes to copy.
Return value: The memset() function returns str, the pointer to the destination string.
CPP
// CPP program to demonstrate memset#include <cstring>#include <iostream>using namespace std; // Driver Codeint main(){ char str[] = "geeksforgeeks"; memset(str, 't', sizeof(str)); cout << str; return 0;}
tttttttttttttt
Note: We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values. The reason is simple, memset works byte by byte.
CPP
// CPP Program to demonstrate that we can use memset() to// set all values as 0 or -1 for integral data types also#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int a[5]; // all elements of A are zero memset(a, 0, sizeof(a)); for (int i = 0; i < 5; i++) cout << a[i] << " "; cout << endl; // all elements of A are -1 memset(a, -1, sizeof(a)); for (int i = 0; i < 5; i++) cout << a[i] << " "; cout << endl; // Would not work memset(a, 5, sizeof(a)); // WRONG for (int i = 0; i < 5; i++) cout << a[i] << " ";}
0 0 0 0 0
-1 -1 -1 -1 -1
84215045 84215045 84215045 84215045 84215045
See Also:
memcpy() in C/C++
memcmp() in C++
This article is contributed by Pranav. 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.
balajimarisetti
anshikajain26
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
Socket Programming in C/C++
Operator Overloading in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Constructors in C++
Iterators in C++ STL
Copy Constructor in C++ | [
{
"code": null,
"e": 24244,
"s": 24216,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 24387,
"s": 24244,
"text": "Memset() is a C++ function. It copies a single character for a specified number of times to an object. It is defined in <cstring> header file."
},
{
"code": null,
"e": 24395,
"s": 24387,
"text": "Syntax:"
},
{
"code": null,
"e": 24439,
"s": 24395,
"text": "void* memset( void* str, int ch, size_t n);"
},
{
"code": null,
"e": 24779,
"s": 24439,
"text": "Memset() converts the value ch to unsigned char and copies it into each of the first n characters of the object pointed to by str[]. If the object is not trivially-copyable (e.g., scalar, array, or a C-compatible struct), the behavior is undefined. If n is greater than the size of the object pointed to by str, the behavior is undefined. "
},
{
"code": null,
"e": 24791,
"s": 24779,
"text": "Parameters:"
},
{
"code": null,
"e": 24844,
"s": 24791,
"text": "str[] : Pointer to the object to copy the character."
},
{
"code": null,
"e": 24872,
"s": 24844,
"text": "ch : The character to copy."
},
{
"code": null,
"e": 24901,
"s": 24872,
"text": "n : Number of bytes to copy."
},
{
"code": null,
"e": 24990,
"s": 24901,
"text": "Return value: The memset() function returns str, the pointer to the destination string. "
},
{
"code": null,
"e": 24994,
"s": 24990,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate memset#include <cstring>#include <iostream>using namespace std; // Driver Codeint main(){ char str[] = \"geeksforgeeks\"; memset(str, 't', sizeof(str)); cout << str; return 0;}",
"e": 25211,
"s": 24994,
"text": null
},
{
"code": null,
"e": 25226,
"s": 25211,
"text": "tttttttttttttt"
},
{
"code": null,
"e": 25416,
"s": 25226,
"text": "Note: We can use memset() to set all values as 0 or -1 for integral data types also. It will not work if we use it to set as other values. The reason is simple, memset works byte by byte. "
},
{
"code": null,
"e": 25420,
"s": 25416,
"text": "CPP"
},
{
"code": "// CPP Program to demonstrate that we can use memset() to// set all values as 0 or -1 for integral data types also#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int a[5]; // all elements of A are zero memset(a, 0, sizeof(a)); for (int i = 0; i < 5; i++) cout << a[i] << \" \"; cout << endl; // all elements of A are -1 memset(a, -1, sizeof(a)); for (int i = 0; i < 5; i++) cout << a[i] << \" \"; cout << endl; // Would not work memset(a, 5, sizeof(a)); // WRONG for (int i = 0; i < 5; i++) cout << a[i] << \" \";}",
"e": 26012,
"s": 25420,
"text": null
},
{
"code": null,
"e": 26085,
"s": 26012,
"text": "0 0 0 0 0 \n-1 -1 -1 -1 -1 \n84215045 84215045 84215045 84215045 84215045 "
},
{
"code": null,
"e": 26095,
"s": 26085,
"text": "See Also:"
},
{
"code": null,
"e": 26113,
"s": 26095,
"text": "memcpy() in C/C++"
},
{
"code": null,
"e": 26129,
"s": 26113,
"text": "memcmp() in C++"
},
{
"code": null,
"e": 26546,
"s": 26129,
"text": "This article is contributed by Pranav. 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": 26562,
"s": 26546,
"text": "balajimarisetti"
},
{
"code": null,
"e": 26576,
"s": 26562,
"text": "anshikajain26"
},
{
"code": null,
"e": 26596,
"s": 26576,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 26600,
"s": 26596,
"text": "STL"
},
{
"code": null,
"e": 26604,
"s": 26600,
"text": "C++"
},
{
"code": null,
"e": 26608,
"s": 26604,
"text": "STL"
},
{
"code": null,
"e": 26612,
"s": 26608,
"text": "CPP"
},
{
"code": null,
"e": 26710,
"s": 26612,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26719,
"s": 26710,
"text": "Comments"
},
{
"code": null,
"e": 26732,
"s": 26719,
"text": "Old Comments"
},
{
"code": null,
"e": 26751,
"s": 26732,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26794,
"s": 26751,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26822,
"s": 26794,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26850,
"s": 26822,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26874,
"s": 26850,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26901,
"s": 26874,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 26925,
"s": 26901,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 26945,
"s": 26925,
"text": "Constructors in C++"
},
{
"code": null,
"e": 26966,
"s": 26945,
"text": "Iterators in C++ STL"
}
] |
Analysis of time and space complexity of C++ STL containers - GeeksforGeeks | 04 Apr, 2022
In this article, we will discuss the time and space complexity of some C++ STL classes.
Characteristics of C++ STL:
C++ has a low execution time as compared to other programming languages.
This makes STL in C++ advantageous and powerful.
The thing that makes STL powerful is that it contains a vast variety of classes that are implementations of popular and standard algorithms and predefined classes with functions that makes them well-optimized while doing competitive programming or problem-solving questions.
Analysis of functions in STL:
The major thing required while using the STL is the analysis of STL.
Analysis of the problem can’t be done without knowing the complexity analysis of the STL class used in the problem.
Implementation and complexity analysis of STL is required to answer the asked interview questions.
Below is the analysis of some STL Containers:
Priority Queue is used in many popular algorithms . Priority Queue is the implementation of Max Heap by default. Priority Queue does even optimize some major operations.
Syntax:
priority_queue<data_type> Q
The Min Heap can also be implemented by using the following syntax.Syntax:
priority_queue<data_type, vector<data_type>, greater<data_type>> Q
The table containing the time and space complexity with different functions given below:
O(1)
O(1)
O(log n)
O(1)
O(log n)
O(1)
O(1)
O(1)
Below is the C++ program illustrating the priority queue:
C++
// C++ program illustrating the// priority queue#include <bits/stdc++.h>using namespace std; // Function illustrating the// priority queuevoid priorityQueue(){ int Array[5] = { 1, 2, 3, 4, 5 }; // Max heap int i; priority_queue<int> Q; for (i = 0; i < 5; i++) { // Pushes array elements to // priority queue and rearranges // to form max heap; Q.push(Array[i]); } // Maximum element in the priority // queue. cout << "The maximum element is " << Q.top() << endl; i = 1; while (Q.empty() != 1) { int peek = Q.top(); cout << "The " << i++ << " th max element is " << peek << endl; // Pops the maximum element // out of priority queue Q.pop(); } cout << " Is priority queue " << "Q empty() ?" << endl << "check -->" << endl; // Checks whether priority // queue is empty if (Q.empty() == 1) cout << "The priority queue" << " is empty" << endl; else cout << "The priority queue" << " is not empty." << endl;} // Driver Codeint main(){ // Function Call priorityQueue(); return 0;}
The maximum element is 5
The 1 th max element is 5
The 2 th max element is 4
The 3 th max element is 3
The 4 th max element is 2
The 5 th max element is 1
Is priority queue Q empty() ?
check -->
The priority queue is empty
It is the famous class of STL that stores the values in the pattern of key-value pair.
It maps the value using the key value, and no same keys will have a different value.
It can be modified to multimap to make it work for the same keys with different values.
The map can be even used for keys and values of different data types.
Syntax:
map<data_type, data_type> M
The map <int, int> M is the implementation of self-balancing Red-Black Trees.
The unordered_map<int, int> M is the implementation of Hash Table which makes the complexity of operations like insert, delete and search to Theta(1).
The multimap<int, int> M is the implementation of Red-Black Trees which are self-balancing trees making the cost of operations the same as the map.
The unordered_multimap<int, int> M is the implemented same as the unordered map is implemented which is the Hash Table.
The only difference is it keeps track of one more variable which keeps track of the count of occurrences.
The pairs are inserted into the map using pair<int, int>(x, y) and can be accessed using the map iterator.first and map iterator.second.
The map by default keeps sorted based on keys and in the case of the unordered map, it can be in any order.
The table containing the time and space complexity with different functions given below(n is the size of the map):
O(log n)
O(1)
O(log n)
O(1)
O(log n)
O(1)
O(1)
O(1)
Theta(n)
O(1)
O(1)
O(1)
Below is the C++ program illustrating map:
C++
// C++ program illustrating the map #include <bits/stdc++.h>using namespace std; // Function illustrating the mapvoid Map(){ int i; // Declaring maps map<int, int> M; unordered_map<int, int> UM; multimap<int, int> MM; unordered_multimap<int, int> UMM; // Inserting pairs of key // and value for (i = 101; i <= 105; i++) { // Inserted the Key and // value twice M.insert( pair<int, int>(i - 100, i)); UM.insert( pair<int, int>(i - 100, i)); M.insert( pair<int, int>(i - 100, i)); UM.insert( pair<int, int>(i - 100, i)); } for (i = 101; i <= 105; i++) { // Inserted the key and // value twice MM.insert( pair<int, int>(i - 100, i)); UMM.insert( pair<int, int>(i - 100, i)); MM.insert( pair<int, int>(i - 100, i)); UMM.insert( pair<int, int>(i - 100, i)); } // Iterators for accessing map<int, int>::iterator Mitr; unordered_map<int, int>::iterator UMitr; multimap<int, int>::iterator MMitr; unordered_multimap<int, int>::iterator UMMitr; // Output cout << "In map" << endl; cout << "Key" << " " << "Value" << endl; for (Mitr = M.begin(); Mitr != M.end(); Mitr++) { cout << Mitr->first << " " << Mitr->second << endl; } // Unsorted and is unordered output cout << "In unordered_map" << endl; cout << "Key" << " " << "Value" << endl; for (UMitr = UM.begin(); UMitr != UM.end(); UMitr++) { cout << UMitr->first << " " << UMitr->second << endl; } // Sorted output cout << "In multimap" << endl; cout << "Key" << " " << "Value" << endl; for (MMitr = MM.begin(); MMitr != MM.end(); MMitr++) { cout << MMitr->first << " " << MMitr->second << endl; } // Unsorted and is unordered // output cout << "In unordered_multimap" << endl; cout << "Key" << " " << "Value" << endl; for (UMMitr = UMM.begin(); UMMitr != UMM.end(); UMMitr++) { cout << UMMitr->first << " " << UMMitr->second << endl; } cout << "The erase() function" << " erases respective key:" << endl; M.erase(1); cout << "Key" << " " << "Value" << endl; for (Mitr = M.begin(); Mitr != M.end(); Mitr++) { cout << Mitr->first << " " << Mitr->second << endl; } cout << "The find() function" << " finds the respective key:" << endl; if (M.find(1) != M.end()) { cout << "Found!" << endl; } else { cout << "Not Found!" << endl; } cout << "The clear() function " << "clears the map:" << endl; M.clear(); // Returns the size of the map cout << "Now the size is :" << M.size();} // Driver Codeint main(){ // Function Call Map(); return 0;}
In map
Key Value
1 101
2 102
3 103
4 104
5 105
In unordered_map
Key Value
5 105
4 104
3 103
1 101
2 102
In multimap
Key Value
1 101
1 101
2 102
2 102
3 103
3 103
4 104
4 104
5 105
5 105
In unoredered_multimap
Key Value
5 105
5 105
4 104
4 104
1 101
1 101
2 102
2 102
3 103
3 103
The erase() function erases respective key:
Key Value
2 102
3 103
4 104
5 105
The find() function finds the respective key:
Not Found!
The clear() function clears the map:
Now the size is :0
Explanation:
m.begin(): points the iterator to starting element.
m.end(): points the iterator to the element after the last which is theoretical.
The first useful property of the set is that it contains only distinct elements of course the variation multiset can even contain repeated elements.
Set contains the distinct elements in an ordered manner whereas unordered set contains distinct elements in an unsorted order and multimaps contain repeated elements.
Syntax:
set<data_type> S
Set (set<int> s) is the implementation of Binary Search Trees.
Unordered set (unordered_set<int> S) is the implementation of Hash Table.
Multiset (multiset<int> S) is implementation of Red-Black trees.
Unordered_multiset(unordered_multiset<int> S) is implemented the same as the unordered set but uses an extra variable that keeps track of the count.
The complexity becomes Theta(1) and O(n) when using unordered<set> the ease of access becomes easier due to Hash Table implementation.
The table containing the time and space complexity with different functions given below(n is the size of the set):
O(log n)
O(1)
O(log n)
O(1)
O(log n)
O(1)
O(1)
O(1)
O(1)
O(1)
Below is the C++ program illustrating set:
C++
// C++ program illustrating the set#include <bits/stdc++.h>using namespace std; // Function illustrating the setvoid Set(){ // Set declaration set<int> s; unordered_set<int> us; multiset<int> ms; unordered_multiset<int> ums; int i; for (i = 1; i <= 5; i++) { // Inserting elements s.insert(2 * i + 1); us.insert(2 * i + 1); ms.insert(2 * i + 1); ums.insert(2 * i + 1); s.insert(2 * i + 1); us.insert(2 * i + 1); ms.insert(2 * i + 1); ums.insert(2 * i + 1); } // Iterator to access values // in set set<int>::iterator sitr; unordered_set<int>::iterator uitr; multiset<int>::iterator mitr; unordered_multiset<int>::iterator umitr; cout << "The difference: " << endl; cout << "The output for set " << endl; for (sitr = s.begin(); sitr != s.end(); sitr++) { cout << *sitr << " "; } cout << endl; cout << "The output for " << "unordered set " << endl; for (uitr = us.begin(); uitr != us.end(); uitr++) { cout << *uitr << " "; } cout << endl; cout << "The output for " << "multiset " << endl; for (mitr = ms.begin(); mitr != ms.end(); mitr++) { cout << *mitr << " "; } cout << endl; cout << "The output for " << "unordered multiset " << endl; for (umitr = ums.begin(); umitr != ums.end(); umitr++) { cout << *umitr << " "; } cout << endl;} // Driver Codeint main(){ // Function Call Set(); return 0;}
The difference:
The output for set
3 5 7 9 11
The output for unordered set
11 9 7 3 5
The output for multiset
3 3 5 5 7 7 9 9 11 11
The output for unordered multiset
11 11 9 9 3 3 5 5 7 7
It is a data structure that follows the Last In First Out (LIFO) rule, this class of STL is alsoused in many algorithms during their implementations. For e.g, many recursive solutions use a system stack to backtrack the pending calls of recursive functions the same can be implemented using the STL stack iteratively.
Syntax:
stack<data_type> A
It is implemented using the linked list implementation of a stack.
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
Below is the C++ program illustrating stack:
C++
// C++ program illustrating the stack#include <bits/stdc++.h>using namespace std; // Function illustrating stackvoid Stack(){ stack<int> s; int i; for (i = 0; i <= 5; i++) { cout << "The pushed element" << " is " << i << endl; s.push(i); } // Points to top element of stack cout << "The top element of the" << " stack is: " << s.top() << endl; // Return size of stack cout << "The size of the stack" << " is: " << s.size() << endl; // Pops the elements of the // stack in the LIFO manner // Checks whether the stack // is empty or not while (s.empty() != 1) { cout << "The popped element" << " is " << s.top() << endl; s.pop(); }} // Driver Codeint main(){ // Function Call Stack(); return 0;}
The pushed element is 0
The pushed element is 1
The pushed element is 2
The pushed element is 3
The pushed element is 4
The pushed element is 5
The top element of the stack is: 5
The size of the stack is: 6
The popped element is 5
The popped element is 4
The popped element is 3
The popped element is 2
The popped element is 1
The popped element is 0
It is a data structure that follows the First In First Out (FIFO) rule.
The inclusion of queue STL class queue in code reduces the function calls for basic operations.
The queue is often used in BFS traversals of trees and graphs and also many popular algorithms.
Queue in STL is implemented using a linked list.
Syntax:
queue<data_type> Q
Table containing the time and space complexity with different functions given below:
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
Below is the C++ program illustrating queue:
C++
// C++ program illustrating the queue#include <bits/stdc++.h>using namespace std; // Function illustrating queuevoid Queue(){ queue<int> q; int i; for (i = 101; i <= 105; i++) { // Inserts into the queue // in the FIFO manner q.push(i); cout << "The first and last" << " elements of the queue " << "are " << q.front() << " " << q.back() << endl; } // Check whether the queue is // empty or not while (q.empty() != 1) { // Pops the first element // of the queue cout << "The Element popped" << " following FIFO is " << q.front() << endl; q.pop(); }} // Driver Codeint main(){ // Function Call Queue(); return 0;}
The first and last elements of the queue are 101 101
The first and last elements of the queue are 101 102
The first and last elements of the queue are 101 103
The first and last elements of the queue are 101 104
The first and last elements of the queue are 101 105
The Element popped following FIFO is 101
The Element popped following FIFO is 102
The Element popped following FIFO is 103
The Element popped following FIFO is 104
The Element popped following FIFO is 105
Vector is the implementation of dynamic arrays and uses new for memory allocation in heap.Syntax:
vector<int> A
2-dimensional vectors can also be implemented using the below syntax:
Syntax:
vector<vector<int>> A
The table containing the time and space complexity with different functions given below:
Theta(log n)
O(n)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(1)
O(n)
O(1)
O(n)
O(1)
Below is the C++ program illustrating vector:
C++
// C++ program illustrating vector #include <bits/stdc++.h>using namespace std; // Function displaying valuesvoid display(vector<int> v){ for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; }} // Function illustrating vectorvoid Vector(){ int i; vector<int> v; for (i = 100; i < 106; i++) { // Inserts an element in vector v.push_back(i); } cout << "The vector after " << "push_back is :" << v.size() << endl; cout << "The vector now is :"; display(v); cout << endl; // Deletes an element at the back v.pop_back(); cout << "The vector after " << "pop_back is :" << v.size() << endl; cout << "The vector now is :"; display(v); cout << endl; // Reverses the vector reverse(v.begin(), v.end()); cout << "The vector after " << "reversing is :" << v.size() << endl; cout << "The vector now is :"; display(v); cout << endl; // Sorts vector using Quick Sort sort(v.begin(), v.end()); cout << "The vector after " << "sorting is :" << v.size() << endl; cout << "The vector now is :"; display(v); cout << endl; // Erases ith position element v.erase(v.begin() + 2); cout << "The size of vector " << "after erasing at position " "3 is :" << v.size() << endl; cout << "The vector now is :"; display(v); cout << endl; // Deletes the vector completely v.clear(); cout << "The size of the vector" << " after clearing is :" << v.size() << endl; cout << "The vector now is :"; display(v); cout << endl;} // Driver Codeint main(){ // Function Call Vector(); return 0;}
The vector after push_back is :6
The vector now is :100 101 102 103 104 105
The vector after pop_back is :5
The vector now is :100 101 102 103 104
The vector after reversing is :5
The vector now is :104 103 102 101 100
The vector after sorting is :5
The vector now is :100 101 102 103 104
The size of vector after erasing at position 3 is :4
The vector now is :100 101 103 104
The size of the vector after clearing is :0
The vector now is :
lokeshpotta20
ahmedabdalmola2017
madhav_mohan
saurabh1990aror
STL
Technical Scripter 2020
Technical Scripter
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 24622,
"s": 24594,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 24710,
"s": 24622,
"text": "In this article, we will discuss the time and space complexity of some C++ STL classes."
},
{
"code": null,
"e": 24738,
"s": 24710,
"text": "Characteristics of C++ STL:"
},
{
"code": null,
"e": 24811,
"s": 24738,
"text": "C++ has a low execution time as compared to other programming languages."
},
{
"code": null,
"e": 24860,
"s": 24811,
"text": "This makes STL in C++ advantageous and powerful."
},
{
"code": null,
"e": 25135,
"s": 24860,
"text": "The thing that makes STL powerful is that it contains a vast variety of classes that are implementations of popular and standard algorithms and predefined classes with functions that makes them well-optimized while doing competitive programming or problem-solving questions."
},
{
"code": null,
"e": 25165,
"s": 25135,
"text": "Analysis of functions in STL:"
},
{
"code": null,
"e": 25234,
"s": 25165,
"text": "The major thing required while using the STL is the analysis of STL."
},
{
"code": null,
"e": 25350,
"s": 25234,
"text": "Analysis of the problem can’t be done without knowing the complexity analysis of the STL class used in the problem."
},
{
"code": null,
"e": 25449,
"s": 25350,
"text": "Implementation and complexity analysis of STL is required to answer the asked interview questions."
},
{
"code": null,
"e": 25495,
"s": 25449,
"text": "Below is the analysis of some STL Containers:"
},
{
"code": null,
"e": 25665,
"s": 25495,
"text": "Priority Queue is used in many popular algorithms . Priority Queue is the implementation of Max Heap by default. Priority Queue does even optimize some major operations."
},
{
"code": null,
"e": 25673,
"s": 25665,
"text": "Syntax:"
},
{
"code": null,
"e": 25701,
"s": 25673,
"text": "priority_queue<data_type> Q"
},
{
"code": null,
"e": 25776,
"s": 25701,
"text": "The Min Heap can also be implemented by using the following syntax.Syntax:"
},
{
"code": null,
"e": 25843,
"s": 25776,
"text": "priority_queue<data_type, vector<data_type>, greater<data_type>> Q"
},
{
"code": null,
"e": 25932,
"s": 25843,
"text": "The table containing the time and space complexity with different functions given below:"
},
{
"code": null,
"e": 25937,
"s": 25932,
"text": "O(1)"
},
{
"code": null,
"e": 25942,
"s": 25937,
"text": "O(1)"
},
{
"code": null,
"e": 25951,
"s": 25942,
"text": "O(log n)"
},
{
"code": null,
"e": 25956,
"s": 25951,
"text": "O(1)"
},
{
"code": null,
"e": 25965,
"s": 25956,
"text": "O(log n)"
},
{
"code": null,
"e": 25970,
"s": 25965,
"text": "O(1)"
},
{
"code": null,
"e": 25975,
"s": 25970,
"text": "O(1)"
},
{
"code": null,
"e": 25980,
"s": 25975,
"text": "O(1)"
},
{
"code": null,
"e": 26038,
"s": 25980,
"text": "Below is the C++ program illustrating the priority queue:"
},
{
"code": null,
"e": 26042,
"s": 26038,
"text": "C++"
},
{
"code": "// C++ program illustrating the// priority queue#include <bits/stdc++.h>using namespace std; // Function illustrating the// priority queuevoid priorityQueue(){ int Array[5] = { 1, 2, 3, 4, 5 }; // Max heap int i; priority_queue<int> Q; for (i = 0; i < 5; i++) { // Pushes array elements to // priority queue and rearranges // to form max heap; Q.push(Array[i]); } // Maximum element in the priority // queue. cout << \"The maximum element is \" << Q.top() << endl; i = 1; while (Q.empty() != 1) { int peek = Q.top(); cout << \"The \" << i++ << \" th max element is \" << peek << endl; // Pops the maximum element // out of priority queue Q.pop(); } cout << \" Is priority queue \" << \"Q empty() ?\" << endl << \"check -->\" << endl; // Checks whether priority // queue is empty if (Q.empty() == 1) cout << \"The priority queue\" << \" is empty\" << endl; else cout << \"The priority queue\" << \" is not empty.\" << endl;} // Driver Codeint main(){ // Function Call priorityQueue(); return 0;}",
"e": 27236,
"s": 26042,
"text": null
},
{
"code": null,
"e": 27460,
"s": 27236,
"text": "The maximum element is 5\nThe 1 th max element is 5\nThe 2 th max element is 4\nThe 3 th max element is 3\nThe 4 th max element is 2\nThe 5 th max element is 1\n Is priority queue Q empty() ?\ncheck -->\nThe priority queue is empty"
},
{
"code": null,
"e": 27550,
"s": 27462,
"text": "It is the famous class of STL that stores the values in the pattern of key-value pair. "
},
{
"code": null,
"e": 27635,
"s": 27550,
"text": "It maps the value using the key value, and no same keys will have a different value."
},
{
"code": null,
"e": 27723,
"s": 27635,
"text": "It can be modified to multimap to make it work for the same keys with different values."
},
{
"code": null,
"e": 27793,
"s": 27723,
"text": "The map can be even used for keys and values of different data types."
},
{
"code": null,
"e": 27801,
"s": 27793,
"text": "Syntax:"
},
{
"code": null,
"e": 27829,
"s": 27801,
"text": "map<data_type, data_type> M"
},
{
"code": null,
"e": 27907,
"s": 27829,
"text": "The map <int, int> M is the implementation of self-balancing Red-Black Trees."
},
{
"code": null,
"e": 28058,
"s": 27907,
"text": "The unordered_map<int, int> M is the implementation of Hash Table which makes the complexity of operations like insert, delete and search to Theta(1)."
},
{
"code": null,
"e": 28206,
"s": 28058,
"text": "The multimap<int, int> M is the implementation of Red-Black Trees which are self-balancing trees making the cost of operations the same as the map."
},
{
"code": null,
"e": 28326,
"s": 28206,
"text": "The unordered_multimap<int, int> M is the implemented same as the unordered map is implemented which is the Hash Table."
},
{
"code": null,
"e": 28432,
"s": 28326,
"text": "The only difference is it keeps track of one more variable which keeps track of the count of occurrences."
},
{
"code": null,
"e": 28569,
"s": 28432,
"text": "The pairs are inserted into the map using pair<int, int>(x, y) and can be accessed using the map iterator.first and map iterator.second."
},
{
"code": null,
"e": 28677,
"s": 28569,
"text": "The map by default keeps sorted based on keys and in the case of the unordered map, it can be in any order."
},
{
"code": null,
"e": 28792,
"s": 28677,
"text": "The table containing the time and space complexity with different functions given below(n is the size of the map):"
},
{
"code": null,
"e": 28801,
"s": 28792,
"text": "O(log n)"
},
{
"code": null,
"e": 28806,
"s": 28801,
"text": "O(1)"
},
{
"code": null,
"e": 28815,
"s": 28806,
"text": "O(log n)"
},
{
"code": null,
"e": 28820,
"s": 28815,
"text": "O(1)"
},
{
"code": null,
"e": 28829,
"s": 28820,
"text": "O(log n)"
},
{
"code": null,
"e": 28834,
"s": 28829,
"text": "O(1)"
},
{
"code": null,
"e": 28839,
"s": 28834,
"text": "O(1)"
},
{
"code": null,
"e": 28844,
"s": 28839,
"text": "O(1)"
},
{
"code": null,
"e": 28853,
"s": 28844,
"text": "Theta(n)"
},
{
"code": null,
"e": 28858,
"s": 28853,
"text": "O(1)"
},
{
"code": null,
"e": 28863,
"s": 28858,
"text": "O(1)"
},
{
"code": null,
"e": 28868,
"s": 28863,
"text": "O(1)"
},
{
"code": null,
"e": 28911,
"s": 28868,
"text": "Below is the C++ program illustrating map:"
},
{
"code": null,
"e": 28915,
"s": 28911,
"text": "C++"
},
{
"code": "// C++ program illustrating the map #include <bits/stdc++.h>using namespace std; // Function illustrating the mapvoid Map(){ int i; // Declaring maps map<int, int> M; unordered_map<int, int> UM; multimap<int, int> MM; unordered_multimap<int, int> UMM; // Inserting pairs of key // and value for (i = 101; i <= 105; i++) { // Inserted the Key and // value twice M.insert( pair<int, int>(i - 100, i)); UM.insert( pair<int, int>(i - 100, i)); M.insert( pair<int, int>(i - 100, i)); UM.insert( pair<int, int>(i - 100, i)); } for (i = 101; i <= 105; i++) { // Inserted the key and // value twice MM.insert( pair<int, int>(i - 100, i)); UMM.insert( pair<int, int>(i - 100, i)); MM.insert( pair<int, int>(i - 100, i)); UMM.insert( pair<int, int>(i - 100, i)); } // Iterators for accessing map<int, int>::iterator Mitr; unordered_map<int, int>::iterator UMitr; multimap<int, int>::iterator MMitr; unordered_multimap<int, int>::iterator UMMitr; // Output cout << \"In map\" << endl; cout << \"Key\" << \" \" << \"Value\" << endl; for (Mitr = M.begin(); Mitr != M.end(); Mitr++) { cout << Mitr->first << \" \" << Mitr->second << endl; } // Unsorted and is unordered output cout << \"In unordered_map\" << endl; cout << \"Key\" << \" \" << \"Value\" << endl; for (UMitr = UM.begin(); UMitr != UM.end(); UMitr++) { cout << UMitr->first << \" \" << UMitr->second << endl; } // Sorted output cout << \"In multimap\" << endl; cout << \"Key\" << \" \" << \"Value\" << endl; for (MMitr = MM.begin(); MMitr != MM.end(); MMitr++) { cout << MMitr->first << \" \" << MMitr->second << endl; } // Unsorted and is unordered // output cout << \"In unordered_multimap\" << endl; cout << \"Key\" << \" \" << \"Value\" << endl; for (UMMitr = UMM.begin(); UMMitr != UMM.end(); UMMitr++) { cout << UMMitr->first << \" \" << UMMitr->second << endl; } cout << \"The erase() function\" << \" erases respective key:\" << endl; M.erase(1); cout << \"Key\" << \" \" << \"Value\" << endl; for (Mitr = M.begin(); Mitr != M.end(); Mitr++) { cout << Mitr->first << \" \" << Mitr->second << endl; } cout << \"The find() function\" << \" finds the respective key:\" << endl; if (M.find(1) != M.end()) { cout << \"Found!\" << endl; } else { cout << \"Not Found!\" << endl; } cout << \"The clear() function \" << \"clears the map:\" << endl; M.clear(); // Returns the size of the map cout << \"Now the size is :\" << M.size();} // Driver Codeint main(){ // Function Call Map(); return 0;}",
"e": 32061,
"s": 28915,
"text": null
},
{
"code": null,
"e": 32599,
"s": 32061,
"text": "In map\nKey Value\n1 101\n2 102\n3 103\n4 104\n5 105\nIn unordered_map\nKey Value\n5 105\n4 104\n3 103\n1 101\n2 102\nIn multimap\nKey Value\n1 101\n1 101\n2 102\n2 102\n3 103\n3 103\n4 104\n4 104\n5 105\n5 105\nIn unoredered_multimap\nKey Value\n5 105\n5 105\n4 104\n4 104\n1 101\n1 101\n2 102\n2 102\n3 103\n3 103\nThe erase() function erases respective key:\nKey Value\n2 102\n3 103\n4 104\n5 105\nThe find() function finds the respective key:\nNot Found!\nThe clear() function clears the map:\nNow the size is :0"
},
{
"code": null,
"e": 32614,
"s": 32601,
"text": "Explanation:"
},
{
"code": null,
"e": 32666,
"s": 32614,
"text": "m.begin(): points the iterator to starting element."
},
{
"code": null,
"e": 32747,
"s": 32666,
"text": "m.end(): points the iterator to the element after the last which is theoretical."
},
{
"code": null,
"e": 32896,
"s": 32747,
"text": "The first useful property of the set is that it contains only distinct elements of course the variation multiset can even contain repeated elements."
},
{
"code": null,
"e": 33063,
"s": 32896,
"text": "Set contains the distinct elements in an ordered manner whereas unordered set contains distinct elements in an unsorted order and multimaps contain repeated elements."
},
{
"code": null,
"e": 33071,
"s": 33063,
"text": "Syntax:"
},
{
"code": null,
"e": 33088,
"s": 33071,
"text": "set<data_type> S"
},
{
"code": null,
"e": 33151,
"s": 33088,
"text": "Set (set<int> s) is the implementation of Binary Search Trees."
},
{
"code": null,
"e": 33225,
"s": 33151,
"text": "Unordered set (unordered_set<int> S) is the implementation of Hash Table."
},
{
"code": null,
"e": 33290,
"s": 33225,
"text": "Multiset (multiset<int> S) is implementation of Red-Black trees."
},
{
"code": null,
"e": 33439,
"s": 33290,
"text": "Unordered_multiset(unordered_multiset<int> S) is implemented the same as the unordered set but uses an extra variable that keeps track of the count."
},
{
"code": null,
"e": 33574,
"s": 33439,
"text": "The complexity becomes Theta(1) and O(n) when using unordered<set> the ease of access becomes easier due to Hash Table implementation."
},
{
"code": null,
"e": 33689,
"s": 33574,
"text": "The table containing the time and space complexity with different functions given below(n is the size of the set):"
},
{
"code": null,
"e": 33698,
"s": 33689,
"text": "O(log n)"
},
{
"code": null,
"e": 33703,
"s": 33698,
"text": "O(1)"
},
{
"code": null,
"e": 33712,
"s": 33703,
"text": "O(log n)"
},
{
"code": null,
"e": 33717,
"s": 33712,
"text": "O(1)"
},
{
"code": null,
"e": 33726,
"s": 33717,
"text": "O(log n)"
},
{
"code": null,
"e": 33731,
"s": 33726,
"text": "O(1)"
},
{
"code": null,
"e": 33736,
"s": 33731,
"text": "O(1)"
},
{
"code": null,
"e": 33741,
"s": 33736,
"text": "O(1)"
},
{
"code": null,
"e": 33746,
"s": 33741,
"text": "O(1)"
},
{
"code": null,
"e": 33751,
"s": 33746,
"text": "O(1)"
},
{
"code": null,
"e": 33795,
"s": 33751,
"text": " Below is the C++ program illustrating set:"
},
{
"code": null,
"e": 33799,
"s": 33795,
"text": "C++"
},
{
"code": "// C++ program illustrating the set#include <bits/stdc++.h>using namespace std; // Function illustrating the setvoid Set(){ // Set declaration set<int> s; unordered_set<int> us; multiset<int> ms; unordered_multiset<int> ums; int i; for (i = 1; i <= 5; i++) { // Inserting elements s.insert(2 * i + 1); us.insert(2 * i + 1); ms.insert(2 * i + 1); ums.insert(2 * i + 1); s.insert(2 * i + 1); us.insert(2 * i + 1); ms.insert(2 * i + 1); ums.insert(2 * i + 1); } // Iterator to access values // in set set<int>::iterator sitr; unordered_set<int>::iterator uitr; multiset<int>::iterator mitr; unordered_multiset<int>::iterator umitr; cout << \"The difference: \" << endl; cout << \"The output for set \" << endl; for (sitr = s.begin(); sitr != s.end(); sitr++) { cout << *sitr << \" \"; } cout << endl; cout << \"The output for \" << \"unordered set \" << endl; for (uitr = us.begin(); uitr != us.end(); uitr++) { cout << *uitr << \" \"; } cout << endl; cout << \"The output for \" << \"multiset \" << endl; for (mitr = ms.begin(); mitr != ms.end(); mitr++) { cout << *mitr << \" \"; } cout << endl; cout << \"The output for \" << \"unordered multiset \" << endl; for (umitr = ums.begin(); umitr != ums.end(); umitr++) { cout << *umitr << \" \"; } cout << endl;} // Driver Codeint main(){ // Function Call Set(); return 0;}",
"e": 35395,
"s": 33799,
"text": null
},
{
"code": null,
"e": 35591,
"s": 35395,
"text": "The difference: \nThe output for set \n3 5 7 9 11 \nThe output for unordered set \n11 9 7 3 5 \nThe output for multiset \n3 3 5 5 7 7 9 9 11 11 \nThe output for unordered multiset \n11 11 9 9 3 3 5 5 7 7"
},
{
"code": null,
"e": 35911,
"s": 35593,
"text": "It is a data structure that follows the Last In First Out (LIFO) rule, this class of STL is alsoused in many algorithms during their implementations. For e.g, many recursive solutions use a system stack to backtrack the pending calls of recursive functions the same can be implemented using the STL stack iteratively."
},
{
"code": null,
"e": 35919,
"s": 35911,
"text": "Syntax:"
},
{
"code": null,
"e": 35938,
"s": 35919,
"text": "stack<data_type> A"
},
{
"code": null,
"e": 36005,
"s": 35938,
"text": "It is implemented using the linked list implementation of a stack."
},
{
"code": null,
"e": 36010,
"s": 36005,
"text": "O(1)"
},
{
"code": null,
"e": 36015,
"s": 36010,
"text": "O(1)"
},
{
"code": null,
"e": 36020,
"s": 36015,
"text": "O(1)"
},
{
"code": null,
"e": 36025,
"s": 36020,
"text": "O(1)"
},
{
"code": null,
"e": 36030,
"s": 36025,
"text": "O(1)"
},
{
"code": null,
"e": 36035,
"s": 36030,
"text": "O(1)"
},
{
"code": null,
"e": 36040,
"s": 36035,
"text": "O(1)"
},
{
"code": null,
"e": 36045,
"s": 36040,
"text": "O(1)"
},
{
"code": null,
"e": 36090,
"s": 36045,
"text": "Below is the C++ program illustrating stack:"
},
{
"code": null,
"e": 36094,
"s": 36090,
"text": "C++"
},
{
"code": "// C++ program illustrating the stack#include <bits/stdc++.h>using namespace std; // Function illustrating stackvoid Stack(){ stack<int> s; int i; for (i = 0; i <= 5; i++) { cout << \"The pushed element\" << \" is \" << i << endl; s.push(i); } // Points to top element of stack cout << \"The top element of the\" << \" stack is: \" << s.top() << endl; // Return size of stack cout << \"The size of the stack\" << \" is: \" << s.size() << endl; // Pops the elements of the // stack in the LIFO manner // Checks whether the stack // is empty or not while (s.empty() != 1) { cout << \"The popped element\" << \" is \" << s.top() << endl; s.pop(); }} // Driver Codeint main(){ // Function Call Stack(); return 0;}",
"e": 36939,
"s": 36094,
"text": null
},
{
"code": null,
"e": 37290,
"s": 36939,
"text": "The pushed element is 0\nThe pushed element is 1\nThe pushed element is 2\nThe pushed element is 3\nThe pushed element is 4\nThe pushed element is 5\nThe top element of the stack is: 5\nThe size of the stack is: 6\nThe popped element is 5\nThe popped element is 4\nThe popped element is 3\nThe popped element is 2\nThe popped element is 1\nThe popped element is 0"
},
{
"code": null,
"e": 37364,
"s": 37292,
"text": "It is a data structure that follows the First In First Out (FIFO) rule."
},
{
"code": null,
"e": 37460,
"s": 37364,
"text": "The inclusion of queue STL class queue in code reduces the function calls for basic operations."
},
{
"code": null,
"e": 37557,
"s": 37460,
"text": "The queue is often used in BFS traversals of trees and graphs and also many popular algorithms. "
},
{
"code": null,
"e": 37607,
"s": 37557,
"text": "Queue in STL is implemented using a linked list. "
},
{
"code": null,
"e": 37615,
"s": 37607,
"text": "Syntax:"
},
{
"code": null,
"e": 37634,
"s": 37615,
"text": "queue<data_type> Q"
},
{
"code": null,
"e": 37719,
"s": 37634,
"text": "Table containing the time and space complexity with different functions given below:"
},
{
"code": null,
"e": 37724,
"s": 37719,
"text": "O(1)"
},
{
"code": null,
"e": 37729,
"s": 37724,
"text": "O(1)"
},
{
"code": null,
"e": 37734,
"s": 37729,
"text": "O(1)"
},
{
"code": null,
"e": 37739,
"s": 37734,
"text": "O(1)"
},
{
"code": null,
"e": 37744,
"s": 37739,
"text": "O(1)"
},
{
"code": null,
"e": 37749,
"s": 37744,
"text": "O(1)"
},
{
"code": null,
"e": 37754,
"s": 37749,
"text": "O(1)"
},
{
"code": null,
"e": 37759,
"s": 37754,
"text": "O(1)"
},
{
"code": null,
"e": 37764,
"s": 37759,
"text": "O(1)"
},
{
"code": null,
"e": 37769,
"s": 37764,
"text": "O(1)"
},
{
"code": null,
"e": 37774,
"s": 37769,
"text": "O(1)"
},
{
"code": null,
"e": 37779,
"s": 37774,
"text": "O(1)"
},
{
"code": null,
"e": 37824,
"s": 37779,
"text": "Below is the C++ program illustrating queue:"
},
{
"code": null,
"e": 37828,
"s": 37824,
"text": "C++"
},
{
"code": "// C++ program illustrating the queue#include <bits/stdc++.h>using namespace std; // Function illustrating queuevoid Queue(){ queue<int> q; int i; for (i = 101; i <= 105; i++) { // Inserts into the queue // in the FIFO manner q.push(i); cout << \"The first and last\" << \" elements of the queue \" << \"are \" << q.front() << \" \" << q.back() << endl; } // Check whether the queue is // empty or not while (q.empty() != 1) { // Pops the first element // of the queue cout << \"The Element popped\" << \" following FIFO is \" << q.front() << endl; q.pop(); }} // Driver Codeint main(){ // Function Call Queue(); return 0;}",
"e": 38606,
"s": 37828,
"text": null
},
{
"code": null,
"e": 39076,
"s": 38606,
"text": "The first and last elements of the queue are 101 101\nThe first and last elements of the queue are 101 102\nThe first and last elements of the queue are 101 103\nThe first and last elements of the queue are 101 104\nThe first and last elements of the queue are 101 105\nThe Element popped following FIFO is 101\nThe Element popped following FIFO is 102\nThe Element popped following FIFO is 103\nThe Element popped following FIFO is 104\nThe Element popped following FIFO is 105"
},
{
"code": null,
"e": 39176,
"s": 39078,
"text": "Vector is the implementation of dynamic arrays and uses new for memory allocation in heap.Syntax:"
},
{
"code": null,
"e": 39190,
"s": 39176,
"text": "vector<int> A"
},
{
"code": null,
"e": 39261,
"s": 39190,
"text": " 2-dimensional vectors can also be implemented using the below syntax:"
},
{
"code": null,
"e": 39269,
"s": 39261,
"text": "Syntax:"
},
{
"code": null,
"e": 39291,
"s": 39269,
"text": "vector<vector<int>> A"
},
{
"code": null,
"e": 39380,
"s": 39291,
"text": "The table containing the time and space complexity with different functions given below:"
},
{
"code": null,
"e": 39393,
"s": 39380,
"text": "Theta(log n)"
},
{
"code": null,
"e": 39399,
"s": 39393,
"text": " O(n)"
},
{
"code": null,
"e": 39404,
"s": 39399,
"text": "O(1)"
},
{
"code": null,
"e": 39409,
"s": 39404,
"text": "O(1)"
},
{
"code": null,
"e": 39414,
"s": 39409,
"text": "O(1)"
},
{
"code": null,
"e": 39419,
"s": 39414,
"text": "O(1)"
},
{
"code": null,
"e": 39424,
"s": 39419,
"text": "O(1)"
},
{
"code": null,
"e": 39429,
"s": 39424,
"text": "O(1)"
},
{
"code": null,
"e": 39434,
"s": 39429,
"text": "O(1)"
},
{
"code": null,
"e": 39440,
"s": 39434,
"text": " O(n)"
},
{
"code": null,
"e": 39445,
"s": 39440,
"text": "O(1)"
},
{
"code": null,
"e": 39450,
"s": 39445,
"text": "O(n)"
},
{
"code": null,
"e": 39455,
"s": 39450,
"text": "O(1)"
},
{
"code": null,
"e": 39501,
"s": 39455,
"text": "Below is the C++ program illustrating vector:"
},
{
"code": null,
"e": 39505,
"s": 39501,
"text": "C++"
},
{
"code": "// C++ program illustrating vector #include <bits/stdc++.h>using namespace std; // Function displaying valuesvoid display(vector<int> v){ for (int i = 0; i < v.size(); i++) { cout << v[i] << \" \"; }} // Function illustrating vectorvoid Vector(){ int i; vector<int> v; for (i = 100; i < 106; i++) { // Inserts an element in vector v.push_back(i); } cout << \"The vector after \" << \"push_back is :\" << v.size() << endl; cout << \"The vector now is :\"; display(v); cout << endl; // Deletes an element at the back v.pop_back(); cout << \"The vector after \" << \"pop_back is :\" << v.size() << endl; cout << \"The vector now is :\"; display(v); cout << endl; // Reverses the vector reverse(v.begin(), v.end()); cout << \"The vector after \" << \"reversing is :\" << v.size() << endl; cout << \"The vector now is :\"; display(v); cout << endl; // Sorts vector using Quick Sort sort(v.begin(), v.end()); cout << \"The vector after \" << \"sorting is :\" << v.size() << endl; cout << \"The vector now is :\"; display(v); cout << endl; // Erases ith position element v.erase(v.begin() + 2); cout << \"The size of vector \" << \"after erasing at position \" \"3 is :\" << v.size() << endl; cout << \"The vector now is :\"; display(v); cout << endl; // Deletes the vector completely v.clear(); cout << \"The size of the vector\" << \" after clearing is :\" << v.size() << endl; cout << \"The vector now is :\"; display(v); cout << endl;} // Driver Codeint main(){ // Function Call Vector(); return 0;}",
"e": 41239,
"s": 39505,
"text": null
},
{
"code": null,
"e": 41688,
"s": 41242,
"text": "The vector after push_back is :6\nThe vector now is :100 101 102 103 104 105 \nThe vector after pop_back is :5\nThe vector now is :100 101 102 103 104 \nThe vector after reversing is :5\nThe vector now is :104 103 102 101 100 \nThe vector after sorting is :5\nThe vector now is :100 101 102 103 104 \nThe size of vector after erasing at position 3 is :4\nThe vector now is :100 101 103 104 \nThe size of the vector after clearing is :0\nThe vector now is :"
},
{
"code": null,
"e": 41706,
"s": 41692,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 41725,
"s": 41706,
"text": "ahmedabdalmola2017"
},
{
"code": null,
"e": 41738,
"s": 41725,
"text": "madhav_mohan"
},
{
"code": null,
"e": 41754,
"s": 41738,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 41758,
"s": 41754,
"text": "STL"
},
{
"code": null,
"e": 41782,
"s": 41758,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 41801,
"s": 41782,
"text": "Technical Scripter"
},
{
"code": null,
"e": 41805,
"s": 41801,
"text": "STL"
}
] |
Mapping Java Beans to CSV Using OpenCSV | 09 Dec, 2021
The need to convert Java Beans(Objects) to CSV file arises very commonly and there are many ways to write Bean into CSV file but one of the best ways to map java bean to CSV is by using OpenCSV Library. In OpenCSV there is a class name StatefulBeanToCsvBuilder which helps to convert Java Beans to CSV.
The first task is to add the OpenCSV library into the Project.For maven project,include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path.Mapping JavaBeans to CSVBelow is the step-by-step procedure to map Java Beans to CSV.Create Writer instance for writing data to the CSV file.Writer writer = Files.newBufferedWriter(Paths.get(file_location));Create a List of objects which are needed to be written into the CSV file.Using ColumnPositionMappingStrategy map the columns of Created objects, to Column of csv.This is an optional step. If ColumnPositionMappingStrategy is not used, then object will be written to csv with column name same as attribute name of object.ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Employee.class);
where Employee is the object to be mapped with CSV.
Create object of StatefulBeanToCsv class by calling build method of StatefulBeanToCsvBuilder class after the creation of StatefulBeanToCsvBuilder, with writer object as parameter. According to the requirement the user can also provide:ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
. withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
After creating object of StatefulBeanToCsv class you can add list of object or object to csv file with the help of write method of StatefulBeanToCsv object.beanToCsv.write(Employeelist);
The first task is to add the OpenCSV library into the Project.For maven project,include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path.
For maven project,include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>
For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
You can Download OpenCSV Jar and include in your project class path.
Mapping JavaBeans to CSVBelow is the step-by-step procedure to map Java Beans to CSV.Create Writer instance for writing data to the CSV file.Writer writer = Files.newBufferedWriter(Paths.get(file_location));Create a List of objects which are needed to be written into the CSV file.Using ColumnPositionMappingStrategy map the columns of Created objects, to Column of csv.This is an optional step. If ColumnPositionMappingStrategy is not used, then object will be written to csv with column name same as attribute name of object.ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Employee.class);
where Employee is the object to be mapped with CSV.
Create object of StatefulBeanToCsv class by calling build method of StatefulBeanToCsvBuilder class after the creation of StatefulBeanToCsvBuilder, with writer object as parameter. According to the requirement the user can also provide:ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
. withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
After creating object of StatefulBeanToCsv class you can add list of object or object to csv file with the help of write method of StatefulBeanToCsv object.beanToCsv.write(Employeelist);
Create Writer instance for writing data to the CSV file.Writer writer = Files.newBufferedWriter(Paths.get(file_location));Create a List of objects which are needed to be written into the CSV file.Using ColumnPositionMappingStrategy map the columns of Created objects, to Column of csv.This is an optional step. If ColumnPositionMappingStrategy is not used, then object will be written to csv with column name same as attribute name of object.ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Employee.class);
where Employee is the object to be mapped with CSV.
Create object of StatefulBeanToCsv class by calling build method of StatefulBeanToCsvBuilder class after the creation of StatefulBeanToCsvBuilder, with writer object as parameter. According to the requirement the user can also provide:ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
. withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
After creating object of StatefulBeanToCsv class you can add list of object or object to csv file with the help of write method of StatefulBeanToCsv object.beanToCsv.write(Employeelist);
Create Writer instance for writing data to the CSV file.Writer writer = Files.newBufferedWriter(Paths.get(file_location));
Writer writer = Files.newBufferedWriter(Paths.get(file_location));
Create a List of objects which are needed to be written into the CSV file.
Using ColumnPositionMappingStrategy map the columns of Created objects, to Column of csv.This is an optional step. If ColumnPositionMappingStrategy is not used, then object will be written to csv with column name same as attribute name of object.ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Employee.class);
where Employee is the object to be mapped with CSV.
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Employee.class);
where Employee is the object to be mapped with CSV.
Create object of StatefulBeanToCsv class by calling build method of StatefulBeanToCsvBuilder class after the creation of StatefulBeanToCsvBuilder, with writer object as parameter. According to the requirement the user can also provide:ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
. withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.
Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.
withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
. withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
After creating object of StatefulBeanToCsv class you can add list of object or object to csv file with the help of write method of StatefulBeanToCsv object.beanToCsv.write(Employeelist);
beanToCsv.write(Employeelist);
Example: In this example, we are going to create the list of Employee Object which has attributes like Name, Age, Company, Salary. Then we will generate a CSV file Employees.csv which contains Employee objects.Codes:
Employee.javapublic class Employee { public String Name, Age, Company, Salary; public Employee(String name, String age, String company, String salary) { super(); Name = name; Age = age; Company = company; Salary = salary; } @Override public String toString() { return "Employee [Name=" + Name + ", Age=" + Age + ", Company=" + Company + ", Salary=" + Salary + "]"; }}BeanToCSV.javaimport java.io.FileWriter;import java.io.Writer;import java.nio.*;import java.nio.file.Files;import java.nio.file.Paths;import java.util.*;import com.opencsv.bean.ColumnPositionMappingStrategy;import com.opencsv.bean.StatefulBeanToCsv;import com.opencsv.bean.StatefulBeanToCsvBuilder; public class BeanToCSV { public static void main(String[] args) { // name of generated csv final String CSV_LOCATION = "Employees.csv "; try { // Creating writer class to generate // csv file FileWriter writer = new FileWriter(CSV_LOCATION); // create a list of employee List<Employee> EmployeeList = new ArrayList<Employee>(); Employee emp1 = new Employee ("Mahafuj", "24", "HTc", "75000"); Employee emp2 = new Employee ("Aman", "24", "microsoft", "79000"); Employee emp3 = new Employee ("Suvradip", "26", "tcs", "39000"); Employee emp4 = new Employee ("Riya", "22", "NgGear", "15000"); Employee emp5 = new Employee ("Prakash", "29", "Sath", "51000"); EmployeeList.add(emp1); EmployeeList.add(emp2); EmployeeList.add(emp3); EmployeeList.add(emp4); EmployeeList.add(emp5); // Create Mapping Strategy to arrange the // column name in order ColumnPositionMappingStrategy mappingStrategy= new ColumnPositionMappingStrategy(); mappingStrategy.setType(Employee.class); // Arrange column name as provided in below array. String[] columns = new String[] { "Name", "Age", "Company", "Salary" }; mappingStrategy.setColumnMapping(columns); // Creating StatefulBeanToCsv object StatefulBeanToCsvBuilder<Employee> builder= new StatefulBeanToCsvBuilder(writer); StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build(); // Write list to StatefulBeanToCsv object beanWriter.write(EmployeeList); // closing the writer object writer.close(); } catch (Exception e) { e.printStackTrace(); } }}
Employee.javapublic class Employee { public String Name, Age, Company, Salary; public Employee(String name, String age, String company, String salary) { super(); Name = name; Age = age; Company = company; Salary = salary; } @Override public String toString() { return "Employee [Name=" + Name + ", Age=" + Age + ", Company=" + Company + ", Salary=" + Salary + "]"; }}
public class Employee { public String Name, Age, Company, Salary; public Employee(String name, String age, String company, String salary) { super(); Name = name; Age = age; Company = company; Salary = salary; } @Override public String toString() { return "Employee [Name=" + Name + ", Age=" + Age + ", Company=" + Company + ", Salary=" + Salary + "]"; }}
BeanToCSV.javaimport java.io.FileWriter;import java.io.Writer;import java.nio.*;import java.nio.file.Files;import java.nio.file.Paths;import java.util.*;import com.opencsv.bean.ColumnPositionMappingStrategy;import com.opencsv.bean.StatefulBeanToCsv;import com.opencsv.bean.StatefulBeanToCsvBuilder; public class BeanToCSV { public static void main(String[] args) { // name of generated csv final String CSV_LOCATION = "Employees.csv "; try { // Creating writer class to generate // csv file FileWriter writer = new FileWriter(CSV_LOCATION); // create a list of employee List<Employee> EmployeeList = new ArrayList<Employee>(); Employee emp1 = new Employee ("Mahafuj", "24", "HTc", "75000"); Employee emp2 = new Employee ("Aman", "24", "microsoft", "79000"); Employee emp3 = new Employee ("Suvradip", "26", "tcs", "39000"); Employee emp4 = new Employee ("Riya", "22", "NgGear", "15000"); Employee emp5 = new Employee ("Prakash", "29", "Sath", "51000"); EmployeeList.add(emp1); EmployeeList.add(emp2); EmployeeList.add(emp3); EmployeeList.add(emp4); EmployeeList.add(emp5); // Create Mapping Strategy to arrange the // column name in order ColumnPositionMappingStrategy mappingStrategy= new ColumnPositionMappingStrategy(); mappingStrategy.setType(Employee.class); // Arrange column name as provided in below array. String[] columns = new String[] { "Name", "Age", "Company", "Salary" }; mappingStrategy.setColumnMapping(columns); // Creating StatefulBeanToCsv object StatefulBeanToCsvBuilder<Employee> builder= new StatefulBeanToCsvBuilder(writer); StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build(); // Write list to StatefulBeanToCsv object beanWriter.write(EmployeeList); // closing the writer object writer.close(); } catch (Exception e) { e.printStackTrace(); } }}
import java.io.FileWriter;import java.io.Writer;import java.nio.*;import java.nio.file.Files;import java.nio.file.Paths;import java.util.*;import com.opencsv.bean.ColumnPositionMappingStrategy;import com.opencsv.bean.StatefulBeanToCsv;import com.opencsv.bean.StatefulBeanToCsvBuilder; public class BeanToCSV { public static void main(String[] args) { // name of generated csv final String CSV_LOCATION = "Employees.csv "; try { // Creating writer class to generate // csv file FileWriter writer = new FileWriter(CSV_LOCATION); // create a list of employee List<Employee> EmployeeList = new ArrayList<Employee>(); Employee emp1 = new Employee ("Mahafuj", "24", "HTc", "75000"); Employee emp2 = new Employee ("Aman", "24", "microsoft", "79000"); Employee emp3 = new Employee ("Suvradip", "26", "tcs", "39000"); Employee emp4 = new Employee ("Riya", "22", "NgGear", "15000"); Employee emp5 = new Employee ("Prakash", "29", "Sath", "51000"); EmployeeList.add(emp1); EmployeeList.add(emp2); EmployeeList.add(emp3); EmployeeList.add(emp4); EmployeeList.add(emp5); // Create Mapping Strategy to arrange the // column name in order ColumnPositionMappingStrategy mappingStrategy= new ColumnPositionMappingStrategy(); mappingStrategy.setType(Employee.class); // Arrange column name as provided in below array. String[] columns = new String[] { "Name", "Age", "Company", "Salary" }; mappingStrategy.setColumnMapping(columns); // Creating StatefulBeanToCsv object StatefulBeanToCsvBuilder<Employee> builder= new StatefulBeanToCsvBuilder(writer); StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build(); // Write list to StatefulBeanToCsv object beanWriter.write(EmployeeList); // closing the writer object writer.close(); } catch (Exception e) { e.printStackTrace(); } }}
Output:
EmployeeData.csv
CSV file contains:-----
"Mahafuj", "24", "HTc", "75000"
"Aman", "24", "microsoft", "79000"
"Suvradip", "26", "tcs", "39000"
"Riya", "22", "NgGear", "15000"
"Prakash", "29", "Sath", "51000"
Reference: BeanToCsv Official Documentation
adnanirshad158
CSV
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 355,
"s": 52,
"text": "The need to convert Java Beans(Objects) to CSV file arises very commonly and there are many ways to write Bean into CSV file but one of the best ways to map java bean to CSV is by using OpenCSV Library. In OpenCSV there is a class name StatefulBeanToCsvBuilder which helps to convert Java Beans to CSV."
},
{
"code": null,
"e": 2472,
"s": 355,
"text": "The first task is to add the OpenCSV library into the Project.For maven project,include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path.Mapping JavaBeans to CSVBelow is the step-by-step procedure to map Java Beans to CSV.Create Writer instance for writing data to the CSV file.Writer writer = Files.newBufferedWriter(Paths.get(file_location));Create a List of objects which are needed to be written into the CSV file.Using ColumnPositionMappingStrategy map the columns of Created objects, to Column of csv.This is an optional step. If ColumnPositionMappingStrategy is not used, then object will be written to csv with column name same as attribute name of object.ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();\n mappingStrategy.setType(Employee.class);\n\nwhere Employee is the object to be mapped with CSV.\nCreate object of StatefulBeanToCsv class by calling build method of StatefulBeanToCsvBuilder class after the creation of StatefulBeanToCsvBuilder, with writer object as parameter. According to the requirement the user can also provide:ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)\n.withMappingStrategy(mappingStrategy)\n. withSeparator('#')\n .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)\n .build();\nAfter creating object of StatefulBeanToCsv class you can add list of object or object to csv file with the help of write method of StatefulBeanToCsv object.beanToCsv.write(Employeelist);\n"
},
{
"code": null,
"e": 2907,
"s": 2472,
"text": "The first task is to add the OpenCSV library into the Project.For maven project,include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'You can Download OpenCSV Jar and include in your project class path."
},
{
"code": null,
"e": 3100,
"s": 2907,
"text": "For maven project,include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>"
},
{
"code": "<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>",
"e": 3222,
"s": 3100,
"text": null
},
{
"code": null,
"e": 3335,
"s": 3222,
"text": "For Gradle Project, include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'"
},
{
"code": null,
"e": 3397,
"s": 3335,
"text": "compile group: 'com.opencsv', name: 'opencsv', version: '4.1'"
},
{
"code": null,
"e": 3466,
"s": 3397,
"text": "You can Download OpenCSV Jar and include in your project class path."
},
{
"code": null,
"e": 5149,
"s": 3466,
"text": "Mapping JavaBeans to CSVBelow is the step-by-step procedure to map Java Beans to CSV.Create Writer instance for writing data to the CSV file.Writer writer = Files.newBufferedWriter(Paths.get(file_location));Create a List of objects which are needed to be written into the CSV file.Using ColumnPositionMappingStrategy map the columns of Created objects, to Column of csv.This is an optional step. If ColumnPositionMappingStrategy is not used, then object will be written to csv with column name same as attribute name of object.ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();\n mappingStrategy.setType(Employee.class);\n\nwhere Employee is the object to be mapped with CSV.\nCreate object of StatefulBeanToCsv class by calling build method of StatefulBeanToCsvBuilder class after the creation of StatefulBeanToCsvBuilder, with writer object as parameter. According to the requirement the user can also provide:ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)\n.withMappingStrategy(mappingStrategy)\n. withSeparator('#')\n .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)\n .build();\nAfter creating object of StatefulBeanToCsv class you can add list of object or object to csv file with the help of write method of StatefulBeanToCsv object.beanToCsv.write(Employeelist);\n"
},
{
"code": null,
"e": 6747,
"s": 5149,
"text": "Create Writer instance for writing data to the CSV file.Writer writer = Files.newBufferedWriter(Paths.get(file_location));Create a List of objects which are needed to be written into the CSV file.Using ColumnPositionMappingStrategy map the columns of Created objects, to Column of csv.This is an optional step. If ColumnPositionMappingStrategy is not used, then object will be written to csv with column name same as attribute name of object.ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();\n mappingStrategy.setType(Employee.class);\n\nwhere Employee is the object to be mapped with CSV.\nCreate object of StatefulBeanToCsv class by calling build method of StatefulBeanToCsvBuilder class after the creation of StatefulBeanToCsvBuilder, with writer object as parameter. According to the requirement the user can also provide:ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)\n.withMappingStrategy(mappingStrategy)\n. withSeparator('#')\n .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)\n .build();\nAfter creating object of StatefulBeanToCsv class you can add list of object or object to csv file with the help of write method of StatefulBeanToCsv object.beanToCsv.write(Employeelist);\n"
},
{
"code": null,
"e": 6870,
"s": 6747,
"text": "Create Writer instance for writing data to the CSV file.Writer writer = Files.newBufferedWriter(Paths.get(file_location));"
},
{
"code": null,
"e": 6937,
"s": 6870,
"text": "Writer writer = Files.newBufferedWriter(Paths.get(file_location));"
},
{
"code": null,
"e": 7012,
"s": 6937,
"text": "Create a List of objects which are needed to be written into the CSV file."
},
{
"code": null,
"e": 7442,
"s": 7012,
"text": "Using ColumnPositionMappingStrategy map the columns of Created objects, to Column of csv.This is an optional step. If ColumnPositionMappingStrategy is not used, then object will be written to csv with column name same as attribute name of object.ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();\n mappingStrategy.setType(Employee.class);\n\nwhere Employee is the object to be mapped with CSV.\n"
},
{
"code": null,
"e": 7626,
"s": 7442,
"text": "ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();\n mappingStrategy.setType(Employee.class);\n\nwhere Employee is the object to be mapped with CSV.\n"
},
{
"code": null,
"e": 8412,
"s": 7626,
"text": "Create object of StatefulBeanToCsv class by calling build method of StatefulBeanToCsvBuilder class after the creation of StatefulBeanToCsvBuilder, with writer object as parameter. According to the requirement the user can also provide:ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object.Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object.withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object.StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)\n.withMappingStrategy(mappingStrategy)\n. withSeparator('#')\n .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)\n .build();\n"
},
{
"code": null,
"e": 8524,
"s": 8412,
"text": "ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCsvBuilder object."
},
{
"code": null,
"e": 8632,
"s": 8524,
"text": "Separator of generated csv file with the help of withSeparator function of StatefulBeanToCsvBuilder object."
},
{
"code": null,
"e": 8744,
"s": 8632,
"text": "withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCsvBuilder object."
},
{
"code": null,
"e": 8966,
"s": 8744,
"text": "StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)\n.withMappingStrategy(mappingStrategy)\n. withSeparator('#')\n .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)\n .build();\n"
},
{
"code": null,
"e": 9154,
"s": 8966,
"text": "After creating object of StatefulBeanToCsv class you can add list of object or object to csv file with the help of write method of StatefulBeanToCsv object.beanToCsv.write(Employeelist);\n"
},
{
"code": null,
"e": 9186,
"s": 9154,
"text": "beanToCsv.write(Employeelist);\n"
},
{
"code": null,
"e": 9403,
"s": 9186,
"text": "Example: In this example, we are going to create the list of Employee Object which has attributes like Name, Age, Company, Salary. Then we will generate a CSV file Employees.csv which contains Employee objects.Codes:"
},
{
"code": null,
"e": 12301,
"s": 9403,
"text": "Employee.javapublic class Employee { public String Name, Age, Company, Salary; public Employee(String name, String age, String company, String salary) { super(); Name = name; Age = age; Company = company; Salary = salary; } @Override public String toString() { return \"Employee [Name=\" + Name + \", Age=\" + Age + \", Company=\" + Company + \", Salary=\" + Salary + \"]\"; }}BeanToCSV.javaimport java.io.FileWriter;import java.io.Writer;import java.nio.*;import java.nio.file.Files;import java.nio.file.Paths;import java.util.*;import com.opencsv.bean.ColumnPositionMappingStrategy;import com.opencsv.bean.StatefulBeanToCsv;import com.opencsv.bean.StatefulBeanToCsvBuilder; public class BeanToCSV { public static void main(String[] args) { // name of generated csv final String CSV_LOCATION = \"Employees.csv \"; try { // Creating writer class to generate // csv file FileWriter writer = new FileWriter(CSV_LOCATION); // create a list of employee List<Employee> EmployeeList = new ArrayList<Employee>(); Employee emp1 = new Employee (\"Mahafuj\", \"24\", \"HTc\", \"75000\"); Employee emp2 = new Employee (\"Aman\", \"24\", \"microsoft\", \"79000\"); Employee emp3 = new Employee (\"Suvradip\", \"26\", \"tcs\", \"39000\"); Employee emp4 = new Employee (\"Riya\", \"22\", \"NgGear\", \"15000\"); Employee emp5 = new Employee (\"Prakash\", \"29\", \"Sath\", \"51000\"); EmployeeList.add(emp1); EmployeeList.add(emp2); EmployeeList.add(emp3); EmployeeList.add(emp4); EmployeeList.add(emp5); // Create Mapping Strategy to arrange the // column name in order ColumnPositionMappingStrategy mappingStrategy= new ColumnPositionMappingStrategy(); mappingStrategy.setType(Employee.class); // Arrange column name as provided in below array. String[] columns = new String[] { \"Name\", \"Age\", \"Company\", \"Salary\" }; mappingStrategy.setColumnMapping(columns); // Creating StatefulBeanToCsv object StatefulBeanToCsvBuilder<Employee> builder= new StatefulBeanToCsvBuilder(writer); StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build(); // Write list to StatefulBeanToCsv object beanWriter.write(EmployeeList); // closing the writer object writer.close(); } catch (Exception e) { e.printStackTrace(); } }}"
},
{
"code": null,
"e": 12770,
"s": 12301,
"text": "Employee.javapublic class Employee { public String Name, Age, Company, Salary; public Employee(String name, String age, String company, String salary) { super(); Name = name; Age = age; Company = company; Salary = salary; } @Override public String toString() { return \"Employee [Name=\" + Name + \", Age=\" + Age + \", Company=\" + Company + \", Salary=\" + Salary + \"]\"; }}"
},
{
"code": "public class Employee { public String Name, Age, Company, Salary; public Employee(String name, String age, String company, String salary) { super(); Name = name; Age = age; Company = company; Salary = salary; } @Override public String toString() { return \"Employee [Name=\" + Name + \", Age=\" + Age + \", Company=\" + Company + \", Salary=\" + Salary + \"]\"; }}",
"e": 13226,
"s": 12770,
"text": null
},
{
"code": null,
"e": 15656,
"s": 13226,
"text": "BeanToCSV.javaimport java.io.FileWriter;import java.io.Writer;import java.nio.*;import java.nio.file.Files;import java.nio.file.Paths;import java.util.*;import com.opencsv.bean.ColumnPositionMappingStrategy;import com.opencsv.bean.StatefulBeanToCsv;import com.opencsv.bean.StatefulBeanToCsvBuilder; public class BeanToCSV { public static void main(String[] args) { // name of generated csv final String CSV_LOCATION = \"Employees.csv \"; try { // Creating writer class to generate // csv file FileWriter writer = new FileWriter(CSV_LOCATION); // create a list of employee List<Employee> EmployeeList = new ArrayList<Employee>(); Employee emp1 = new Employee (\"Mahafuj\", \"24\", \"HTc\", \"75000\"); Employee emp2 = new Employee (\"Aman\", \"24\", \"microsoft\", \"79000\"); Employee emp3 = new Employee (\"Suvradip\", \"26\", \"tcs\", \"39000\"); Employee emp4 = new Employee (\"Riya\", \"22\", \"NgGear\", \"15000\"); Employee emp5 = new Employee (\"Prakash\", \"29\", \"Sath\", \"51000\"); EmployeeList.add(emp1); EmployeeList.add(emp2); EmployeeList.add(emp3); EmployeeList.add(emp4); EmployeeList.add(emp5); // Create Mapping Strategy to arrange the // column name in order ColumnPositionMappingStrategy mappingStrategy= new ColumnPositionMappingStrategy(); mappingStrategy.setType(Employee.class); // Arrange column name as provided in below array. String[] columns = new String[] { \"Name\", \"Age\", \"Company\", \"Salary\" }; mappingStrategy.setColumnMapping(columns); // Creating StatefulBeanToCsv object StatefulBeanToCsvBuilder<Employee> builder= new StatefulBeanToCsvBuilder(writer); StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build(); // Write list to StatefulBeanToCsv object beanWriter.write(EmployeeList); // closing the writer object writer.close(); } catch (Exception e) { e.printStackTrace(); } }}"
},
{
"code": "import java.io.FileWriter;import java.io.Writer;import java.nio.*;import java.nio.file.Files;import java.nio.file.Paths;import java.util.*;import com.opencsv.bean.ColumnPositionMappingStrategy;import com.opencsv.bean.StatefulBeanToCsv;import com.opencsv.bean.StatefulBeanToCsvBuilder; public class BeanToCSV { public static void main(String[] args) { // name of generated csv final String CSV_LOCATION = \"Employees.csv \"; try { // Creating writer class to generate // csv file FileWriter writer = new FileWriter(CSV_LOCATION); // create a list of employee List<Employee> EmployeeList = new ArrayList<Employee>(); Employee emp1 = new Employee (\"Mahafuj\", \"24\", \"HTc\", \"75000\"); Employee emp2 = new Employee (\"Aman\", \"24\", \"microsoft\", \"79000\"); Employee emp3 = new Employee (\"Suvradip\", \"26\", \"tcs\", \"39000\"); Employee emp4 = new Employee (\"Riya\", \"22\", \"NgGear\", \"15000\"); Employee emp5 = new Employee (\"Prakash\", \"29\", \"Sath\", \"51000\"); EmployeeList.add(emp1); EmployeeList.add(emp2); EmployeeList.add(emp3); EmployeeList.add(emp4); EmployeeList.add(emp5); // Create Mapping Strategy to arrange the // column name in order ColumnPositionMappingStrategy mappingStrategy= new ColumnPositionMappingStrategy(); mappingStrategy.setType(Employee.class); // Arrange column name as provided in below array. String[] columns = new String[] { \"Name\", \"Age\", \"Company\", \"Salary\" }; mappingStrategy.setColumnMapping(columns); // Creating StatefulBeanToCsv object StatefulBeanToCsvBuilder<Employee> builder= new StatefulBeanToCsvBuilder(writer); StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build(); // Write list to StatefulBeanToCsv object beanWriter.write(EmployeeList); // closing the writer object writer.close(); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 18072,
"s": 15656,
"text": null
},
{
"code": null,
"e": 18080,
"s": 18072,
"text": "Output:"
},
{
"code": null,
"e": 18288,
"s": 18080,
"text": "EmployeeData.csv\nCSV file contains:-----\n\n\"Mahafuj\", \"24\", \"HTc\", \"75000\"\n\"Aman\", \"24\", \"microsoft\", \"79000\"\n\"Suvradip\", \"26\", \"tcs\", \"39000\"\n\"Riya\", \"22\", \"NgGear\", \"15000\"\n\"Prakash\", \"29\", \"Sath\", \"51000\"\n"
},
{
"code": null,
"e": 18332,
"s": 18288,
"text": "Reference: BeanToCsv Official Documentation"
},
{
"code": null,
"e": 18347,
"s": 18332,
"text": "adnanirshad158"
},
{
"code": null,
"e": 18351,
"s": 18347,
"text": "CSV"
},
{
"code": null,
"e": 18356,
"s": 18351,
"text": "Java"
},
{
"code": null,
"e": 18361,
"s": 18356,
"text": "Java"
}
] |
Check missing dates in Pandas | 09 Nov, 2021
In this article, we will learn how to check missing dates in Pandas.
A data frame is created from a dictionary of lists using pd.DataFrame() which accepts the data as its parameter. Note that here, the dictionary consists of two lists named Date and Name. Both of them are of the same length and some dates are missing from the given sequence of dates ( From 2021-01-18 to 2021-01-25 ). We can also provide a CSV file to this method instead of creating a dataset of our own.
df.set_index() method sets the dates as the index for the data frame we created. One can simply print the data frame using print(df) to see it before and after setting the Date as an index.
Syntax: DataFrame.set_index(keys, drop=True, append=False, inplace=False)
Before setting Date as index:
2021-01-18
After setting Date as index:
Now, once we have set the date as the index, we convert the given list of dates into a DateTime object. Originally, the dates in our list are strings that need to be converted into the DateTime object. Pandas provide us with a method called to_datetime() which converts the date and time in string format to a DateTime object.
Syntax: pandas.to_datetime(arg, errors=’raise’, format=None)
pd.date_range() method accepts a start date, an end date, and creates date sequences in that range.
Syntax: pandas.date_range(start=None, end=None, freq=None)
Pandas.Index.difference() returns a new Index with elements of index not in others. Therefore, by using pd.date_range(start date, end date).difference(Date), we get all the dates that are not present in our list of Dates. The data type returned is an Immutable ndarray-like of datetime64 data.
Syntax: Pandas.Index.difference(other, sort=True)
Example 1:
Python3
#import pandasimport pandas as pd # A dataframe from a dictionary of listsdata = {'Date': ['2021-01-18', '2021-01-20', '2021-01-23', '2021-01-25'], 'Name': ['Jia', 'Tanya', 'Rohan', 'Sam']}df = pd.DataFrame(data) # Setting the Date values as indexdf = df.set_index('Date') # to_datetime() method converts string# format to a DateTime objectdf.index = pd.to_datetime(df.index) # dates which are not in the sequence# are returnedprint(pd.date_range( start="2021-01-18", end="2021-01-25").difference(df.index))
Output:
Finally, we get all the dates that are missing between 2021-01-18 and 2021-01-25.
DatetimeIndex([‘2021-01-19’, ‘2021-01-21’, ‘2021-01-22’, ‘2021-01-24′], dtype=’datetime64[ns]’, freq=None)
Example 2:
Let us consider another example. However, this time we will not set the date as an index and will assign freq=’B’ (Business Day Frequency) inside the pd.date_range() function.
Just like the previous example, we make a dataframe from the dictionary of lists. However, this time we do not set the date values as index. Instead, we set the column ‘Total People’ as our index values. Using pd.date_range() function, which takes start date, end date and frequency as parameters, we provide the values. We set the freq= ‘B’ (Business Day Frequency) in order to omit weekends. Finally, Pandas.Index.difference() takes the Date column as a parameter and returns all those values which are not in the given set of values.
Python3
#import pandasimport pandas as pd # A dataframe from a dictionary of listsd = {'Date': ['2021-01-10', '2021-01-14', '2021-01-18', '2021-01-25', '2021-01-28', '2021-01-29'], 'Total People': [20, 21, 19, 18, 13, 56]}df = pd.DataFrame(d) # Setting the Total People as indexdf = df.set_index('Total People') # to_datetime() method converts string# format to a DateTime objectdf['Date'] = pd.to_datetime(df['Date']) # dates which are not in the sequence# are returnedmy_range = pd.date_range( start="2021-01-10", end="2021-01-31", freq='B') print(my_range.difference(df['Date']))
Output:
Note that all the missing values except 2021-01-23, 2021-01-24, and 2021-01-30 are returned because we have set freq=’B’ which omits all the weekends.
kashishsoda
Picked
Python pandas-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 97,
"s": 28,
"text": "In this article, we will learn how to check missing dates in Pandas."
},
{
"code": null,
"e": 504,
"s": 97,
"text": "A data frame is created from a dictionary of lists using pd.DataFrame() which accepts the data as its parameter. Note that here, the dictionary consists of two lists named Date and Name. Both of them are of the same length and some dates are missing from the given sequence of dates ( From 2021-01-18 to 2021-01-25 ). We can also provide a CSV file to this method instead of creating a dataset of our own."
},
{
"code": null,
"e": 695,
"s": 504,
"text": "df.set_index() method sets the dates as the index for the data frame we created. One can simply print the data frame using print(df) to see it before and after setting the Date as an index."
},
{
"code": null,
"e": 769,
"s": 695,
"text": "Syntax: DataFrame.set_index(keys, drop=True, append=False, inplace=False)"
},
{
"code": null,
"e": 799,
"s": 769,
"text": "Before setting Date as index:"
},
{
"code": null,
"e": 811,
"s": 799,
"text": "2021-01-18 "
},
{
"code": null,
"e": 840,
"s": 811,
"text": "After setting Date as index:"
},
{
"code": null,
"e": 1167,
"s": 840,
"text": "Now, once we have set the date as the index, we convert the given list of dates into a DateTime object. Originally, the dates in our list are strings that need to be converted into the DateTime object. Pandas provide us with a method called to_datetime() which converts the date and time in string format to a DateTime object."
},
{
"code": null,
"e": 1228,
"s": 1167,
"text": "Syntax: pandas.to_datetime(arg, errors=’raise’, format=None)"
},
{
"code": null,
"e": 1328,
"s": 1228,
"text": "pd.date_range() method accepts a start date, an end date, and creates date sequences in that range."
},
{
"code": null,
"e": 1387,
"s": 1328,
"text": "Syntax: pandas.date_range(start=None, end=None, freq=None)"
},
{
"code": null,
"e": 1681,
"s": 1387,
"text": "Pandas.Index.difference() returns a new Index with elements of index not in others. Therefore, by using pd.date_range(start date, end date).difference(Date), we get all the dates that are not present in our list of Dates. The data type returned is an Immutable ndarray-like of datetime64 data."
},
{
"code": null,
"e": 1731,
"s": 1681,
"text": "Syntax: Pandas.Index.difference(other, sort=True)"
},
{
"code": null,
"e": 1742,
"s": 1731,
"text": "Example 1:"
},
{
"code": null,
"e": 1750,
"s": 1742,
"text": "Python3"
},
{
"code": "#import pandasimport pandas as pd # A dataframe from a dictionary of listsdata = {'Date': ['2021-01-18', '2021-01-20', '2021-01-23', '2021-01-25'], 'Name': ['Jia', 'Tanya', 'Rohan', 'Sam']}df = pd.DataFrame(data) # Setting the Date values as indexdf = df.set_index('Date') # to_datetime() method converts string# format to a DateTime objectdf.index = pd.to_datetime(df.index) # dates which are not in the sequence# are returnedprint(pd.date_range( start=\"2021-01-18\", end=\"2021-01-25\").difference(df.index))",
"e": 2282,
"s": 1750,
"text": null
},
{
"code": null,
"e": 2290,
"s": 2282,
"text": "Output:"
},
{
"code": null,
"e": 2372,
"s": 2290,
"text": "Finally, we get all the dates that are missing between 2021-01-18 and 2021-01-25."
},
{
"code": null,
"e": 2479,
"s": 2372,
"text": "DatetimeIndex([‘2021-01-19’, ‘2021-01-21’, ‘2021-01-22’, ‘2021-01-24′], dtype=’datetime64[ns]’, freq=None)"
},
{
"code": null,
"e": 2490,
"s": 2479,
"text": "Example 2:"
},
{
"code": null,
"e": 2666,
"s": 2490,
"text": "Let us consider another example. However, this time we will not set the date as an index and will assign freq=’B’ (Business Day Frequency) inside the pd.date_range() function."
},
{
"code": null,
"e": 3205,
"s": 2666,
"text": "Just like the previous example, we make a dataframe from the dictionary of lists. However, this time we do not set the date values as index. Instead, we set the column ‘Total People’ as our index values. Using pd.date_range() function, which takes start date, end date and frequency as parameters, we provide the values. We set the freq= ‘B’ (Business Day Frequency) in order to omit weekends. Finally, Pandas.Index.difference() takes the Date column as a parameter and returns all those values which are not in the given set of values."
},
{
"code": null,
"e": 3213,
"s": 3205,
"text": "Python3"
},
{
"code": "#import pandasimport pandas as pd # A dataframe from a dictionary of listsd = {'Date': ['2021-01-10', '2021-01-14', '2021-01-18', '2021-01-25', '2021-01-28', '2021-01-29'], 'Total People': [20, 21, 19, 18, 13, 56]}df = pd.DataFrame(d) # Setting the Total People as indexdf = df.set_index('Total People') # to_datetime() method converts string# format to a DateTime objectdf['Date'] = pd.to_datetime(df['Date']) # dates which are not in the sequence# are returnedmy_range = pd.date_range( start=\"2021-01-10\", end=\"2021-01-31\", freq='B') print(my_range.difference(df['Date']))",
"e": 3806,
"s": 3213,
"text": null
},
{
"code": null,
"e": 3815,
"s": 3806,
"text": " Output:"
},
{
"code": null,
"e": 3966,
"s": 3815,
"text": "Note that all the missing values except 2021-01-23, 2021-01-24, and 2021-01-30 are returned because we have set freq=’B’ which omits all the weekends."
},
{
"code": null,
"e": 3978,
"s": 3966,
"text": "kashishsoda"
},
{
"code": null,
"e": 3985,
"s": 3978,
"text": "Picked"
},
{
"code": null,
"e": 4008,
"s": 3985,
"text": "Python pandas-datetime"
},
{
"code": null,
"e": 4022,
"s": 4008,
"text": "Python-pandas"
},
{
"code": null,
"e": 4029,
"s": 4022,
"text": "Python"
}
] |
Range-based for loop in C++ | The range based for loop is added in C++ 11 standard and is a more compact form of its traditional equivalent. The range based for loop is used to iterate over elements of a container from beginning to end. The syntax for range-based for loop is as follows −
for( range-declaration : range-expression ) loop statement
range-declaration − it is declaration of a variable of type same as the type of elements of range-expression. Often the auto keyword is used to automatically identify the type of elements in range-expression.
range-expression − any expression used to represent a sequence of elements. Also Sequence of elements in braces can be used.
loop-statement − body of for loop that contains one or more statements that are to be executed repeatedly till the end of range-expression.
Comparison with traditional for loop −
// Iterating over array
int arr[] = { 10,20,30,40,50 };
for (int num : arr)
printf("%d, ",num);
Is same as:
for ( int i=0;i<5;i++ )
printf("%d, ",arr[i]);
Here one can easily see that there is no need of calculating the size of array in rangebased
for loop therefore no conditional expression is required. Also, there is no requirement of increment or decrement operation. The num in range based for loop above for each iteration takes the value of element from array arr[] from beginning till
end. No elements are skipped until one of the jump statements are executed.
Break − terminates the loop for all rest of the iterations.
Continue − skips the current iteration and moves to next
goto − jumps out of the loop to statement followed by label −
Easy to use and simple syntax.
Easy to use and simple syntax.
No need to calculate the number of elements in container or size of range-expression.
No need to calculate the number of elements in container or size of range-expression.
If data type of range-declaration is not known then auto specifier can be used in its
place, that automatically makes it compatible with range-expression’s type.
If data type of range-declaration is not known then auto specifier can be used in its
place, that automatically makes it compatible with range-expression’s type.
No conditional statements or increment/decrement statements are required.
No conditional statements or increment/decrement statements are required.
Best in case where the whole container is to be iterated in one go.
Best in case where the whole container is to be iterated in one go.
Iterates over every element between begin() and end(). Specific indexes cannot be treated.
Iterates over every element between begin() and end(). Specific indexes cannot be treated.
Revisiting one or more elements and skipping a group of elements cannot be done using
range-based for loop.
Revisiting one or more elements and skipping a group of elements cannot be done using
range-based for loop.
The array cannot be iterated in reverse order. For that
<boost/range/adaptor/reversed.hpp> library is used
The array cannot be iterated in reverse order. For that
<boost/range/adaptor/reversed.hpp> library is used
Live Demo
#include <iostream>
#include <vector>
#include <map>
int main(){
int arr[] = { 10,20,30,40,50 };
// traditional for
for ( int i=0;i<5;i++ )
printf("%d, ",arr[i]);
printf("\n");
for (int num : arr)
printf("%d, ",num);
printf("\n");
// for character array
char str[] = "Hello World";
for (char c : str)
printf("%c ",c);
printf("\n");
for (char c : "Hello World")
printf("%c ",c);
printf("\n");
std::map <int, char> MAP({{1, 'A'}, {2, 'B'}, {3, 'C'}});
for (auto m : MAP)
printf("{ %d, %c }", m.first,m.second);
}
10, 20, 30, 40, 50,
10, 20, 30, 40, 50,
H e l l o W o r l d
H e l l o W o r l d
{ 1, A }{ 2, B }{ 3, C } | [
{
"code": null,
"e": 1446,
"s": 1187,
"text": "The range based for loop is added in C++ 11 standard and is a more compact form of its traditional equivalent. The range based for loop is used to iterate over elements of a container from beginning to end. The syntax for range-based for loop is as follows −"
},
{
"code": null,
"e": 1505,
"s": 1446,
"text": "for( range-declaration : range-expression ) loop statement"
},
{
"code": null,
"e": 1714,
"s": 1505,
"text": "range-declaration − it is declaration of a variable of type same as the type of elements of range-expression. Often the auto keyword is used to automatically identify the type of elements in range-expression."
},
{
"code": null,
"e": 1839,
"s": 1714,
"text": "range-expression − any expression used to represent a sequence of elements. Also Sequence of elements in braces can be used."
},
{
"code": null,
"e": 1979,
"s": 1839,
"text": "loop-statement − body of for loop that contains one or more statements that are to be executed repeatedly till the end of range-expression."
},
{
"code": null,
"e": 2018,
"s": 1979,
"text": "Comparison with traditional for loop −"
},
{
"code": null,
"e": 2173,
"s": 2018,
"text": "// Iterating over array\nint arr[] = { 10,20,30,40,50 };\nfor (int num : arr)\nprintf(\"%d, \",num);\nIs same as:\nfor ( int i=0;i<5;i++ )\nprintf(\"%d, \",arr[i]);"
},
{
"code": null,
"e": 2588,
"s": 2173,
"text": "Here one can easily see that there is no need of calculating the size of array in rangebased\nfor loop therefore no conditional expression is required. Also, there is no requirement of increment or decrement operation. The num in range based for loop above for each iteration takes the value of element from array arr[] from beginning till\nend. No elements are skipped until one of the jump statements are executed."
},
{
"code": null,
"e": 2648,
"s": 2588,
"text": "Break − terminates the loop for all rest of the iterations."
},
{
"code": null,
"e": 2705,
"s": 2648,
"text": "Continue − skips the current iteration and moves to next"
},
{
"code": null,
"e": 2767,
"s": 2705,
"text": "goto − jumps out of the loop to statement followed by label −"
},
{
"code": null,
"e": 2798,
"s": 2767,
"text": "Easy to use and simple syntax."
},
{
"code": null,
"e": 2829,
"s": 2798,
"text": "Easy to use and simple syntax."
},
{
"code": null,
"e": 2915,
"s": 2829,
"text": "No need to calculate the number of elements in container or size of range-expression."
},
{
"code": null,
"e": 3001,
"s": 2915,
"text": "No need to calculate the number of elements in container or size of range-expression."
},
{
"code": null,
"e": 3163,
"s": 3001,
"text": "If data type of range-declaration is not known then auto specifier can be used in its\nplace, that automatically makes it compatible with range-expression’s type."
},
{
"code": null,
"e": 3325,
"s": 3163,
"text": "If data type of range-declaration is not known then auto specifier can be used in its\nplace, that automatically makes it compatible with range-expression’s type."
},
{
"code": null,
"e": 3399,
"s": 3325,
"text": "No conditional statements or increment/decrement statements are required."
},
{
"code": null,
"e": 3473,
"s": 3399,
"text": "No conditional statements or increment/decrement statements are required."
},
{
"code": null,
"e": 3541,
"s": 3473,
"text": "Best in case where the whole container is to be iterated in one go."
},
{
"code": null,
"e": 3609,
"s": 3541,
"text": "Best in case where the whole container is to be iterated in one go."
},
{
"code": null,
"e": 3700,
"s": 3609,
"text": "Iterates over every element between begin() and end(). Specific indexes cannot be treated."
},
{
"code": null,
"e": 3791,
"s": 3700,
"text": "Iterates over every element between begin() and end(). Specific indexes cannot be treated."
},
{
"code": null,
"e": 3899,
"s": 3791,
"text": "Revisiting one or more elements and skipping a group of elements cannot be done using\nrange-based for loop."
},
{
"code": null,
"e": 4007,
"s": 3899,
"text": "Revisiting one or more elements and skipping a group of elements cannot be done using\nrange-based for loop."
},
{
"code": null,
"e": 4114,
"s": 4007,
"text": "The array cannot be iterated in reverse order. For that\n<boost/range/adaptor/reversed.hpp> library is used"
},
{
"code": null,
"e": 4221,
"s": 4114,
"text": "The array cannot be iterated in reverse order. For that\n<boost/range/adaptor/reversed.hpp> library is used"
},
{
"code": null,
"e": 4232,
"s": 4221,
"text": " Live Demo"
},
{
"code": null,
"e": 4833,
"s": 4232,
"text": "#include <iostream>\n#include <vector>\n#include <map>\nint main(){\n int arr[] = { 10,20,30,40,50 };\n // traditional for\n for ( int i=0;i<5;i++ )\n printf(\"%d, \",arr[i]);\n printf(\"\\n\");\n for (int num : arr)\n printf(\"%d, \",num);\n printf(\"\\n\");\n // for character array\n char str[] = \"Hello World\";\n for (char c : str)\n printf(\"%c \",c);\n printf(\"\\n\");\n for (char c : \"Hello World\")\n printf(\"%c \",c);\n printf(\"\\n\");\n std::map <int, char> MAP({{1, 'A'}, {2, 'B'}, {3, 'C'}});\n for (auto m : MAP)\n printf(\"{ %d, %c }\", m.first,m.second);\n}"
},
{
"code": null,
"e": 4938,
"s": 4833,
"text": "10, 20, 30, 40, 50,\n10, 20, 30, 40, 50,\nH e l l o W o r l d\nH e l l o W o r l d\n{ 1, A }{ 2, B }{ 3, C }"
}
] |
Python Turtle – Graphics Keyboard Commands | 16 Dec, 2021
Python Turtle module is a graphical tool that can be used to draw simple graphics on the screen using a cursor. Python Turtle was a part of Logo programming language which had similar purpose of letting the users draw graphics on the screen with the help of simple commands. Turtle is a pre-installed module and has inbuilt commands and features that can be used to draw pictures on the screen. This article will be primarily focused on creating a graphic using keyboard commands along with how the same methodology can be used to add or change color to the graphic.
Screen() – used to create a canvas for drawing
Turtle Motion:forward(distance) | fd(distance) : move the turtle forwardbackward(distance) | back(distance) | bk(distance) : move the turtle backwardsright(distance) | rt(distance) : move the turtle rightleft(distance) | lt(distance) : move the turtle leftcircle(radius) : draws a circle with a given radius
forward(distance) | fd(distance) : move the turtle forward
backward(distance) | back(distance) | bk(distance) : move the turtle backwards
right(distance) | rt(distance) : move the turtle right
left(distance) | lt(distance) : move the turtle left
circle(radius) : draws a circle with a given radius
Coloring:color() : set the colorsbegin_fill() : this method is called before drawing a shape that is to be filledend_fill() : Fills the shape drawn after the call to begin_fill().
color() : set the colors
begin_fill() : this method is called before drawing a shape that is to be filled
end_fill() : Fills the shape drawn after the call to begin_fill().
Given below are two approaches that deal and discuss how to create a graphics keyboard
Approach
Import module and submodules
Create setup- The setup() method sets up a window of size 500×500.
Create window- The Screen() method creates a canvas for drawing.
Instantiate turtle object
Set turtle speed to 0 which is maximum
Set visibility- The showturtle() method sets the visibility of the turtle.
In order to capture the keystrokes we need to define few functions namely up, down, left, right. By default, the turtle points to the right.The setheading() method changes the orientation of the turtle to the given angle.The forward() method moves the turtle to the specified distance.The listen() method sets focus on the turtle screen to capture events.The onkey() method invokes the method specific to the captured keystroke. The first argument of onkey() is the function to be called and the second argument is the key.The Up,Down,Left and Right are the corresponding arrow keys on the keyboard.
The setheading() method changes the orientation of the turtle to the given angle.
The forward() method moves the turtle to the specified distance.
The listen() method sets focus on the turtle screen to capture events.
The onkey() method invokes the method specific to the captured keystroke. The first argument of onkey() is the function to be called and the second argument is the key.
The Up,Down,Left and Right are the corresponding arrow keys on the keyboard.
Add mainloop() command, it prevents the application from terminating before the user actually clicks the exit option.
Program
Python3
import turtlefrom turtle import * setup(500, 500)Screen()turtle = turtle.Turtle()turtle.speed(0)showturtle() def up(): turtle.setheading(90) turtle.forward(100) def down(): turtle.setheading(270) turtle.forward(100) def left(): turtle.setheading(180) turtle.forward(100) def right(): turtle.setheading(0) turtle.forward(100) listen()onkey(up, 'Up')onkey(down, 'Down')onkey(left, 'Left')onkey(right, 'Right') mainloop()
Output
This is similar to the previous example with the addition of few more keys. Now we have added keys to change the color of the line.
If the user presses r it turns red,
If g it turns green and if b it turns blue.
For resetting the line color to black the user must press z.
Also, the thickness of the line is increased by setting the width o the turtle to 5px using the width() method.
Program
Python3
import turtlefrom turtle import * setup(500, 500)Screen()turtle = turtle.Turtle()turtle.speed(0)turtle.width(5)showturtle() def up(): turtle.setheading(90) turtle.forward(100) def down(): turtle.setheading(270) turtle.forward(100) def left(): turtle.setheading(180) turtle.forward(100) def right(): turtle.setheading(0) turtle.forward(100) def r(): turtle.color("red") def g(): turtle.color("green") def b(): turtle.color("blue") def z(): turtle.color("black") listen()onkey(up, 'Up')onkey(down, 'Down')onkey(left, 'Left')onkey(right, 'Right')onkey(z, "z")onkey(r, 'r')onkey(g, 'g')onkey(b, 'b') mainloop()
Output
ManasChhabra2
Picked
Python-turtle
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 595,
"s": 28,
"text": "Python Turtle module is a graphical tool that can be used to draw simple graphics on the screen using a cursor. Python Turtle was a part of Logo programming language which had similar purpose of letting the users draw graphics on the screen with the help of simple commands. Turtle is a pre-installed module and has inbuilt commands and features that can be used to draw pictures on the screen. This article will be primarily focused on creating a graphic using keyboard commands along with how the same methodology can be used to add or change color to the graphic."
},
{
"code": null,
"e": 642,
"s": 595,
"text": "Screen() – used to create a canvas for drawing"
},
{
"code": null,
"e": 950,
"s": 642,
"text": "Turtle Motion:forward(distance) | fd(distance) : move the turtle forwardbackward(distance) | back(distance) | bk(distance) : move the turtle backwardsright(distance) | rt(distance) : move the turtle rightleft(distance) | lt(distance) : move the turtle leftcircle(radius) : draws a circle with a given radius"
},
{
"code": null,
"e": 1009,
"s": 950,
"text": "forward(distance) | fd(distance) : move the turtle forward"
},
{
"code": null,
"e": 1088,
"s": 1009,
"text": "backward(distance) | back(distance) | bk(distance) : move the turtle backwards"
},
{
"code": null,
"e": 1143,
"s": 1088,
"text": "right(distance) | rt(distance) : move the turtle right"
},
{
"code": null,
"e": 1196,
"s": 1143,
"text": "left(distance) | lt(distance) : move the turtle left"
},
{
"code": null,
"e": 1248,
"s": 1196,
"text": "circle(radius) : draws a circle with a given radius"
},
{
"code": null,
"e": 1428,
"s": 1248,
"text": "Coloring:color() : set the colorsbegin_fill() : this method is called before drawing a shape that is to be filledend_fill() : Fills the shape drawn after the call to begin_fill()."
},
{
"code": null,
"e": 1453,
"s": 1428,
"text": "color() : set the colors"
},
{
"code": null,
"e": 1534,
"s": 1453,
"text": "begin_fill() : this method is called before drawing a shape that is to be filled"
},
{
"code": null,
"e": 1601,
"s": 1534,
"text": "end_fill() : Fills the shape drawn after the call to begin_fill()."
},
{
"code": null,
"e": 1688,
"s": 1601,
"text": "Given below are two approaches that deal and discuss how to create a graphics keyboard"
},
{
"code": null,
"e": 1697,
"s": 1688,
"text": "Approach"
},
{
"code": null,
"e": 1726,
"s": 1697,
"text": "Import module and submodules"
},
{
"code": null,
"e": 1793,
"s": 1726,
"text": "Create setup- The setup() method sets up a window of size 500×500."
},
{
"code": null,
"e": 1858,
"s": 1793,
"text": "Create window- The Screen() method creates a canvas for drawing."
},
{
"code": null,
"e": 1884,
"s": 1858,
"text": "Instantiate turtle object"
},
{
"code": null,
"e": 1923,
"s": 1884,
"text": "Set turtle speed to 0 which is maximum"
},
{
"code": null,
"e": 1998,
"s": 1923,
"text": "Set visibility- The showturtle() method sets the visibility of the turtle."
},
{
"code": null,
"e": 2598,
"s": 1998,
"text": "In order to capture the keystrokes we need to define few functions namely up, down, left, right. By default, the turtle points to the right.The setheading() method changes the orientation of the turtle to the given angle.The forward() method moves the turtle to the specified distance.The listen() method sets focus on the turtle screen to capture events.The onkey() method invokes the method specific to the captured keystroke. The first argument of onkey() is the function to be called and the second argument is the key.The Up,Down,Left and Right are the corresponding arrow keys on the keyboard."
},
{
"code": null,
"e": 2680,
"s": 2598,
"text": "The setheading() method changes the orientation of the turtle to the given angle."
},
{
"code": null,
"e": 2745,
"s": 2680,
"text": "The forward() method moves the turtle to the specified distance."
},
{
"code": null,
"e": 2816,
"s": 2745,
"text": "The listen() method sets focus on the turtle screen to capture events."
},
{
"code": null,
"e": 2985,
"s": 2816,
"text": "The onkey() method invokes the method specific to the captured keystroke. The first argument of onkey() is the function to be called and the second argument is the key."
},
{
"code": null,
"e": 3062,
"s": 2985,
"text": "The Up,Down,Left and Right are the corresponding arrow keys on the keyboard."
},
{
"code": null,
"e": 3180,
"s": 3062,
"text": "Add mainloop() command, it prevents the application from terminating before the user actually clicks the exit option."
},
{
"code": null,
"e": 3188,
"s": 3180,
"text": "Program"
},
{
"code": null,
"e": 3196,
"s": 3188,
"text": "Python3"
},
{
"code": "import turtlefrom turtle import * setup(500, 500)Screen()turtle = turtle.Turtle()turtle.speed(0)showturtle() def up(): turtle.setheading(90) turtle.forward(100) def down(): turtle.setheading(270) turtle.forward(100) def left(): turtle.setheading(180) turtle.forward(100) def right(): turtle.setheading(0) turtle.forward(100) listen()onkey(up, 'Up')onkey(down, 'Down')onkey(left, 'Left')onkey(right, 'Right') mainloop()",
"e": 3644,
"s": 3196,
"text": null
},
{
"code": null,
"e": 3651,
"s": 3644,
"text": "Output"
},
{
"code": null,
"e": 3784,
"s": 3651,
"text": "This is similar to the previous example with the addition of few more keys. Now we have added keys to change the color of the line. "
},
{
"code": null,
"e": 3820,
"s": 3784,
"text": "If the user presses r it turns red,"
},
{
"code": null,
"e": 3864,
"s": 3820,
"text": "If g it turns green and if b it turns blue."
},
{
"code": null,
"e": 3925,
"s": 3864,
"text": "For resetting the line color to black the user must press z."
},
{
"code": null,
"e": 4037,
"s": 3925,
"text": "Also, the thickness of the line is increased by setting the width o the turtle to 5px using the width() method."
},
{
"code": null,
"e": 4045,
"s": 4037,
"text": "Program"
},
{
"code": null,
"e": 4053,
"s": 4045,
"text": "Python3"
},
{
"code": "import turtlefrom turtle import * setup(500, 500)Screen()turtle = turtle.Turtle()turtle.speed(0)turtle.width(5)showturtle() def up(): turtle.setheading(90) turtle.forward(100) def down(): turtle.setheading(270) turtle.forward(100) def left(): turtle.setheading(180) turtle.forward(100) def right(): turtle.setheading(0) turtle.forward(100) def r(): turtle.color(\"red\") def g(): turtle.color(\"green\") def b(): turtle.color(\"blue\") def z(): turtle.color(\"black\") listen()onkey(up, 'Up')onkey(down, 'Down')onkey(left, 'Left')onkey(right, 'Right')onkey(z, \"z\")onkey(r, 'r')onkey(g, 'g')onkey(b, 'b') mainloop()",
"e": 4705,
"s": 4053,
"text": null
},
{
"code": null,
"e": 4712,
"s": 4705,
"text": "Output"
},
{
"code": null,
"e": 4726,
"s": 4712,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 4733,
"s": 4726,
"text": "Picked"
},
{
"code": null,
"e": 4747,
"s": 4733,
"text": "Python-turtle"
},
{
"code": null,
"e": 4771,
"s": 4747,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4778,
"s": 4771,
"text": "Python"
},
{
"code": null,
"e": 4797,
"s": 4778,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4895,
"s": 4797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4940,
"s": 4895,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 4990,
"s": 4940,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 5006,
"s": 4990,
"text": "Deque in Python"
},
{
"code": null,
"e": 5022,
"s": 5006,
"text": "Queue in Python"
},
{
"code": null,
"e": 5044,
"s": 5022,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 5086,
"s": 5044,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5113,
"s": 5086,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5136,
"s": 5113,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 5155,
"s": 5136,
"text": "reduce() in Python"
}
] |
How to create horizontal scrollable sections using CSS ? | 27 Oct, 2021
In this article, we will see how we can create a horizontal scrollable section using CSS. HTML code is used to create the basic structure of the sections and CSS code is used to set the style,
HTML Code: In this section, we will create a structure of our sections.
Steps:
Create a div element with class content.
Inside our content div create another four div with class section.
Give four different ids to each div.
In each div include a heading tag with the appropriate heading.
HTML
<!DOCTYPE html><html lang="en"> <body> <!-- Main container with class content --> <div class="content"> <!-- Four sections for our code --> <div class="section" id="one"> <!-- Heading tag --> <h1>Welcome To</h1> </div> <div class="section" id="two"> <h1>Geeks</h1> </div> <div class="section" id="three"> <h1>For</h1> </div> <div class="section" id="four"> <h1>Geeks</h1> </div> </div></body></html>
CSS: We will use CSS to give our section some structure.
HTML
<style> /* Adding color to first section */ #one{ background-color: #E6358B; } /* Adding color to second section */ #two{ background-color: #22A2AF; } /* Adding color to third section */ #three{ background-color: #7CEC9F; } /* Adding color to four section */ #four{ background-color: #D8A928; } /* General styling to our main section */ .content{ width: 100vw; height: 80vh; display: flex; align-items: center; flex-wrap: nowrap; } /* Styling to each individual section */ .section{ width: 100%; height: 100%; flex: 0 0 auto; display: flex; align-items: center; justify-content: center; color: #ffffff; } /* For hiding scroll bar */ ::-webkit-scrollbar{ display: none; }</style>
Complete Code:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> /* Adding color to first section */ #one { background-color: #E6358B; } /* Adding color to second section */ #two { background-color: #22A2AF; } /* Adding color to third section */ #three { background-color: #7CEC9F; } /* Adding color to four section */ #four { background-color: #D8A928; } /* General styling to our main section */ .content { width: 100vw; height: 80vh; display: flex; align-items: center; flex-wrap: nowrap; } /* Styling to each individual section */ .section { width: 100%; height: 100%; flex: 0 0 auto; display: flex; align-items: center; justify-content: center; color: #ffffff; } /* For hiding scoll bar */ ::-webkit-scrollbar { display: none; } </style></head> <body> <!-- Main container with class content --> <div class="content"> <!-- Four sections for our code --> <div class="section" id="one"> <!-- Heading tag --> <h1>Welcome To</h1> </div> <div class="section" id="two"> <h1>Geeks</h1> </div> <div class="section" id="three"> <h1>For</h1> </div> <div class="section" id="four"> <h1>Geeks</h1> </div> </div></body> </html>
Output:
rajeev0719singh
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 221,
"s": 28,
"text": "In this article, we will see how we can create a horizontal scrollable section using CSS. HTML code is used to create the basic structure of the sections and CSS code is used to set the style,"
},
{
"code": null,
"e": 294,
"s": 221,
"text": "HTML Code: In this section, we will create a structure of our sections. "
},
{
"code": null,
"e": 301,
"s": 294,
"text": "Steps:"
},
{
"code": null,
"e": 342,
"s": 301,
"text": "Create a div element with class content."
},
{
"code": null,
"e": 409,
"s": 342,
"text": "Inside our content div create another four div with class section."
},
{
"code": null,
"e": 446,
"s": 409,
"text": "Give four different ids to each div."
},
{
"code": null,
"e": 510,
"s": 446,
"text": "In each div include a heading tag with the appropriate heading."
},
{
"code": null,
"e": 515,
"s": 510,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <body> <!-- Main container with class content --> <div class=\"content\"> <!-- Four sections for our code --> <div class=\"section\" id=\"one\"> <!-- Heading tag --> <h1>Welcome To</h1> </div> <div class=\"section\" id=\"two\"> <h1>Geeks</h1> </div> <div class=\"section\" id=\"three\"> <h1>For</h1> </div> <div class=\"section\" id=\"four\"> <h1>Geeks</h1> </div> </div></body></html>",
"e": 1045,
"s": 515,
"text": null
},
{
"code": null,
"e": 1102,
"s": 1045,
"text": "CSS: We will use CSS to give our section some structure."
},
{
"code": null,
"e": 1107,
"s": 1102,
"text": "HTML"
},
{
"code": "<style> /* Adding color to first section */ #one{ background-color: #E6358B; } /* Adding color to second section */ #two{ background-color: #22A2AF; } /* Adding color to third section */ #three{ background-color: #7CEC9F; } /* Adding color to four section */ #four{ background-color: #D8A928; } /* General styling to our main section */ .content{ width: 100vw; height: 80vh; display: flex; align-items: center; flex-wrap: nowrap; } /* Styling to each individual section */ .section{ width: 100%; height: 100%; flex: 0 0 auto; display: flex; align-items: center; justify-content: center; color: #ffffff; } /* For hiding scroll bar */ ::-webkit-scrollbar{ display: none; }</style>",
"e": 1973,
"s": 1107,
"text": null
},
{
"code": null,
"e": 1988,
"s": 1973,
"text": "Complete Code:"
},
{
"code": null,
"e": 1993,
"s": 1988,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Adding color to first section */ #one { background-color: #E6358B; } /* Adding color to second section */ #two { background-color: #22A2AF; } /* Adding color to third section */ #three { background-color: #7CEC9F; } /* Adding color to four section */ #four { background-color: #D8A928; } /* General styling to our main section */ .content { width: 100vw; height: 80vh; display: flex; align-items: center; flex-wrap: nowrap; } /* Styling to each individual section */ .section { width: 100%; height: 100%; flex: 0 0 auto; display: flex; align-items: center; justify-content: center; color: #ffffff; } /* For hiding scoll bar */ ::-webkit-scrollbar { display: none; } </style></head> <body> <!-- Main container with class content --> <div class=\"content\"> <!-- Four sections for our code --> <div class=\"section\" id=\"one\"> <!-- Heading tag --> <h1>Welcome To</h1> </div> <div class=\"section\" id=\"two\"> <h1>Geeks</h1> </div> <div class=\"section\" id=\"three\"> <h1>For</h1> </div> <div class=\"section\" id=\"four\"> <h1>Geeks</h1> </div> </div></body> </html>",
"e": 3582,
"s": 1993,
"text": null
},
{
"code": null,
"e": 3590,
"s": 3582,
"text": "Output:"
},
{
"code": null,
"e": 3606,
"s": 3590,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 3621,
"s": 3606,
"text": "CSS-Properties"
},
{
"code": null,
"e": 3635,
"s": 3621,
"text": "CSS-Questions"
},
{
"code": null,
"e": 3650,
"s": 3635,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3660,
"s": 3650,
"text": "HTML-Tags"
},
{
"code": null,
"e": 3664,
"s": 3660,
"text": "CSS"
},
{
"code": null,
"e": 3681,
"s": 3664,
"text": "Web Technologies"
},
{
"code": null,
"e": 3779,
"s": 3681,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3827,
"s": 3779,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3889,
"s": 3827,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3939,
"s": 3889,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3997,
"s": 3939,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 4047,
"s": 3997,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 4080,
"s": 4047,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4142,
"s": 4080,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4203,
"s": 4142,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4253,
"s": 4203,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Computer Graphics | Antialiasing | 03 Jul, 2022
Antialiasing is a technique used in computer graphics to remove the aliasing effect. The aliasing effect is the appearance of jagged edges or “jaggies” in a rasterized image (an image rendered using pixels). The problem of jagged edges technically occurs due to distortion of the image when scan conversion is done with sampling at a low frequency, which is also known as Undersampling. Aliasing occurs when real-world objects which comprise of smooth, continuous curves are rasterized using pixels.
Cause of anti-aliasing is Undersampling. Undersampling results in loss of information of the picture. Undersampling occurs when sampling is done at a frequency lower than Nyquist sampling frequency. To avoid this loss, we need to have our sampling frequency atleast twice that of highest frequency occurring in the object.
This minimum required frequency is referred to as Nyquist sampling frequency (fs):
fs =2*fmax
This can also be stated as that our sampling interval should be no larger than half the cycle interval. This maximum required the sampling interval is called Nyquist sampling interval Δxs:
Δxs = Δxcycle/2
Where Δxcycle=1/fmax
Methods of Antialiasing (AA) –Aliasing is removed using four methods: Using high-resolution display, Post filtering (Supersampling), Pre-filtering (Area Sampling), Pixel phasing. These are explained as following below.
Using high-resolution display:One way to reduce aliasing effect and increase sampling rate is to simply display objects at a higher resolution. Using high resolution, the jaggies become so small that they become indistinguishable by the human eye. Hence, jagged edges get blurred out and edges appear smooth.Practical applications:For example retina displays in Apple devices, OLED displays have high pixel density due to which jaggies formed are so small that they blurred and indistinguishable by our eyes.Post filtering (Supersampling):In this method, we are increasing the sampling resolution by treating the screen as if it’s made of a much more fine grid, due to which the effective pixel size is reduced. But the screen resolution remains the same. Now, intensity from each subpixel is calculated and average intensity of the pixel is found from the average of intensities of subpixels. Thus we do sampling at higher resolution and display the image at lower resolution or resolution of the screen, hence this technique is called supersampling. This method is also known as post filtration as this procedure is done after generating the rasterized image.Practical applications:In gaming, SSAA (Supersample Antialiasing) or FSAA (full-scene antialiasing) is used to create best image quality. It is often called the pure AA and hence is very slow and has a very high computational cost. This technique was widely used in early days when better AA techniques were not available. Different modes of SSAA available are: 2X, 4X, 8X, etc. denoting that sampling is done x times (more than) the current resolution.A better style of AA is MSAA (multisampling Antialiasing) which is a faster and approximate style of supersampling AA.It has lesser computational cost. Better and sophisticated supersampling techniques are developed by graphics card companies like CSAA by NVIDIA and CFAA by AMD.Pre-filtering (Area Sampling):In area sampling, pixel intensities are calculated proportional to areas of overlap of each pixel with objects to be displayed. Here pixel color is computed based on the overlap of scene’s objects with a pixel area.For example: Suppose, a line passes through two pixels. The pixel covering bigger portion(90%) of line displays 90% intensity while less area(10%) covering pixel displays 10-15% intensity. If pixel area overlaps with different color areas, then the final pixel color is taken as an average of colors of the overlap area. This method is also known as pre-filtering as this procedure is done BEFORE generating the rasterized image. It’s done using some graphics primitive algorithms.Pixel phasing:It’s a technique to remove aliasing. Here pixel positions are shifted to nearly approximate positions near object geometry. Some systems allow the size of individual pixels to be adjusted for distributing intensities which is helpful in pixel phasing.
Using high-resolution display:One way to reduce aliasing effect and increase sampling rate is to simply display objects at a higher resolution. Using high resolution, the jaggies become so small that they become indistinguishable by the human eye. Hence, jagged edges get blurred out and edges appear smooth.Practical applications:For example retina displays in Apple devices, OLED displays have high pixel density due to which jaggies formed are so small that they blurred and indistinguishable by our eyes.
Practical applications:For example retina displays in Apple devices, OLED displays have high pixel density due to which jaggies formed are so small that they blurred and indistinguishable by our eyes.
Post filtering (Supersampling):In this method, we are increasing the sampling resolution by treating the screen as if it’s made of a much more fine grid, due to which the effective pixel size is reduced. But the screen resolution remains the same. Now, intensity from each subpixel is calculated and average intensity of the pixel is found from the average of intensities of subpixels. Thus we do sampling at higher resolution and display the image at lower resolution or resolution of the screen, hence this technique is called supersampling. This method is also known as post filtration as this procedure is done after generating the rasterized image.Practical applications:In gaming, SSAA (Supersample Antialiasing) or FSAA (full-scene antialiasing) is used to create best image quality. It is often called the pure AA and hence is very slow and has a very high computational cost. This technique was widely used in early days when better AA techniques were not available. Different modes of SSAA available are: 2X, 4X, 8X, etc. denoting that sampling is done x times (more than) the current resolution.A better style of AA is MSAA (multisampling Antialiasing) which is a faster and approximate style of supersampling AA.It has lesser computational cost. Better and sophisticated supersampling techniques are developed by graphics card companies like CSAA by NVIDIA and CFAA by AMD.
Practical applications:In gaming, SSAA (Supersample Antialiasing) or FSAA (full-scene antialiasing) is used to create best image quality. It is often called the pure AA and hence is very slow and has a very high computational cost. This technique was widely used in early days when better AA techniques were not available. Different modes of SSAA available are: 2X, 4X, 8X, etc. denoting that sampling is done x times (more than) the current resolution.
A better style of AA is MSAA (multisampling Antialiasing) which is a faster and approximate style of supersampling AA.It has lesser computational cost. Better and sophisticated supersampling techniques are developed by graphics card companies like CSAA by NVIDIA and CFAA by AMD.
Pre-filtering (Area Sampling):In area sampling, pixel intensities are calculated proportional to areas of overlap of each pixel with objects to be displayed. Here pixel color is computed based on the overlap of scene’s objects with a pixel area.For example: Suppose, a line passes through two pixels. The pixel covering bigger portion(90%) of line displays 90% intensity while less area(10%) covering pixel displays 10-15% intensity. If pixel area overlaps with different color areas, then the final pixel color is taken as an average of colors of the overlap area. This method is also known as pre-filtering as this procedure is done BEFORE generating the rasterized image. It’s done using some graphics primitive algorithms.
Pixel phasing:It’s a technique to remove aliasing. Here pixel positions are shifted to nearly approximate positions near object geometry. Some systems allow the size of individual pixels to be adjusted for distributing intensities which is helpful in pixel phasing.
Other Applications of antialiasing techniques:
Compensating for line intensity differences:When a horizontal line and a diagonal line plotted on the raster display, the number of pixels required to display both lines is same, even though the diagonal line is 1.414 times larger than the horizontal line. This leads to a decrease in the intensity of the longer line. To compensate for this decrease in intensity, the intensity of pixels is assigned according to the length of line using anti-aliasing techniques.Anti-aliasing area boundaries:Anti-aliasing concepts can also be applied to remove jaggies along area boundaries. These procedures can be applied to scanline algorithms to smoothen out area boundaries .if repositioning of pixels is possible then pixel positions are adjusted to positions closer to area boundaries. Other methods adjust pixel intensity at a boundary position according to the percent of pixel area inside the boundary. These methods effectively smoothen out area boundaries.
Compensating for line intensity differences:When a horizontal line and a diagonal line plotted on the raster display, the number of pixels required to display both lines is same, even though the diagonal line is 1.414 times larger than the horizontal line. This leads to a decrease in the intensity of the longer line. To compensate for this decrease in intensity, the intensity of pixels is assigned according to the length of line using anti-aliasing techniques.
Anti-aliasing area boundaries:Anti-aliasing concepts can also be applied to remove jaggies along area boundaries. These procedures can be applied to scanline algorithms to smoothen out area boundaries .if repositioning of pixels is possible then pixel positions are adjusted to positions closer to area boundaries. Other methods adjust pixel intensity at a boundary position according to the percent of pixel area inside the boundary. These methods effectively smoothen out area boundaries.
computer-graphics
Technical Scripter 2018
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Jul, 2022"
},
{
"code": null,
"e": 553,
"s": 53,
"text": "Antialiasing is a technique used in computer graphics to remove the aliasing effect. The aliasing effect is the appearance of jagged edges or “jaggies” in a rasterized image (an image rendered using pixels). The problem of jagged edges technically occurs due to distortion of the image when scan conversion is done with sampling at a low frequency, which is also known as Undersampling. Aliasing occurs when real-world objects which comprise of smooth, continuous curves are rasterized using pixels."
},
{
"code": null,
"e": 876,
"s": 553,
"text": "Cause of anti-aliasing is Undersampling. Undersampling results in loss of information of the picture. Undersampling occurs when sampling is done at a frequency lower than Nyquist sampling frequency. To avoid this loss, we need to have our sampling frequency atleast twice that of highest frequency occurring in the object."
},
{
"code": null,
"e": 959,
"s": 876,
"text": "This minimum required frequency is referred to as Nyquist sampling frequency (fs):"
},
{
"code": null,
"e": 971,
"s": 959,
"text": "fs =2*fmax "
},
{
"code": null,
"e": 1160,
"s": 971,
"text": "This can also be stated as that our sampling interval should be no larger than half the cycle interval. This maximum required the sampling interval is called Nyquist sampling interval Δxs:"
},
{
"code": null,
"e": 1198,
"s": 1160,
"text": "Δxs = Δxcycle/2\nWhere Δxcycle=1/fmax "
},
{
"code": null,
"e": 1417,
"s": 1198,
"text": "Methods of Antialiasing (AA) –Aliasing is removed using four methods: Using high-resolution display, Post filtering (Supersampling), Pre-filtering (Area Sampling), Pixel phasing. These are explained as following below."
},
{
"code": null,
"e": 4302,
"s": 1417,
"text": "Using high-resolution display:One way to reduce aliasing effect and increase sampling rate is to simply display objects at a higher resolution. Using high resolution, the jaggies become so small that they become indistinguishable by the human eye. Hence, jagged edges get blurred out and edges appear smooth.Practical applications:For example retina displays in Apple devices, OLED displays have high pixel density due to which jaggies formed are so small that they blurred and indistinguishable by our eyes.Post filtering (Supersampling):In this method, we are increasing the sampling resolution by treating the screen as if it’s made of a much more fine grid, due to which the effective pixel size is reduced. But the screen resolution remains the same. Now, intensity from each subpixel is calculated and average intensity of the pixel is found from the average of intensities of subpixels. Thus we do sampling at higher resolution and display the image at lower resolution or resolution of the screen, hence this technique is called supersampling. This method is also known as post filtration as this procedure is done after generating the rasterized image.Practical applications:In gaming, SSAA (Supersample Antialiasing) or FSAA (full-scene antialiasing) is used to create best image quality. It is often called the pure AA and hence is very slow and has a very high computational cost. This technique was widely used in early days when better AA techniques were not available. Different modes of SSAA available are: 2X, 4X, 8X, etc. denoting that sampling is done x times (more than) the current resolution.A better style of AA is MSAA (multisampling Antialiasing) which is a faster and approximate style of supersampling AA.It has lesser computational cost. Better and sophisticated supersampling techniques are developed by graphics card companies like CSAA by NVIDIA and CFAA by AMD.Pre-filtering (Area Sampling):In area sampling, pixel intensities are calculated proportional to areas of overlap of each pixel with objects to be displayed. Here pixel color is computed based on the overlap of scene’s objects with a pixel area.For example: Suppose, a line passes through two pixels. The pixel covering bigger portion(90%) of line displays 90% intensity while less area(10%) covering pixel displays 10-15% intensity. If pixel area overlaps with different color areas, then the final pixel color is taken as an average of colors of the overlap area. This method is also known as pre-filtering as this procedure is done BEFORE generating the rasterized image. It’s done using some graphics primitive algorithms.Pixel phasing:It’s a technique to remove aliasing. Here pixel positions are shifted to nearly approximate positions near object geometry. Some systems allow the size of individual pixels to be adjusted for distributing intensities which is helpful in pixel phasing."
},
{
"code": null,
"e": 4811,
"s": 4302,
"text": "Using high-resolution display:One way to reduce aliasing effect and increase sampling rate is to simply display objects at a higher resolution. Using high resolution, the jaggies become so small that they become indistinguishable by the human eye. Hence, jagged edges get blurred out and edges appear smooth.Practical applications:For example retina displays in Apple devices, OLED displays have high pixel density due to which jaggies formed are so small that they blurred and indistinguishable by our eyes."
},
{
"code": null,
"e": 5012,
"s": 4811,
"text": "Practical applications:For example retina displays in Apple devices, OLED displays have high pixel density due to which jaggies formed are so small that they blurred and indistinguishable by our eyes."
},
{
"code": null,
"e": 6398,
"s": 5012,
"text": "Post filtering (Supersampling):In this method, we are increasing the sampling resolution by treating the screen as if it’s made of a much more fine grid, due to which the effective pixel size is reduced. But the screen resolution remains the same. Now, intensity from each subpixel is calculated and average intensity of the pixel is found from the average of intensities of subpixels. Thus we do sampling at higher resolution and display the image at lower resolution or resolution of the screen, hence this technique is called supersampling. This method is also known as post filtration as this procedure is done after generating the rasterized image.Practical applications:In gaming, SSAA (Supersample Antialiasing) or FSAA (full-scene antialiasing) is used to create best image quality. It is often called the pure AA and hence is very slow and has a very high computational cost. This technique was widely used in early days when better AA techniques were not available. Different modes of SSAA available are: 2X, 4X, 8X, etc. denoting that sampling is done x times (more than) the current resolution.A better style of AA is MSAA (multisampling Antialiasing) which is a faster and approximate style of supersampling AA.It has lesser computational cost. Better and sophisticated supersampling techniques are developed by graphics card companies like CSAA by NVIDIA and CFAA by AMD."
},
{
"code": null,
"e": 6852,
"s": 6398,
"text": "Practical applications:In gaming, SSAA (Supersample Antialiasing) or FSAA (full-scene antialiasing) is used to create best image quality. It is often called the pure AA and hence is very slow and has a very high computational cost. This technique was widely used in early days when better AA techniques were not available. Different modes of SSAA available are: 2X, 4X, 8X, etc. denoting that sampling is done x times (more than) the current resolution."
},
{
"code": null,
"e": 7132,
"s": 6852,
"text": "A better style of AA is MSAA (multisampling Antialiasing) which is a faster and approximate style of supersampling AA.It has lesser computational cost. Better and sophisticated supersampling techniques are developed by graphics card companies like CSAA by NVIDIA and CFAA by AMD."
},
{
"code": null,
"e": 7859,
"s": 7132,
"text": "Pre-filtering (Area Sampling):In area sampling, pixel intensities are calculated proportional to areas of overlap of each pixel with objects to be displayed. Here pixel color is computed based on the overlap of scene’s objects with a pixel area.For example: Suppose, a line passes through two pixels. The pixel covering bigger portion(90%) of line displays 90% intensity while less area(10%) covering pixel displays 10-15% intensity. If pixel area overlaps with different color areas, then the final pixel color is taken as an average of colors of the overlap area. This method is also known as pre-filtering as this procedure is done BEFORE generating the rasterized image. It’s done using some graphics primitive algorithms."
},
{
"code": null,
"e": 8125,
"s": 7859,
"text": "Pixel phasing:It’s a technique to remove aliasing. Here pixel positions are shifted to nearly approximate positions near object geometry. Some systems allow the size of individual pixels to be adjusted for distributing intensities which is helpful in pixel phasing."
},
{
"code": null,
"e": 8172,
"s": 8125,
"text": "Other Applications of antialiasing techniques:"
},
{
"code": null,
"e": 9127,
"s": 8172,
"text": "Compensating for line intensity differences:When a horizontal line and a diagonal line plotted on the raster display, the number of pixels required to display both lines is same, even though the diagonal line is 1.414 times larger than the horizontal line. This leads to a decrease in the intensity of the longer line. To compensate for this decrease in intensity, the intensity of pixels is assigned according to the length of line using anti-aliasing techniques.Anti-aliasing area boundaries:Anti-aliasing concepts can also be applied to remove jaggies along area boundaries. These procedures can be applied to scanline algorithms to smoothen out area boundaries .if repositioning of pixels is possible then pixel positions are adjusted to positions closer to area boundaries. Other methods adjust pixel intensity at a boundary position according to the percent of pixel area inside the boundary. These methods effectively smoothen out area boundaries."
},
{
"code": null,
"e": 9592,
"s": 9127,
"text": "Compensating for line intensity differences:When a horizontal line and a diagonal line plotted on the raster display, the number of pixels required to display both lines is same, even though the diagonal line is 1.414 times larger than the horizontal line. This leads to a decrease in the intensity of the longer line. To compensate for this decrease in intensity, the intensity of pixels is assigned according to the length of line using anti-aliasing techniques."
},
{
"code": null,
"e": 10083,
"s": 9592,
"text": "Anti-aliasing area boundaries:Anti-aliasing concepts can also be applied to remove jaggies along area boundaries. These procedures can be applied to scanline algorithms to smoothen out area boundaries .if repositioning of pixels is possible then pixel positions are adjusted to positions closer to area boundaries. Other methods adjust pixel intensity at a boundary position according to the percent of pixel area inside the boundary. These methods effectively smoothen out area boundaries."
},
{
"code": null,
"e": 10101,
"s": 10083,
"text": "computer-graphics"
},
{
"code": null,
"e": 10125,
"s": 10101,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 10144,
"s": 10125,
"text": "Technical Scripter"
}
] |
Python Program For Finding The Length Of Longest Palindrome List In A Linked List Using O(1) Extra Space | 18 Apr, 2022
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples:
Input : List = 2->3->7->3->2->12->24
Output : 5
The longest palindrome list is 2->3->7->3->2
Input : List = 12->4->4->3->14
Output : 2
The longest palindrome list is 4->4
A simple solution could be to copy linked list content to array and then find the longest palindromic subarray in the array, but this solution is not allowed as it requires extra space.The idea is based on iterative linked list reverse process. We iterate through the given a linked list and one by one reverse every prefix of the linked list from the left. After reversing a prefix, we find the longest common list beginning from reversed prefix and the list after the reversed prefix. Below is the implementation of the above idea.
Python
# Python program to find longest palindrome# sublist in a list in O(1) time. # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # function for counting the common elementsdef countCommon(a, b) : count = 0 # loop to count common in the list starting # from node a and b while ( a != None and b != None ) : # increment the count for same values if (a.data == b.data) : count = count + 1 else: break a = a.next b = b.next return count # Returns length of the longest palindrome# sublist in given listdef maxPalindrome(head) : result = 0 prev = None curr = head # loop till the end of the linked list while (curr != None) : # The sublist from head to current # reversed. next = curr.next curr.next = prev # check for odd length # palindrome by finding # longest common list elements # beginning from prev and # from next (We exclude curr) result = max(result, 2 * countCommon(prev, next) + 1) # check for even length palindrome # by finding longest common list elements # beginning from curr and from next result = max(result, 2 * countCommon(curr, next)) # update prev and curr for next iteration prev = curr curr = next return result # Utility function to create a new list nodedef newNode(key) : temp = Node(0) temp.data = key temp.next = None return temp # Driver code # Let us create a linked lists to test# the functions# Created list is a: 2->4->3->4->2->15head = newNode(2)head.next = newNode(4)head.next.next = newNode(3)head.next.next.next = newNode(4)head.next.next.next.next = newNode(2)head.next.next.next.next.next = newNode(15) print(maxPalindrome(head)) # This code is contributed by Arnab Kundu
Output :
5
Time Complexity : O(n2)Note that the above code modifies the given linked list and may not work if modifications to the linked list are not allowed. However, we can finally do one more reverse to get an original list back. Please refer complete article on Length of longest palindrome list in a linked list using O(1) extra space for more details!
sumitgumber28
Accolite
Microsoft
palindrome
Linked List
Python Programs
Accolite
Microsoft
Linked List
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 141,
"s": 28,
"text": "Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: "
},
{
"code": null,
"e": 315,
"s": 141,
"text": "Input : List = 2->3->7->3->2->12->24\nOutput : 5\nThe longest palindrome list is 2->3->7->3->2\n\nInput : List = 12->4->4->3->14\nOutput : 2\nThe longest palindrome list is 4->4"
},
{
"code": null,
"e": 852,
"s": 317,
"text": "A simple solution could be to copy linked list content to array and then find the longest palindromic subarray in the array, but this solution is not allowed as it requires extra space.The idea is based on iterative linked list reverse process. We iterate through the given a linked list and one by one reverse every prefix of the linked list from the left. After reversing a prefix, we find the longest common list beginning from reversed prefix and the list after the reversed prefix. Below is the implementation of the above idea. "
},
{
"code": null,
"e": 859,
"s": 852,
"text": "Python"
},
{
"code": "# Python program to find longest palindrome# sublist in a list in O(1) time. # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # function for counting the common elementsdef countCommon(a, b) : count = 0 # loop to count common in the list starting # from node a and b while ( a != None and b != None ) : # increment the count for same values if (a.data == b.data) : count = count + 1 else: break a = a.next b = b.next return count # Returns length of the longest palindrome# sublist in given listdef maxPalindrome(head) : result = 0 prev = None curr = head # loop till the end of the linked list while (curr != None) : # The sublist from head to current # reversed. next = curr.next curr.next = prev # check for odd length # palindrome by finding # longest common list elements # beginning from prev and # from next (We exclude curr) result = max(result, 2 * countCommon(prev, next) + 1) # check for even length palindrome # by finding longest common list elements # beginning from curr and from next result = max(result, 2 * countCommon(curr, next)) # update prev and curr for next iteration prev = curr curr = next return result # Utility function to create a new list nodedef newNode(key) : temp = Node(0) temp.data = key temp.next = None return temp # Driver code # Let us create a linked lists to test# the functions# Created list is a: 2->4->3->4->2->15head = newNode(2)head.next = newNode(4)head.next.next = newNode(3)head.next.next.next = newNode(4)head.next.next.next.next = newNode(2)head.next.next.next.next.next = newNode(15) print(maxPalindrome(head)) # This code is contributed by Arnab Kundu",
"e": 2811,
"s": 859,
"text": null
},
{
"code": null,
"e": 2821,
"s": 2811,
"text": "Output : "
},
{
"code": null,
"e": 2823,
"s": 2821,
"text": "5"
},
{
"code": null,
"e": 3171,
"s": 2823,
"text": "Time Complexity : O(n2)Note that the above code modifies the given linked list and may not work if modifications to the linked list are not allowed. However, we can finally do one more reverse to get an original list back. Please refer complete article on Length of longest palindrome list in a linked list using O(1) extra space for more details!"
},
{
"code": null,
"e": 3185,
"s": 3171,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3194,
"s": 3185,
"text": "Accolite"
},
{
"code": null,
"e": 3204,
"s": 3194,
"text": "Microsoft"
},
{
"code": null,
"e": 3215,
"s": 3204,
"text": "palindrome"
},
{
"code": null,
"e": 3227,
"s": 3215,
"text": "Linked List"
},
{
"code": null,
"e": 3243,
"s": 3227,
"text": "Python Programs"
},
{
"code": null,
"e": 3252,
"s": 3243,
"text": "Accolite"
},
{
"code": null,
"e": 3262,
"s": 3252,
"text": "Microsoft"
},
{
"code": null,
"e": 3274,
"s": 3262,
"text": "Linked List"
},
{
"code": null,
"e": 3285,
"s": 3274,
"text": "palindrome"
}
] |
Why FIRST and FOLLOW in Compiler Design? | 16 Nov, 2021
Why FIRST?We saw the need of backtrack in the previous article of on Introduction to Syntax Analysis, which is really a complex process to implement. There can be easier way to sort out this problem:
If the compiler would have come to know in advance, that what is the “first character of the string produced when a production rule is applied”, and comparing it to the current character or token in the input string it sees, it can wisely take decision on which production rule to apply.
Let’s take the same grammar from the previous article:
S -> cAd
A -> bc|a
And the input string is “cad”.
Thus, in the example above, if it knew that after reading character ‘c’ in the input string and applying S->cAd, next character in the input string is ‘a’, then it would have ignored the production rule A->bc (because ‘b’ is the first character of the string produced by this production rule, not ‘a’ ), and directly use the production rule A->a (because ‘a’ is the first character of the string produced by this production rule, and is same as the current character of the input string which is also ‘a’).Hence it is validated that if the compiler/parser knows about first character of the string that can be obtained by applying a production rule, then it can wisely apply the correct production rule to get the correct syntax tree for the given input string.
Why FOLLOW?The parser faces one more problem. Let us consider below grammar to understand this problem.
A -> aBb
B -> c | ε
And suppose the input string is “ab” to parse.
As the first character in the input is a, the parser applies the rule A->aBb.
A
/ | \
a B b
Now the parser checks for the second character of the input string which is b, and the Non-Terminal to derive is B, but the parser can’t get any string derivable from B that contains b as first character.But the Grammar does contain a production rule B -> ε, if that is applied then B will vanish, and the parser gets the input “ab”, as shown below. But the parser can apply it only when it knows that the character that follows B in the production rule is same as the current character in the input.
In RHS of A -> aBb, b follows Non-Terminal B, i.e. FOLLOW(B) = {b}, and the current input character read is also b. Hence the parser applies this rule. And it is able to get the string “ab” from the given grammar.
A A
/ | \ / \
a B b => a b
|
ε
So FOLLOW can make a Non-terminal vanish out if needed to generate the string from the parse tree.
The conclusions is, we need to find FIRST and FOLLOW sets for a given grammar so that the parser can properly apply the needed rule at the correct position.
In the next article, we will discuss formal definitions of FIRST and FOLLOW, and some easy rules to compute these sets.
Quiz on Syntax Analysis
This article is compiled by Vaibhav Bajpai. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Kumar Neelabh
vaibhavsinghtanwar
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 252,
"s": 52,
"text": "Why FIRST?We saw the need of backtrack in the previous article of on Introduction to Syntax Analysis, which is really a complex process to implement. There can be easier way to sort out this problem:"
},
{
"code": null,
"e": 540,
"s": 252,
"text": "If the compiler would have come to know in advance, that what is the “first character of the string produced when a production rule is applied”, and comparing it to the current character or token in the input string it sees, it can wisely take decision on which production rule to apply."
},
{
"code": null,
"e": 595,
"s": 540,
"text": "Let’s take the same grammar from the previous article:"
},
{
"code": null,
"e": 647,
"s": 595,
"text": "S -> cAd\nA -> bc|a \nAnd the input string is “cad”. "
},
{
"code": null,
"e": 1409,
"s": 647,
"text": "Thus, in the example above, if it knew that after reading character ‘c’ in the input string and applying S->cAd, next character in the input string is ‘a’, then it would have ignored the production rule A->bc (because ‘b’ is the first character of the string produced by this production rule, not ‘a’ ), and directly use the production rule A->a (because ‘a’ is the first character of the string produced by this production rule, and is same as the current character of the input string which is also ‘a’).Hence it is validated that if the compiler/parser knows about first character of the string that can be obtained by applying a production rule, then it can wisely apply the correct production rule to get the correct syntax tree for the given input string."
},
{
"code": null,
"e": 1513,
"s": 1409,
"text": "Why FOLLOW?The parser faces one more problem. Let us consider below grammar to understand this problem."
},
{
"code": null,
"e": 1584,
"s": 1513,
"text": " A -> aBb\n B -> c | ε\n And suppose the input string is “ab” to parse. "
},
{
"code": null,
"e": 1662,
"s": 1584,
"text": "As the first character in the input is a, the parser applies the rule A->aBb."
},
{
"code": null,
"e": 1705,
"s": 1662,
"text": " A\n / | \\\n a B b"
},
{
"code": null,
"e": 2206,
"s": 1705,
"text": "Now the parser checks for the second character of the input string which is b, and the Non-Terminal to derive is B, but the parser can’t get any string derivable from B that contains b as first character.But the Grammar does contain a production rule B -> ε, if that is applied then B will vanish, and the parser gets the input “ab”, as shown below. But the parser can apply it only when it knows that the character that follows B in the production rule is same as the current character in the input."
},
{
"code": null,
"e": 2420,
"s": 2206,
"text": "In RHS of A -> aBb, b follows Non-Terminal B, i.e. FOLLOW(B) = {b}, and the current input character read is also b. Hence the parser applies this rule. And it is able to get the string “ab” from the given grammar."
},
{
"code": null,
"e": 2609,
"s": 2420,
"text": " A A\n / | \\ / \\ \n a B b => a b \n |\n ε "
},
{
"code": null,
"e": 2708,
"s": 2609,
"text": "So FOLLOW can make a Non-terminal vanish out if needed to generate the string from the parse tree."
},
{
"code": null,
"e": 2867,
"s": 2710,
"text": "The conclusions is, we need to find FIRST and FOLLOW sets for a given grammar so that the parser can properly apply the needed rule at the correct position."
},
{
"code": null,
"e": 2987,
"s": 2867,
"text": "In the next article, we will discuss formal definitions of FIRST and FOLLOW, and some easy rules to compute these sets."
},
{
"code": null,
"e": 3011,
"s": 2987,
"text": "Quiz on Syntax Analysis"
},
{
"code": null,
"e": 3179,
"s": 3011,
"text": "This article is compiled by Vaibhav Bajpai. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 3193,
"s": 3179,
"text": "Kumar Neelabh"
},
{
"code": null,
"e": 3212,
"s": 3193,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 3228,
"s": 3212,
"text": "Compiler Design"
},
{
"code": null,
"e": 3236,
"s": 3228,
"text": "GATE CS"
}
] |
Zend Framework - Service Manager | The Zend Framework includes a powerful service locator pattern implementation called zend-servicemanager. Zend framework extensively uses the service manager for all its functionalities. The Service Manager provides a high-level abstraction for the Zend Framework. It also integrates nicely with all the other components of the Zend Framework.
The Service Manager component can be installed using the composer tool.
composer require zendframework/zend-servicemanager
First, all the services need to be registered into the service manager. Once the services are registered into the server manager system, it can be accessed at any time with minimal efforts. The service manager provides a lot of options to register the service. A simple example is as follows −
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\Factory\InvokableFactory;
use stdClass;
$serviceManager = new ServiceManager([
'factories' => [stdClass::class => InvokableFactory::class,],
]);
The above code registers the stdClass into the system using the Factory option. Now, we can get an instance of the stdClass at any time using the get() method of the service manager as shown below.
use Zend\ServiceManager\ServiceManager;
$object = $serviceManager->get(stdClass::class);
The get() method shares the retrieved object and so, the object returned by calling the get() method multiple times is one and the same instance. To get a different instance every time, the service manager provides another method, which is the build() method.
use Zend\ServiceManager\ServiceManager;
$a = $serviceManager->build(stdClass::class);
$b = $serviceManager->build(stdClass::class);
The service manager provides a set of methods to register a component. Some of the most important methods are as given below −
Factory method
Abstract factory method
Initializer method
Delegator factory method
We will discuss each of these in detail in the upcoming chapters.
A factory is basically any callable or any class that implements the FactoryInterface (Zend\ServiceManager\Factory\FactoryInterface).
The FactoryInterface has a single method −
public function __invoke(ContainerInterface $container, $requestedName, array
$options = null)
The arguments details of the FactoryInterface is as follows −
container (ContainerInterface) − It is the base interface of the ServiceManager. It provides an option to get other services.
container (ContainerInterface) − It is the base interface of the ServiceManager. It provides an option to get other services.
requestedName − It is the service name.
requestedName − It is the service name.
options − It gives additional options needed for the service.
options − It gives additional options needed for the service.
Let us create a simple class implementing the FactoryInterface and see how to register the class.
use stdClass;
class Test {
public function __construct(stdClass $sc) {
// use $sc
}
}
The Test class depends on the stdClass.
class TestFactory implements FactoryInterface {
public function __invoke(ContainerInterface $container, $requestedName,
array $options = null) {
$dep = $container->get(stdClass::class);
return new Test($dep);
}
}
The TestFactory uses a container to retrieve the stdClass, creates the instance of the Test class, and returns it.
Let us now understand how to register and use the Zend Framework.
serviceManager $sc = new ServiceManager([
'factories' => [stdClass::class => InvokableFactory::class,
Test::class => TestFactory::class]
]);
$test = $sc->get(Test::class);
The service manager provides a special factory called InvokableFactory to retrieve any class which has no dependency. For example, the stdClass can be configured using the InvokableFactory since the stdClass does not depend on any other class.
serviceManager $sc = new ServiceManager([
'factories' => [stdClass::class => InvokableFactory::class]
]);
$stdC = $sc->get(stdClass::class);
Another way to retrieve an object without implementing the FactoryInterface or using the InvokableFactory is using the inline method as given below.
$serviceManager = new ServiceManager([
'factories' => [
stdClass::class => InvokableFactory::class,
Test::class => function(ContainerInterface $container, $requestedName) {
$dep = $container->get(stdClass::class);
return new Test($dep);
},
],
]);
Sometimes, we may need to create objects, which we come to know only at runtime. This situation can be handled using the AbstractFactoryInterface, which is derived from the FactoryInterface.
The AbstractFactoryInterface defines a method to check whether the object can be created at the requested instance or not. If object creation is possible, it will create the object using the __invokemethod of the FactoryInterface and return it.
The signature of the AbstractFactoryInterface is as follows −
public function canCreate(ContainerInterface $container, $requestedName)
The Initializer Method is a special option to inject additional dependency for already created services. It implements the InitializerInterface and the signature of the sole method available is as follows −
public function(ContainerInterface $container, $instance)
function(ContainerInterface $container, $instance) {
if (! $instance instanceof EventManagerAwareInterface) {
return;
}
$instance->setEventManager($container->get(EventManager::class));
}
In the above example, the method checks whether the instance is of type EventManagerAwareInterface. If it is of type EventManagerAwareInterface, it sets the event manager object, otherwise not. Since, the method may or may not set the dependency, it is not reliable and produces many runtime issues.
Zend Framework supports delegators pattern through DelegatorFactoryInterface. It can be used to decorate the service.
The signature of this function is as follows −
public function __invoke(ContainerInterface $container,
$name, callable $callback, array $options = null
);
Here, the $callback is responsible for decorating the service instance.
Lazy service is one of those services which will not be fully initialized at the time of creation. They are just referenced and only initialized when it is really needed. One of the best example is database connection, which may not be needed in all places. It is an expensive resource as well as have time-consuming process to create. Zend framework provides LazyServiceFactory derived from the DelegatorFactoryInterface, which can produce lazy service with the help of the Delegator concept and a 3rd party proxy manager, which is called as the ocramius proxy manager.
Plugin Manager extends the service manager and provides additional functionality like instance validation. Zend Framework extensively uses the plugin manager.
For example, all the validation services come under the ValidationPluginManager.
The service manager provides some options to extend the feature of a service manager. They are shared, shared_by_default and aliases. As we discussed earlier, retrieved objects are shared among requested objects by default and we can use the build() method to get a distinct object. We can also use the shared option to specify which service to be shared. The shared_by_default is same as the shared feature, except that it applies for all services.
$serviceManager = new ServiceManager([
'factories' => [
stdClass::class => InvokableFactory::class
],
'shared' => [
stdClass::class => false // will not be shared
],
'shared_by_default' => false, // will not be shared and applies to all service
]);
The aliases option can be used to provide an alternative name to the registered services. This have both advantages and disadvantages. On the positive side, we can provide alternative short names for a service. But, at the same time, the name may become out of context and introduce bugs.
aliases' => ['std' => stdClass::class, 'standard' => 'std']
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2656,
"s": 2312,
"text": "The Zend Framework includes a powerful service locator pattern implementation called zend-servicemanager. Zend framework extensively uses the service manager for all its functionalities. The Service Manager provides a high-level abstraction for the Zend Framework. It also integrates nicely with all the other components of the Zend Framework."
},
{
"code": null,
"e": 2728,
"s": 2656,
"text": "The Service Manager component can be installed using the composer tool."
},
{
"code": null,
"e": 2780,
"s": 2728,
"text": "composer require zendframework/zend-servicemanager\n"
},
{
"code": null,
"e": 3074,
"s": 2780,
"text": "First, all the services need to be registered into the service manager. Once the services are registered into the server manager system, it can be accessed at any time with minimal efforts. The service manager provides a lot of options to register the service. A simple example is as follows −"
},
{
"code": null,
"e": 3292,
"s": 3074,
"text": "use Zend\\ServiceManager\\ServiceManager; \nuse Zend\\ServiceManager\\Factory\\InvokableFactory; \nuse stdClass; \n$serviceManager = new ServiceManager([ \n 'factories' => [stdClass::class => InvokableFactory::class,], \n]);"
},
{
"code": null,
"e": 3490,
"s": 3292,
"text": "The above code registers the stdClass into the system using the Factory option. Now, we can get an instance of the stdClass at any time using the get() method of the service manager as shown below."
},
{
"code": null,
"e": 3582,
"s": 3490,
"text": "use Zend\\ServiceManager\\ServiceManager; \n$object = $serviceManager->get(stdClass::class);\n"
},
{
"code": null,
"e": 3842,
"s": 3582,
"text": "The get() method shares the retrieved object and so, the object returned by calling the get() method multiple times is one and the same instance. To get a different instance every time, the service manager provides another method, which is the build() method."
},
{
"code": null,
"e": 3978,
"s": 3842,
"text": "use Zend\\ServiceManager\\ServiceManager; \n$a = $serviceManager->build(stdClass::class); \n$b = $serviceManager->build(stdClass::class);\n"
},
{
"code": null,
"e": 4105,
"s": 3978,
"text": "The service manager provides a set of methods to register a component. Some of the most important methods are as given below −"
},
{
"code": null,
"e": 4120,
"s": 4105,
"text": "Factory method"
},
{
"code": null,
"e": 4144,
"s": 4120,
"text": "Abstract factory method"
},
{
"code": null,
"e": 4163,
"s": 4144,
"text": "Initializer method"
},
{
"code": null,
"e": 4188,
"s": 4163,
"text": "Delegator factory method"
},
{
"code": null,
"e": 4254,
"s": 4188,
"text": "We will discuss each of these in detail in the upcoming chapters."
},
{
"code": null,
"e": 4388,
"s": 4254,
"text": "A factory is basically any callable or any class that implements the FactoryInterface (Zend\\ServiceManager\\Factory\\FactoryInterface)."
},
{
"code": null,
"e": 4431,
"s": 4388,
"text": "The FactoryInterface has a single method −"
},
{
"code": null,
"e": 4531,
"s": 4431,
"text": "public function __invoke(ContainerInterface $container, $requestedName, array \n $options = null)\n"
},
{
"code": null,
"e": 4593,
"s": 4531,
"text": "The arguments details of the FactoryInterface is as follows −"
},
{
"code": null,
"e": 4719,
"s": 4593,
"text": "container (ContainerInterface) − It is the base interface of the ServiceManager. It provides an option to get other services."
},
{
"code": null,
"e": 4845,
"s": 4719,
"text": "container (ContainerInterface) − It is the base interface of the ServiceManager. It provides an option to get other services."
},
{
"code": null,
"e": 4885,
"s": 4845,
"text": "requestedName − It is the service name."
},
{
"code": null,
"e": 4925,
"s": 4885,
"text": "requestedName − It is the service name."
},
{
"code": null,
"e": 4987,
"s": 4925,
"text": "options − It gives additional options needed for the service."
},
{
"code": null,
"e": 5049,
"s": 4987,
"text": "options − It gives additional options needed for the service."
},
{
"code": null,
"e": 5147,
"s": 5049,
"text": "Let us create a simple class implementing the FactoryInterface and see how to register the class."
},
{
"code": null,
"e": 5252,
"s": 5147,
"text": "use stdClass; \nclass Test { \n public function __construct(stdClass $sc) { \n // use $sc \n } \n} "
},
{
"code": null,
"e": 5292,
"s": 5252,
"text": "The Test class depends on the stdClass."
},
{
"code": null,
"e": 5535,
"s": 5292,
"text": "class TestFactory implements FactoryInterface { \n public function __invoke(ContainerInterface $container, $requestedName, \n array $options = null) { \n $dep = $container->get(stdClass::class); \n return new Test($dep); \n } \n}"
},
{
"code": null,
"e": 5650,
"s": 5535,
"text": "The TestFactory uses a container to retrieve the stdClass, creates the instance of the Test class, and returns it."
},
{
"code": null,
"e": 5716,
"s": 5650,
"text": "Let us now understand how to register and use the Zend Framework."
},
{
"code": null,
"e": 5901,
"s": 5716,
"text": "serviceManager $sc = new ServiceManager([ \n 'factories' => [stdClass::class => InvokableFactory::class, \n Test::class => TestFactory::class] \n]); \n$test = $sc->get(Test::class);"
},
{
"code": null,
"e": 6145,
"s": 5901,
"text": "The service manager provides a special factory called InvokableFactory to retrieve any class which has no dependency. For example, the stdClass can be configured using the InvokableFactory since the stdClass does not depend on any other class."
},
{
"code": null,
"e": 6294,
"s": 6145,
"text": "serviceManager $sc = new ServiceManager([ \n 'factories' => [stdClass::class => InvokableFactory::class] \n]); \n$stdC = $sc->get(stdClass::class); "
},
{
"code": null,
"e": 6443,
"s": 6294,
"text": "Another way to retrieve an object without implementing the FactoryInterface or using the InvokableFactory is using the inline method as given below."
},
{
"code": null,
"e": 6740,
"s": 6443,
"text": "$serviceManager = new ServiceManager([ \n 'factories' => [ \n stdClass::class => InvokableFactory::class, \n Test::class => function(ContainerInterface $container, $requestedName) { \n $dep = $container->get(stdClass::class); \n return new Test($dep); \n }, \n ], \n]);"
},
{
"code": null,
"e": 6931,
"s": 6740,
"text": "Sometimes, we may need to create objects, which we come to know only at runtime. This situation can be handled using the AbstractFactoryInterface, which is derived from the FactoryInterface."
},
{
"code": null,
"e": 7176,
"s": 6931,
"text": "The AbstractFactoryInterface defines a method to check whether the object can be created at the requested instance or not. If object creation is possible, it will create the object using the __invokemethod of the FactoryInterface and return it."
},
{
"code": null,
"e": 7238,
"s": 7176,
"text": "The signature of the AbstractFactoryInterface is as follows −"
},
{
"code": null,
"e": 7313,
"s": 7238,
"text": "public function canCreate(ContainerInterface $container, $requestedName) \n"
},
{
"code": null,
"e": 7520,
"s": 7313,
"text": "The Initializer Method is a special option to inject additional dependency for already created services. It implements the InitializerInterface and the signature of the sole method available is as follows −"
},
{
"code": null,
"e": 7789,
"s": 7520,
"text": "public function(ContainerInterface $container, $instance) \nfunction(ContainerInterface $container, $instance) { \n if (! $instance instanceof EventManagerAwareInterface) { \n return; \n } \n $instance->setEventManager($container->get(EventManager::class)); \n} "
},
{
"code": null,
"e": 8089,
"s": 7789,
"text": "In the above example, the method checks whether the instance is of type EventManagerAwareInterface. If it is of type EventManagerAwareInterface, it sets the event manager object, otherwise not. Since, the method may or may not set the dependency, it is not reliable and produces many runtime issues."
},
{
"code": null,
"e": 8207,
"s": 8089,
"text": "Zend Framework supports delegators pattern through DelegatorFactoryInterface. It can be used to decorate the service."
},
{
"code": null,
"e": 8254,
"s": 8207,
"text": "The signature of this function is as follows −"
},
{
"code": null,
"e": 8368,
"s": 8254,
"text": "public function __invoke(ContainerInterface $container, \n $name, callable $callback, array $options = null \n); "
},
{
"code": null,
"e": 8440,
"s": 8368,
"text": "Here, the $callback is responsible for decorating the service instance."
},
{
"code": null,
"e": 9011,
"s": 8440,
"text": "Lazy service is one of those services which will not be fully initialized at the time of creation. They are just referenced and only initialized when it is really needed. One of the best example is database connection, which may not be needed in all places. It is an expensive resource as well as have time-consuming process to create. Zend framework provides LazyServiceFactory derived from the DelegatorFactoryInterface, which can produce lazy service with the help of the Delegator concept and a 3rd party proxy manager, which is called as the ocramius proxy manager."
},
{
"code": null,
"e": 9170,
"s": 9011,
"text": "Plugin Manager extends the service manager and provides additional functionality like instance validation. Zend Framework extensively uses the plugin manager."
},
{
"code": null,
"e": 9251,
"s": 9170,
"text": "For example, all the validation services come under the ValidationPluginManager."
},
{
"code": null,
"e": 9701,
"s": 9251,
"text": "The service manager provides some options to extend the feature of a service manager. They are shared, shared_by_default and aliases. As we discussed earlier, retrieved objects are shared among requested objects by default and we can use the build() method to get a distinct object. We can also use the shared option to specify which service to be shared. The shared_by_default is same as the shared feature, except that it applies for all services."
},
{
"code": null,
"e": 9985,
"s": 9701,
"text": "$serviceManager = new ServiceManager([ \n 'factories' => [ \n stdClass::class => InvokableFactory::class \n ], \n 'shared' => [ \n stdClass::class => false // will not be shared \n ], \n 'shared_by_default' => false, // will not be shared and applies to all service \n]);"
},
{
"code": null,
"e": 10274,
"s": 9985,
"text": "The aliases option can be used to provide an alternative name to the registered services. This have both advantages and disadvantages. On the positive side, we can provide alternative short names for a service. But, at the same time, the name may become out of context and introduce bugs."
},
{
"code": null,
"e": 10336,
"s": 10274,
"text": "aliases' => ['std' => stdClass::class, 'standard' => 'std'] \n"
},
{
"code": null,
"e": 10343,
"s": 10336,
"text": " Print"
},
{
"code": null,
"e": 10354,
"s": 10343,
"text": " Add Notes"
}
] |
ML from Scratch: Linear Regression Model with NumPy | by Aman Sharma | Towards Data Science | In this project, we will see how to create a machine learning model that uses the Multiple Linear Regression algorithm.
The main focus of this project is to explain how linear regression works, and how you can code a linear regression model from scratch using the awesome NumPy module.
Of course, you can create a linear regression model using the scikit-learn with just 3–4 lines of code, but really, coding your own model from scratch is far more awesome than relying on a library that does everything for you while you sit and watch.
Not only that, coding a custom model means you have full control over what the model does and how that model deals with the data that you will be feeding it. This allows for more flexibility during the training process, and you can actually tweak the model to make it more robust and responsive to the real world data as required in the future during re-training or in the production.
In this project, our model will be used to predict the CO2 emissions of a vehicle based on its features such as its engine size, fuel consumption etc.
Let’s start working on the project.
First, we will import the necessary PyData modules.
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline
Now, let us import our data set. The data set contains model-specific fuel consumption ratings and estimated carbon dioxide emissions for new light-duty vehicles for retail sale in Canada.
df = pd.read_csv("FuelConsumptionCo2.csv")print(df.head())
Here’s the link for the data set. I will also share the link to the Github repo containing the Jupyter notebook and the dataset at the end of this project.
Click the link to download the csv file- drive.google.com
Here’s how it looks in my Jupyter notebook:
The following are the columns present in our data set.
MODELYEAR e.g. 2014
MAKE e.g. Acura
MODEL e.g. ILX
VEHICLE CLASS e.g. SUV
ENGINE SIZE e.g. 4.7
CYLINDERS e.g 6
TRANSMISSION e.g. A6
FUEL CONSUMPTION in CITY(L/100 km) e.g. 9.9
FUEL CONSUMPTION in HWY (L/100 km) e.g. 8.9
FUEL CONSUMPTION COMB (L/100 km) e.g. 9.2
CO2 EMISSIONS (g/km) e.g. 182 → low → 0
One of the most important steps in any data science project is pre-processing the data. This involves cleaning the data, typecasting some columns as required, conversion of categorical variables and standardizing/normalizing the data as per the project requirements.
For our project, the first step of the pre-processing is going to be checking whether we need to typecast the data type of any feature/target variable.
print(df.dtypes)
We get the following output:
As we can see, there’s no need to typecast any column.
The second step in our data wrangling process is analyzing whether the features need to be standardized or not. For that, let us have a look at the descriptive analysis of the dataframe.
print(df.describe())
As we can see, all the potential features are of the same order in terms of scales, so we needn’t standardize any feature.
For this project, the features we will be choosing are ENGINESIZE, CYLINDERS & FUELCONSUMPTION_COMB and the target variable is CO2EMISSIONS.
df = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]print(df.head())
Our next step- Checking the number of NaN(null) values in the dataframe.
for i in df.columns: print(df[i].isnull().value_counts())
As we can see, there are are no null values in our dataframe. So the data is perfect for training the model.
First, we will have a look at the correlation of the features and the target variables.
print(df.corr())
This table shows a strong positive correlation between the features and the target variable. Remember, a strong correlation is a good thing for a linear regression model.
Now, let us visualize the plots of different features against the target variable. This will allow us to get an idea whether the features show a linear relation with the target variable or not.
fig, a = plt.subplots(1,3, figsize = (18, 5))a[0].scatter(df['ENGINESIZE'], df['CO2EMISSIONS'], color = 'c')a[0].set_title('Engine Size vs CO2 Emissions')a[0].set_xlabel('Engine Size (L)')a[1].scatter(df['CYLINDERS'], df['CO2EMISSIONS'], color = 'm')a[1].set_title('No. of Cylinders vs CO2 Emissions')a[1].set_xlabel('No. of Cylinders')a[2].scatter(df['FUELCONSUMPTION_COMB'], df['CO2EMISSIONS'], color = 'b')a[2].set_title('Fuel Consumption vs CO2 Emissions')a[2].set_xlabel('Fuel Consumption (L/100km)')fig.text(0.08, 0.5, 'CO2 Emissions', va='center', rotation='vertical')plt.show()
As we can see, the features show a considerable linear relationship with the target. Hence, we can use them for training the model.
Linear regression uses the following mathematical formula for prediction of a dependent variable using an independent variable.
y = wx + b
Here,
y- Dependent variable(s)
x- Dependent variable(s)
w- Weight(s) associated with the independent variable(s)
b- Biases for the given lin-reg equation
The following is the process for developing a linear regression model.
Splitting the data set into training and testing sets. For the sake of simplicity however, we will be skipping this step in our custom model.Assigning random weights and biases to the model and then calculating dependent variable, ŷ on the basis of the random weights and biases.Using a loss function to calculate the total information loss, i.e., the total inaccuracy within out model. In our examples, we will be using the Mean Squared Error (MSE) loss function.Our next step is to reduce the total MSE of our model. For this, we will be using the Stochastic Gradient Descent (SGD) function, which is one of the most popular optimizer algorithms used in regression models. We will discuss the SGD function in detail while coding the optimizer function.We will update the model weights and biases based on our optimizer algorithm, then retrain the model. This is a recurrent process that will keep on repeating until we achieve an optimum model with low information loss.
Splitting the data set into training and testing sets. For the sake of simplicity however, we will be skipping this step in our custom model.
Assigning random weights and biases to the model and then calculating dependent variable, ŷ on the basis of the random weights and biases.
Using a loss function to calculate the total information loss, i.e., the total inaccuracy within out model. In our examples, we will be using the Mean Squared Error (MSE) loss function.
Our next step is to reduce the total MSE of our model. For this, we will be using the Stochastic Gradient Descent (SGD) function, which is one of the most popular optimizer algorithms used in regression models. We will discuss the SGD function in detail while coding the optimizer function.
We will update the model weights and biases based on our optimizer algorithm, then retrain the model. This is a recurrent process that will keep on repeating until we achieve an optimum model with low information loss.
First, let’s cast the features to a NumPy array, features.
features = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']].to_numpy() #Converts the dataframe to numpy arrayprint(features)
Now, let us get cast the target column to a NumPy array, target.
target = df[‘CO2EMISSIONS’].to_numpy() #Converts the dataframe to numpy arrayprint(target)
Since we have 3 dependent variables, we will have 3 weights. Let’s generate array weights of 3 small random weights.
weights = np.random.rand(3) #Generates a numpy array with two small random floatsprint(weights)
Since we have a single target variable, we will have just one bias, b. We will also create an array bias equal to the length of features array having bias b for each element.
b = np.random.rand(1) #Generates a numpy array with a small random floatbias = np.array([b[0] for i in range(len(features))])print(bias)
Now, we will define our model function that uses weights, biases and dependent variables to calculate ŷ.
def linearRegr(features, weights, bias): """Calculates the y_hat predicted values using the given parameters of weights, dependent variables, and biases. Args: -dependant_var: Matrix of dependant variable values -weights: Matrix/array of weights associated with each dependant variable -biases: Biases for the model Returns: -Array/matrix of predicted values """ y_hat = weights.dot(features.transpose()) + np.array([bias[0] for i in range(len(features))]) # Takes the value stored in the bias array and makes an array of length of feature matrix for addition return y_hat
Now, let us run the function once to see the results we’ll get.
y_hat = linearRegr(features, weights, b)print(y_hat)
Now, we will define the MSE function to calculate the total loss of our model.
def meanSqrError(y, y_hat): """Calculates the total mean squared error. Args- y: Array of actual target values y_hat: Array of predicted target values Returns- total mean squared error """ MSE = np.sum((y - y_hat) ** 2) / len(y) return MSE
Let us now calculate the information loss based on the y_hat values we got earlier.
print('Total error- {}'.format(meanSqrError(target, y_hat)))
As we can see, our model is currently massively inaccurate and we need to optimize it.
Now comes the most important step in the linear regression. Formulating the SGD function. This is a slightly advance topic as compared to all the basic functions we have covered up until this point. It requires some knowledge of differential calculus; partial differentiation to be specific. I have tried to explain this in the image below, however, if you don’t get it, I’d strongly suggest you get familiar with the mathematics portion of Machine Learning (Calculus, Statistics and Probability, Linear Algebra) before proceeding any further.
Image source- Adarsh Menon-Medium.com
Once we have calculated the gradients, we will update the parameters as follows.
m = m - α Dm
c = c - α Dc
Here,
E- Total mean squared error
m- Weights associated with features
c- Model bias
y- Array of actual target values
ŷ- Predicted target values
Dm- Partial derivative of E w.r.t. weights m
Dc- Partial derivative of E w.r.t. bias c
α- Learning rate, i.e., size of the step that the optimizer function takes.
Once we have the new updated values of the weights and biases, we will calculate the loss again. We will repeat the process for n epochs, i.e., number of cycles and plot the loss values after each epoch. To keep the code clean, I will create a separate function for calculation of gradients.
def gradient(target, features, weights, bias): """Returns the gradient(slopes) for weights and biases """ m = len(features) target_pred = linearRegr(features, weights, bias) loss = target - target_pred # y-y_hat # Gradient calculation for model bias grad_bias = np.array([-2/m * np.sum(loss)]) grad_weights = np.ones(3) # Gradient calculation for first feature feature_0 = np.array([feature[0] for feature in features]) grad_weights[0] = -2/m * np.sum(loss * feature_0) # Gradient calculation for second feature feature_1 = np.array([feature[1] for feature in features]) grad_weights[1] = -2/m * np.sum(loss * feature_1) # Gradient calculation for third feature feature_2 = np.array([feature[1] for feature in features]) grad_weights[2] = -2/m * np.sum(loss * feature_2) return grad_bias, grad_weights
Now, let us write the SDG function that will return the updated weights and biases so we can formulate our final model.
def stochGradDesMODIFIED(learning_rate, epochs, target, features, weights, bias): """Performs stochastic gradient descent optimization on the model. Args- learning_rate- Size of the step the function will take during optimization epochs- No. of iterations the function will run for on the model target- Actual emission values features- Matrix of dependent variables weights- Weights associated with each feature bias- Model bias Returns- return_dict = {'weights': weights, 'bias': bias[0], 'MSE': total_MSE_new, 'MSE_list': MSE_list} """MSE_list = [] for i in range(epochs): grad_bias, grad_weights = gradient(target, features, weights, bias) weights -= grad_weights * learning_rate bias -= grad_bias * learning_rate new_pred = linearRegr(features, weights, bias) total_MSE_new = meanSqrError(target, new_pred) MSE_list.append(total_MSE_new) return_dict = {'weights': weights, 'bias': bias[0], 'MSE': total_MSE_new, 'MSE_list': MSE_list} return return_dict
Finally, we have the optimizer function for our linear regression model. Let us run the function now and store the values for further use.
model_val = stochGradDesMODIFIED(0.001, 2000, target, features, weights, bias)print("Weights- {}\nBias- {}\nMSE- {}".format(model_val['weights'], model_val['bias'], model_val['MSE']))
The initial MSE was around 65,000 while the current MSE is around 680. We can see from the results that our model has significantly improved.
Finally, we will write the model function that uses the updated model weights and biases to predict the target values.
def LinearRegressionModel(model_val, feature_list): """Predicts the CO2 emission values of the vehicle Args- model_val- This is the dictionary returned by the stockGradDesMODIFIED function. Contains model weights and biases feature_list- An array of the dependent variables Returns- co2_emission- Emission predictions for the given set of features """ co2_emission = np.sum(model_val['weights'] * feature_list) + model_val['bias'] return co2_emission
As a test run, we will now test our model on the following data.
feature_list = [2.0, 4, 8.5]
The actual target value for the data is 196. Let’s see how our model fares.
target_price = 196feature_list = [2.0, 4, 8.5]predicted_price = LinearRegressionModel(model_val, feature_list)print(predicted_price)
The original target value was 196 for the given model. As we can see, our model did a fairly good job at making the prediction, considering this is a model implementation from scratch. You can further improve the model though, by tweaking a few things or maybe running more optimization epochs. However, too much optimization can lead to model overfitting, which is equally bad for the model as overfitting makes the model practically unusable for real world data.
Now, to check the accuracy of our model, we will calculate its r-squared score. The following is the formula for r2 score-
def r2_score(target, prediction): """Calculates the r2 score of the model Args- target- Actual values of the target variable prediction- Predicted values, calculated using the model Returns- r2- r-squared score of the model """ r2 = 1- np.sum((target-prediction)**2)/np.sum((target-target.mean())**2) return r2
As we can see, our model explains around 83% of the variability of the response data around its mean, which is fairly good. However, there is always room for improvement in a Machine Learning model!
With this, we come to an end for our project.
I am going to make a series of blogs, where we will be working on similar projects, coding new ML models from scratch, working hands-on with real world datasets and problem statements.
I am just a novice in the field of Machine Learning and Data Science so any suggestions and criticism will really help me improve.
Hit that follow and stay tuned for more ML stuff!
Link to GitHub repo for dataset and Jupyter notebook- | [
{
"code": null,
"e": 292,
"s": 172,
"text": "In this project, we will see how to create a machine learning model that uses the Multiple Linear Regression algorithm."
},
{
"code": null,
"e": 458,
"s": 292,
"text": "The main focus of this project is to explain how linear regression works, and how you can code a linear regression model from scratch using the awesome NumPy module."
},
{
"code": null,
"e": 709,
"s": 458,
"text": "Of course, you can create a linear regression model using the scikit-learn with just 3–4 lines of code, but really, coding your own model from scratch is far more awesome than relying on a library that does everything for you while you sit and watch."
},
{
"code": null,
"e": 1094,
"s": 709,
"text": "Not only that, coding a custom model means you have full control over what the model does and how that model deals with the data that you will be feeding it. This allows for more flexibility during the training process, and you can actually tweak the model to make it more robust and responsive to the real world data as required in the future during re-training or in the production."
},
{
"code": null,
"e": 1245,
"s": 1094,
"text": "In this project, our model will be used to predict the CO2 emissions of a vehicle based on its features such as its engine size, fuel consumption etc."
},
{
"code": null,
"e": 1281,
"s": 1245,
"text": "Let’s start working on the project."
},
{
"code": null,
"e": 1333,
"s": 1281,
"text": "First, we will import the necessary PyData modules."
},
{
"code": null,
"e": 1441,
"s": 1333,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline"
},
{
"code": null,
"e": 1630,
"s": 1441,
"text": "Now, let us import our data set. The data set contains model-specific fuel consumption ratings and estimated carbon dioxide emissions for new light-duty vehicles for retail sale in Canada."
},
{
"code": null,
"e": 1689,
"s": 1630,
"text": "df = pd.read_csv(\"FuelConsumptionCo2.csv\")print(df.head())"
},
{
"code": null,
"e": 1845,
"s": 1689,
"text": "Here’s the link for the data set. I will also share the link to the Github repo containing the Jupyter notebook and the dataset at the end of this project."
},
{
"code": null,
"e": 1903,
"s": 1845,
"text": "Click the link to download the csv file- drive.google.com"
},
{
"code": null,
"e": 1947,
"s": 1903,
"text": "Here’s how it looks in my Jupyter notebook:"
},
{
"code": null,
"e": 2002,
"s": 1947,
"text": "The following are the columns present in our data set."
},
{
"code": null,
"e": 2022,
"s": 2002,
"text": "MODELYEAR e.g. 2014"
},
{
"code": null,
"e": 2038,
"s": 2022,
"text": "MAKE e.g. Acura"
},
{
"code": null,
"e": 2053,
"s": 2038,
"text": "MODEL e.g. ILX"
},
{
"code": null,
"e": 2076,
"s": 2053,
"text": "VEHICLE CLASS e.g. SUV"
},
{
"code": null,
"e": 2097,
"s": 2076,
"text": "ENGINE SIZE e.g. 4.7"
},
{
"code": null,
"e": 2113,
"s": 2097,
"text": "CYLINDERS e.g 6"
},
{
"code": null,
"e": 2134,
"s": 2113,
"text": "TRANSMISSION e.g. A6"
},
{
"code": null,
"e": 2178,
"s": 2134,
"text": "FUEL CONSUMPTION in CITY(L/100 km) e.g. 9.9"
},
{
"code": null,
"e": 2222,
"s": 2178,
"text": "FUEL CONSUMPTION in HWY (L/100 km) e.g. 8.9"
},
{
"code": null,
"e": 2264,
"s": 2222,
"text": "FUEL CONSUMPTION COMB (L/100 km) e.g. 9.2"
},
{
"code": null,
"e": 2304,
"s": 2264,
"text": "CO2 EMISSIONS (g/km) e.g. 182 → low → 0"
},
{
"code": null,
"e": 2571,
"s": 2304,
"text": "One of the most important steps in any data science project is pre-processing the data. This involves cleaning the data, typecasting some columns as required, conversion of categorical variables and standardizing/normalizing the data as per the project requirements."
},
{
"code": null,
"e": 2723,
"s": 2571,
"text": "For our project, the first step of the pre-processing is going to be checking whether we need to typecast the data type of any feature/target variable."
},
{
"code": null,
"e": 2740,
"s": 2723,
"text": "print(df.dtypes)"
},
{
"code": null,
"e": 2769,
"s": 2740,
"text": "We get the following output:"
},
{
"code": null,
"e": 2824,
"s": 2769,
"text": "As we can see, there’s no need to typecast any column."
},
{
"code": null,
"e": 3011,
"s": 2824,
"text": "The second step in our data wrangling process is analyzing whether the features need to be standardized or not. For that, let us have a look at the descriptive analysis of the dataframe."
},
{
"code": null,
"e": 3032,
"s": 3011,
"text": "print(df.describe())"
},
{
"code": null,
"e": 3155,
"s": 3032,
"text": "As we can see, all the potential features are of the same order in terms of scales, so we needn’t standardize any feature."
},
{
"code": null,
"e": 3296,
"s": 3155,
"text": "For this project, the features we will be choosing are ENGINESIZE, CYLINDERS & FUELCONSUMPTION_COMB and the target variable is CO2EMISSIONS."
},
{
"code": null,
"e": 3386,
"s": 3296,
"text": "df = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]print(df.head())"
},
{
"code": null,
"e": 3459,
"s": 3386,
"text": "Our next step- Checking the number of NaN(null) values in the dataframe."
},
{
"code": null,
"e": 3521,
"s": 3459,
"text": "for i in df.columns: print(df[i].isnull().value_counts()) "
},
{
"code": null,
"e": 3630,
"s": 3521,
"text": "As we can see, there are are no null values in our dataframe. So the data is perfect for training the model."
},
{
"code": null,
"e": 3718,
"s": 3630,
"text": "First, we will have a look at the correlation of the features and the target variables."
},
{
"code": null,
"e": 3735,
"s": 3718,
"text": "print(df.corr())"
},
{
"code": null,
"e": 3906,
"s": 3735,
"text": "This table shows a strong positive correlation between the features and the target variable. Remember, a strong correlation is a good thing for a linear regression model."
},
{
"code": null,
"e": 4100,
"s": 3906,
"text": "Now, let us visualize the plots of different features against the target variable. This will allow us to get an idea whether the features show a linear relation with the target variable or not."
},
{
"code": null,
"e": 4687,
"s": 4100,
"text": "fig, a = plt.subplots(1,3, figsize = (18, 5))a[0].scatter(df['ENGINESIZE'], df['CO2EMISSIONS'], color = 'c')a[0].set_title('Engine Size vs CO2 Emissions')a[0].set_xlabel('Engine Size (L)')a[1].scatter(df['CYLINDERS'], df['CO2EMISSIONS'], color = 'm')a[1].set_title('No. of Cylinders vs CO2 Emissions')a[1].set_xlabel('No. of Cylinders')a[2].scatter(df['FUELCONSUMPTION_COMB'], df['CO2EMISSIONS'], color = 'b')a[2].set_title('Fuel Consumption vs CO2 Emissions')a[2].set_xlabel('Fuel Consumption (L/100km)')fig.text(0.08, 0.5, 'CO2 Emissions', va='center', rotation='vertical')plt.show()"
},
{
"code": null,
"e": 4819,
"s": 4687,
"text": "As we can see, the features show a considerable linear relationship with the target. Hence, we can use them for training the model."
},
{
"code": null,
"e": 4947,
"s": 4819,
"text": "Linear regression uses the following mathematical formula for prediction of a dependent variable using an independent variable."
},
{
"code": null,
"e": 4958,
"s": 4947,
"text": "y = wx + b"
},
{
"code": null,
"e": 4964,
"s": 4958,
"text": "Here,"
},
{
"code": null,
"e": 4989,
"s": 4964,
"text": "y- Dependent variable(s)"
},
{
"code": null,
"e": 5014,
"s": 4989,
"text": "x- Dependent variable(s)"
},
{
"code": null,
"e": 5071,
"s": 5014,
"text": "w- Weight(s) associated with the independent variable(s)"
},
{
"code": null,
"e": 5112,
"s": 5071,
"text": "b- Biases for the given lin-reg equation"
},
{
"code": null,
"e": 5183,
"s": 5112,
"text": "The following is the process for developing a linear regression model."
},
{
"code": null,
"e": 6157,
"s": 5183,
"text": "Splitting the data set into training and testing sets. For the sake of simplicity however, we will be skipping this step in our custom model.Assigning random weights and biases to the model and then calculating dependent variable, ŷ on the basis of the random weights and biases.Using a loss function to calculate the total information loss, i.e., the total inaccuracy within out model. In our examples, we will be using the Mean Squared Error (MSE) loss function.Our next step is to reduce the total MSE of our model. For this, we will be using the Stochastic Gradient Descent (SGD) function, which is one of the most popular optimizer algorithms used in regression models. We will discuss the SGD function in detail while coding the optimizer function.We will update the model weights and biases based on our optimizer algorithm, then retrain the model. This is a recurrent process that will keep on repeating until we achieve an optimum model with low information loss."
},
{
"code": null,
"e": 6299,
"s": 6157,
"text": "Splitting the data set into training and testing sets. For the sake of simplicity however, we will be skipping this step in our custom model."
},
{
"code": null,
"e": 6439,
"s": 6299,
"text": "Assigning random weights and biases to the model and then calculating dependent variable, ŷ on the basis of the random weights and biases."
},
{
"code": null,
"e": 6625,
"s": 6439,
"text": "Using a loss function to calculate the total information loss, i.e., the total inaccuracy within out model. In our examples, we will be using the Mean Squared Error (MSE) loss function."
},
{
"code": null,
"e": 6916,
"s": 6625,
"text": "Our next step is to reduce the total MSE of our model. For this, we will be using the Stochastic Gradient Descent (SGD) function, which is one of the most popular optimizer algorithms used in regression models. We will discuss the SGD function in detail while coding the optimizer function."
},
{
"code": null,
"e": 7135,
"s": 6916,
"text": "We will update the model weights and biases based on our optimizer algorithm, then retrain the model. This is a recurrent process that will keep on repeating until we achieve an optimum model with low information loss."
},
{
"code": null,
"e": 7194,
"s": 7135,
"text": "First, let’s cast the features to a NumPy array, features."
},
{
"code": null,
"e": 7324,
"s": 7194,
"text": "features = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB']].to_numpy() #Converts the dataframe to numpy arrayprint(features)"
},
{
"code": null,
"e": 7389,
"s": 7324,
"text": "Now, let us get cast the target column to a NumPy array, target."
},
{
"code": null,
"e": 7480,
"s": 7389,
"text": "target = df[‘CO2EMISSIONS’].to_numpy() #Converts the dataframe to numpy arrayprint(target)"
},
{
"code": null,
"e": 7597,
"s": 7480,
"text": "Since we have 3 dependent variables, we will have 3 weights. Let’s generate array weights of 3 small random weights."
},
{
"code": null,
"e": 7693,
"s": 7597,
"text": "weights = np.random.rand(3) #Generates a numpy array with two small random floatsprint(weights)"
},
{
"code": null,
"e": 7868,
"s": 7693,
"text": "Since we have a single target variable, we will have just one bias, b. We will also create an array bias equal to the length of features array having bias b for each element."
},
{
"code": null,
"e": 8005,
"s": 7868,
"text": "b = np.random.rand(1) #Generates a numpy array with a small random floatbias = np.array([b[0] for i in range(len(features))])print(bias)"
},
{
"code": null,
"e": 8111,
"s": 8005,
"text": "Now, we will define our model function that uses weights, biases and dependent variables to calculate ŷ."
},
{
"code": null,
"e": 8730,
"s": 8111,
"text": "def linearRegr(features, weights, bias): \"\"\"Calculates the y_hat predicted values using the given parameters of weights, dependent variables, and biases. Args: -dependant_var: Matrix of dependant variable values -weights: Matrix/array of weights associated with each dependant variable -biases: Biases for the model Returns: -Array/matrix of predicted values \"\"\" y_hat = weights.dot(features.transpose()) + np.array([bias[0] for i in range(len(features))]) # Takes the value stored in the bias array and makes an array of length of feature matrix for addition return y_hat"
},
{
"code": null,
"e": 8794,
"s": 8730,
"text": "Now, let us run the function once to see the results we’ll get."
},
{
"code": null,
"e": 8847,
"s": 8794,
"text": "y_hat = linearRegr(features, weights, b)print(y_hat)"
},
{
"code": null,
"e": 8926,
"s": 8847,
"text": "Now, we will define the MSE function to calculate the total loss of our model."
},
{
"code": null,
"e": 9218,
"s": 8926,
"text": "def meanSqrError(y, y_hat): \"\"\"Calculates the total mean squared error. Args- y: Array of actual target values y_hat: Array of predicted target values Returns- total mean squared error \"\"\" MSE = np.sum((y - y_hat) ** 2) / len(y) return MSE"
},
{
"code": null,
"e": 9302,
"s": 9218,
"text": "Let us now calculate the information loss based on the y_hat values we got earlier."
},
{
"code": null,
"e": 9363,
"s": 9302,
"text": "print('Total error- {}'.format(meanSqrError(target, y_hat)))"
},
{
"code": null,
"e": 9450,
"s": 9363,
"text": "As we can see, our model is currently massively inaccurate and we need to optimize it."
},
{
"code": null,
"e": 9994,
"s": 9450,
"text": "Now comes the most important step in the linear regression. Formulating the SGD function. This is a slightly advance topic as compared to all the basic functions we have covered up until this point. It requires some knowledge of differential calculus; partial differentiation to be specific. I have tried to explain this in the image below, however, if you don’t get it, I’d strongly suggest you get familiar with the mathematics portion of Machine Learning (Calculus, Statistics and Probability, Linear Algebra) before proceeding any further."
},
{
"code": null,
"e": 10032,
"s": 9994,
"text": "Image source- Adarsh Menon-Medium.com"
},
{
"code": null,
"e": 10113,
"s": 10032,
"text": "Once we have calculated the gradients, we will update the parameters as follows."
},
{
"code": null,
"e": 10126,
"s": 10113,
"text": "m = m - α Dm"
},
{
"code": null,
"e": 10139,
"s": 10126,
"text": "c = c - α Dc"
},
{
"code": null,
"e": 10145,
"s": 10139,
"text": "Here,"
},
{
"code": null,
"e": 10173,
"s": 10145,
"text": "E- Total mean squared error"
},
{
"code": null,
"e": 10209,
"s": 10173,
"text": "m- Weights associated with features"
},
{
"code": null,
"e": 10223,
"s": 10209,
"text": "c- Model bias"
},
{
"code": null,
"e": 10256,
"s": 10223,
"text": "y- Array of actual target values"
},
{
"code": null,
"e": 10284,
"s": 10256,
"text": "ŷ- Predicted target values"
},
{
"code": null,
"e": 10329,
"s": 10284,
"text": "Dm- Partial derivative of E w.r.t. weights m"
},
{
"code": null,
"e": 10371,
"s": 10329,
"text": "Dc- Partial derivative of E w.r.t. bias c"
},
{
"code": null,
"e": 10447,
"s": 10371,
"text": "α- Learning rate, i.e., size of the step that the optimizer function takes."
},
{
"code": null,
"e": 10739,
"s": 10447,
"text": "Once we have the new updated values of the weights and biases, we will calculate the loss again. We will repeat the process for n epochs, i.e., number of cycles and plot the loss values after each epoch. To keep the code clean, I will create a separate function for calculation of gradients."
},
{
"code": null,
"e": 11605,
"s": 10739,
"text": "def gradient(target, features, weights, bias): \"\"\"Returns the gradient(slopes) for weights and biases \"\"\" m = len(features) target_pred = linearRegr(features, weights, bias) loss = target - target_pred # y-y_hat # Gradient calculation for model bias grad_bias = np.array([-2/m * np.sum(loss)]) grad_weights = np.ones(3) # Gradient calculation for first feature feature_0 = np.array([feature[0] for feature in features]) grad_weights[0] = -2/m * np.sum(loss * feature_0) # Gradient calculation for second feature feature_1 = np.array([feature[1] for feature in features]) grad_weights[1] = -2/m * np.sum(loss * feature_1) # Gradient calculation for third feature feature_2 = np.array([feature[1] for feature in features]) grad_weights[2] = -2/m * np.sum(loss * feature_2) return grad_bias, grad_weights"
},
{
"code": null,
"e": 11725,
"s": 11605,
"text": "Now, let us write the SDG function that will return the updated weights and biases so we can formulate our final model."
},
{
"code": null,
"e": 12810,
"s": 11725,
"text": "def stochGradDesMODIFIED(learning_rate, epochs, target, features, weights, bias): \"\"\"Performs stochastic gradient descent optimization on the model. Args- learning_rate- Size of the step the function will take during optimization epochs- No. of iterations the function will run for on the model target- Actual emission values features- Matrix of dependent variables weights- Weights associated with each feature bias- Model bias Returns- return_dict = {'weights': weights, 'bias': bias[0], 'MSE': total_MSE_new, 'MSE_list': MSE_list} \"\"\"MSE_list = [] for i in range(epochs): grad_bias, grad_weights = gradient(target, features, weights, bias) weights -= grad_weights * learning_rate bias -= grad_bias * learning_rate new_pred = linearRegr(features, weights, bias) total_MSE_new = meanSqrError(target, new_pred) MSE_list.append(total_MSE_new) return_dict = {'weights': weights, 'bias': bias[0], 'MSE': total_MSE_new, 'MSE_list': MSE_list} return return_dict"
},
{
"code": null,
"e": 12949,
"s": 12810,
"text": "Finally, we have the optimizer function for our linear regression model. Let us run the function now and store the values for further use."
},
{
"code": null,
"e": 13133,
"s": 12949,
"text": "model_val = stochGradDesMODIFIED(0.001, 2000, target, features, weights, bias)print(\"Weights- {}\\nBias- {}\\nMSE- {}\".format(model_val['weights'], model_val['bias'], model_val['MSE']))"
},
{
"code": null,
"e": 13275,
"s": 13133,
"text": "The initial MSE was around 65,000 while the current MSE is around 680. We can see from the results that our model has significantly improved."
},
{
"code": null,
"e": 13394,
"s": 13275,
"text": "Finally, we will write the model function that uses the updated model weights and biases to predict the target values."
},
{
"code": null,
"e": 13888,
"s": 13394,
"text": "def LinearRegressionModel(model_val, feature_list): \"\"\"Predicts the CO2 emission values of the vehicle Args- model_val- This is the dictionary returned by the stockGradDesMODIFIED function. Contains model weights and biases feature_list- An array of the dependent variables Returns- co2_emission- Emission predictions for the given set of features \"\"\" co2_emission = np.sum(model_val['weights'] * feature_list) + model_val['bias'] return co2_emission"
},
{
"code": null,
"e": 13953,
"s": 13888,
"text": "As a test run, we will now test our model on the following data."
},
{
"code": null,
"e": 13982,
"s": 13953,
"text": "feature_list = [2.0, 4, 8.5]"
},
{
"code": null,
"e": 14058,
"s": 13982,
"text": "The actual target value for the data is 196. Let’s see how our model fares."
},
{
"code": null,
"e": 14191,
"s": 14058,
"text": "target_price = 196feature_list = [2.0, 4, 8.5]predicted_price = LinearRegressionModel(model_val, feature_list)print(predicted_price)"
},
{
"code": null,
"e": 14656,
"s": 14191,
"text": "The original target value was 196 for the given model. As we can see, our model did a fairly good job at making the prediction, considering this is a model implementation from scratch. You can further improve the model though, by tweaking a few things or maybe running more optimization epochs. However, too much optimization can lead to model overfitting, which is equally bad for the model as overfitting makes the model practically unusable for real world data."
},
{
"code": null,
"e": 14779,
"s": 14656,
"text": "Now, to check the accuracy of our model, we will calculate its r-squared score. The following is the formula for r2 score-"
},
{
"code": null,
"e": 15142,
"s": 14779,
"text": "def r2_score(target, prediction): \"\"\"Calculates the r2 score of the model Args- target- Actual values of the target variable prediction- Predicted values, calculated using the model Returns- r2- r-squared score of the model \"\"\" r2 = 1- np.sum((target-prediction)**2)/np.sum((target-target.mean())**2) return r2"
},
{
"code": null,
"e": 15341,
"s": 15142,
"text": "As we can see, our model explains around 83% of the variability of the response data around its mean, which is fairly good. However, there is always room for improvement in a Machine Learning model!"
},
{
"code": null,
"e": 15387,
"s": 15341,
"text": "With this, we come to an end for our project."
},
{
"code": null,
"e": 15572,
"s": 15387,
"text": "I am going to make a series of blogs, where we will be working on similar projects, coding new ML models from scratch, working hands-on with real world datasets and problem statements."
},
{
"code": null,
"e": 15703,
"s": 15572,
"text": "I am just a novice in the field of Machine Learning and Data Science so any suggestions and criticism will really help me improve."
},
{
"code": null,
"e": 15753,
"s": 15703,
"text": "Hit that follow and stay tuned for more ML stuff!"
}
] |
Minimum steps needed to cover a sequence of points on an infinite grid - GeeksforGeeks | 02 Mar, 2022
Given an infinite grid, initial cell position (x, y) and a sequence of other cell position which needs to be covered in the given order. The task is to find the minimum number of steps needed to travel to all those cells.Note: Movement can be done in any of the eight possible directions from a given cell i.e from cell (x, y) you can move to any of the following eight positions:(x-1, y+1), (x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1) is possible.
Examples:
Input: points[] = [(0, 0), (1, 1), (1, 2)]Output: 2Move from (0, 0) to (1, 1) in 1 step(diagonal) andthen from (1, 1) to (1, 2) in 1 step (rightwards)
Input: points[] = [{4, 6}, {1, 2}, {4, 5}, {10, 12}]Output: 14Move from (4, 6) -> (3, 5) -> (2, 4) -> (1, 3) ->(1, 2) -> (2, 3) -> (3, 4) ->(4, 5) -> (5, 6) -> (6, 7) ->(7, 8) -> (8, 9) -> (9, 10) -> (10, 11) -> (10, 12)
Approach: Since all the given points are to be covered in the specified order. Find the minimum number of steps required to reach from a starting point to next point, then the sum of all such minimum steps for covering all the points would be the answer. One way to reach from a point (x1, y1) to (x2, y2) is to move abs(x2-x1) steps in the horizontal direction and abs(y2-y1) steps in the vertical direction, but this is not the shortest path to reach (x2, y2). The best way would be to cover the maximum possible distance in a diagonal direction and remaining in horizontal or vertical direction.If we look closely this just reduces to the maximum of abs(x2-x1) and abs(y2-y1). Traverse for all points and summation of all diagonal distance will be the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program to cover a sequence of points// in minimum steps in a given order.#include <bits/stdc++.h>using namespace std; // cell structure denoted as pointstruct point { int x, y;}; // function to give minimum steps to// move from point p1 to p2int shortestPath(point p1, point p2){ // dx is total horizontal // distance to be covered int dx = abs(p1.x - p2.x); // dy is total vertical // distance to be covered int dy = abs(p1.y - p2.y); // required answer is // maximum of these two return max(dx, dy);} // Function to return the minimum stepsint coverPoints(point sequence[], int size){ int stepCount = 0; // finding steps for each // consecutive point in the sequence for (int i = 0; i < size - 1; i++) { stepCount += shortestPath(sequence[i], sequence[i + 1]); } return stepCount;} // Driver codeint main(){ // arr stores sequence of points // that are to be visited point arr[] = { { 4, 6 }, { 1, 2 }, { 4, 5 }, { 10, 12 } }; int n = sizeof(arr) / sizeof(arr[0]); cout << coverPoints(arr, n);}
// Java program to cover a// sequence of points in// minimum steps in a given order.import java.io.*;import java.util.*;import java.lang.*; // class denoted as pointclass point{ int x, y; point(int a, int b) { x = a; y = b; }} class GFG{// function to give minimum// steps to move from point// p1 to p2static int shortestPath(point p1, point p2){ // dx is total horizontal // distance to be covered int dx = Math.abs(p1.x - p2.x); // dy is total vertical // distance to be covered int dy = Math.abs(p1.y - p2.y); // required answer is // maximum of these two return Math.max(dx, dy);} // Function to return// the minimum stepsstatic int coverPoints(point sequence[], int size){ int stepCount = 0; // finding steps for // each consecutive // point in the sequence for (int i = 0; i < size - 1; i++) { stepCount += shortestPath(sequence[i], sequence[i + 1]); } return stepCount;} // Driver codepublic static void main(String args[]){ // arr stores sequence of points // that are to be visited point arr[] = new point[4]; arr[0] = new point(4, 6); arr[1] = new point(1, 2); arr[2] = new point(4, 5); arr[3] = new point(10, 12); int n = arr.length; System.out.print(coverPoints(arr, n));}}
# Python program to cover a sequence of points# in minimum steps in a given order. # function to give minimum steps to# move from pop1 to p2def shortestPath(p1, p2): # dx is total horizontal # distance to be covered dx = abs(p1[0] - p2[0]) # dy is total vertical # distance to be covered dy = abs(p1[1] - p2[1]) # required answer is # maximum of these two return max(dx, dy) # Function to return the minimum stepsdef coverPoints(sequence, size): stepCount = 0 # finding steps for each # consecutive poin the sequence for i in range(size-1): stepCount += shortestPath(sequence[i],sequence[i + 1]) return stepCount # Driver code# arr stores sequence of points# that are to be visitedarr = [[4, 6] ,[ 1, 2 ], [ 4, 5] , [ 10, 12]] n = len(arr)print(coverPoints(arr, n)) # This code is contributed by shivanisinghss2110.
// C# program to cover a// sequence of points in// minimum steps in a given order. using System;// class denoted as pointpublic class point{ public int x, y; public point(int a, int b) { x = a; y = b; }} public class GFG{ // function to give minimum // steps to move from point // p1 to p2[] static int shortestPath(point p1, point p2) { // dx is total horizontal // distance to be covered int dx = Math.Abs(p1.x - p2.x); // dy is total vertical // distance to be covered int dy = Math.Abs(p1.y - p2.y); // required answer is // maximum of these two return Math.Max(dx, dy); } // Function to return // the minimum steps static int coverPoints(point []sequence, int size) { int stepCount = 0; // finding steps for // each consecutive // point in the sequence for (int i = 0; i < size - 1; i++) { stepCount += shortestPath(sequence[i], sequence[i + 1]); } return stepCount; } // Driver code public static void Main() { // arr stores sequence of points // that are to be visited point []arr = new point[4]; arr[0] = new point(4, 6); arr[1] = new point(1, 2); arr[2] = new point(4, 5); arr[3] = new point(10, 12); int n = arr.Length; Console.WriteLine(coverPoints(arr, n)); }}// This code is contributed by Rajput-Ji
# Traversing from one point to another point# storing the minimum number of stepsdef traversal_steps(points): minSteps = 0 for p in range(len(points)-1): # taking the manhattan distance between # x and y-coordinates d1 = abs(points[p][0] - points[p+1][0]) d2 = abs(points[p][1] - points[p+1][1]) # adding the maximum among the two to the # running steps parameter minSteps += max(d1,d2) return (minSteps) # Main Driver Codeif __name__ == '__main__': points = [(0,0),(1,1),(1,2)] print (traversal_steps(points)) points = [(4,6),(1,2),(4,5),(10,12)] print (traversal_steps(points))
<script>// JacaScript program to cover a sequence of points// in minimum steps in a given order. // function to give minimum steps to// move from pop1 to p2function shortestPath(p1, p2){ // dx is total horizontal // distance to be covered let dx = Math.abs(p1[0] - p2[0]) // dy is total vertical // distance to be covered let dy = Math.abs(p1[1] - p2[1]) // required answer is // maximum of these two return Math.max(dx, dy) } // Function to return the minimum stepsfunction coverPoints(sequence, size){ let stepCount = 0 // finding steps for each // consecutive poin the sequence for(let i=0;i<(size-1);i++) stepCount += shortestPath(sequence[i],sequence[i + 1]) return stepCount } // Driver code// arr stores sequence of points// that are to be visitedlet arr = [[4, 6] ,[ 1, 2 ], [ 4, 5] , [ 10, 12]] let n = arr.lengthdocument.write(coverPoints(arr, n)) // This code is contributed by shivanisinghss2110.</script>
14
Time Complexity: O(N)
Rajput-Ji
Vikas Chitturi
shivanisinghss2110
shinjanpatra
Greedy Algorithms
math
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
Efficient program to print all prime factors of a given number
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Print all possible combinations of r elements in a given array of size n | [
{
"code": null,
"e": 25112,
"s": 25084,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 25592,
"s": 25112,
"text": "Given an infinite grid, initial cell position (x, y) and a sequence of other cell position which needs to be covered in the given order. The task is to find the minimum number of steps needed to travel to all those cells.Note: Movement can be done in any of the eight possible directions from a given cell i.e from cell (x, y) you can move to any of the following eight positions:(x-1, y+1), (x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1) is possible."
},
{
"code": null,
"e": 25602,
"s": 25592,
"text": "Examples:"
},
{
"code": null,
"e": 25753,
"s": 25602,
"text": "Input: points[] = [(0, 0), (1, 1), (1, 2)]Output: 2Move from (0, 0) to (1, 1) in 1 step(diagonal) andthen from (1, 1) to (1, 2) in 1 step (rightwards)"
},
{
"code": null,
"e": 25974,
"s": 25753,
"text": "Input: points[] = [{4, 6}, {1, 2}, {4, 5}, {10, 12}]Output: 14Move from (4, 6) -> (3, 5) -> (2, 4) -> (1, 3) ->(1, 2) -> (2, 3) -> (3, 4) ->(4, 5) -> (5, 6) -> (6, 7) ->(7, 8) -> (8, 9) -> (9, 10) -> (10, 11) -> (10, 12)"
},
{
"code": null,
"e": 26737,
"s": 25974,
"text": "Approach: Since all the given points are to be covered in the specified order. Find the minimum number of steps required to reach from a starting point to next point, then the sum of all such minimum steps for covering all the points would be the answer. One way to reach from a point (x1, y1) to (x2, y2) is to move abs(x2-x1) steps in the horizontal direction and abs(y2-y1) steps in the vertical direction, but this is not the shortest path to reach (x2, y2). The best way would be to cover the maximum possible distance in a diagonal direction and remaining in horizontal or vertical direction.If we look closely this just reduces to the maximum of abs(x2-x1) and abs(y2-y1). Traverse for all points and summation of all diagonal distance will be the answer."
},
{
"code": null,
"e": 26788,
"s": 26737,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26792,
"s": 26788,
"text": "C++"
},
{
"code": null,
"e": 26797,
"s": 26792,
"text": "Java"
},
{
"code": null,
"e": 26805,
"s": 26797,
"text": "Python3"
},
{
"code": null,
"e": 26808,
"s": 26805,
"text": "C#"
},
{
"code": "// C++ program to cover a sequence of points// in minimum steps in a given order.#include <bits/stdc++.h>using namespace std; // cell structure denoted as pointstruct point { int x, y;}; // function to give minimum steps to// move from point p1 to p2int shortestPath(point p1, point p2){ // dx is total horizontal // distance to be covered int dx = abs(p1.x - p2.x); // dy is total vertical // distance to be covered int dy = abs(p1.y - p2.y); // required answer is // maximum of these two return max(dx, dy);} // Function to return the minimum stepsint coverPoints(point sequence[], int size){ int stepCount = 0; // finding steps for each // consecutive point in the sequence for (int i = 0; i < size - 1; i++) { stepCount += shortestPath(sequence[i], sequence[i + 1]); } return stepCount;} // Driver codeint main(){ // arr stores sequence of points // that are to be visited point arr[] = { { 4, 6 }, { 1, 2 }, { 4, 5 }, { 10, 12 } }; int n = sizeof(arr) / sizeof(arr[0]); cout << coverPoints(arr, n);}",
"e": 27921,
"s": 26808,
"text": null
},
{
"code": "// Java program to cover a// sequence of points in// minimum steps in a given order.import java.io.*;import java.util.*;import java.lang.*; // class denoted as pointclass point{ int x, y; point(int a, int b) { x = a; y = b; }} class GFG{// function to give minimum// steps to move from point// p1 to p2static int shortestPath(point p1, point p2){ // dx is total horizontal // distance to be covered int dx = Math.abs(p1.x - p2.x); // dy is total vertical // distance to be covered int dy = Math.abs(p1.y - p2.y); // required answer is // maximum of these two return Math.max(dx, dy);} // Function to return// the minimum stepsstatic int coverPoints(point sequence[], int size){ int stepCount = 0; // finding steps for // each consecutive // point in the sequence for (int i = 0; i < size - 1; i++) { stepCount += shortestPath(sequence[i], sequence[i + 1]); } return stepCount;} // Driver codepublic static void main(String args[]){ // arr stores sequence of points // that are to be visited point arr[] = new point[4]; arr[0] = new point(4, 6); arr[1] = new point(1, 2); arr[2] = new point(4, 5); arr[3] = new point(10, 12); int n = arr.length; System.out.print(coverPoints(arr, n));}}",
"e": 29310,
"s": 27921,
"text": null
},
{
"code": "# Python program to cover a sequence of points# in minimum steps in a given order. # function to give minimum steps to# move from pop1 to p2def shortestPath(p1, p2): # dx is total horizontal # distance to be covered dx = abs(p1[0] - p2[0]) # dy is total vertical # distance to be covered dy = abs(p1[1] - p2[1]) # required answer is # maximum of these two return max(dx, dy) # Function to return the minimum stepsdef coverPoints(sequence, size): stepCount = 0 # finding steps for each # consecutive poin the sequence for i in range(size-1): stepCount += shortestPath(sequence[i],sequence[i + 1]) return stepCount # Driver code# arr stores sequence of points# that are to be visitedarr = [[4, 6] ,[ 1, 2 ], [ 4, 5] , [ 10, 12]] n = len(arr)print(coverPoints(arr, n)) # This code is contributed by shivanisinghss2110.",
"e": 30215,
"s": 29310,
"text": null
},
{
"code": "// C# program to cover a// sequence of points in// minimum steps in a given order. using System;// class denoted as pointpublic class point{ public int x, y; public point(int a, int b) { x = a; y = b; }} public class GFG{ // function to give minimum // steps to move from point // p1 to p2[] static int shortestPath(point p1, point p2) { // dx is total horizontal // distance to be covered int dx = Math.Abs(p1.x - p2.x); // dy is total vertical // distance to be covered int dy = Math.Abs(p1.y - p2.y); // required answer is // maximum of these two return Math.Max(dx, dy); } // Function to return // the minimum steps static int coverPoints(point []sequence, int size) { int stepCount = 0; // finding steps for // each consecutive // point in the sequence for (int i = 0; i < size - 1; i++) { stepCount += shortestPath(sequence[i], sequence[i + 1]); } return stepCount; } // Driver code public static void Main() { // arr stores sequence of points // that are to be visited point []arr = new point[4]; arr[0] = new point(4, 6); arr[1] = new point(1, 2); arr[2] = new point(4, 5); arr[3] = new point(10, 12); int n = arr.Length; Console.WriteLine(coverPoints(arr, n)); }}// This code is contributed by Rajput-Ji",
"e": 31800,
"s": 30215,
"text": null
},
{
"code": "# Traversing from one point to another point# storing the minimum number of stepsdef traversal_steps(points): minSteps = 0 for p in range(len(points)-1): # taking the manhattan distance between # x and y-coordinates d1 = abs(points[p][0] - points[p+1][0]) d2 = abs(points[p][1] - points[p+1][1]) # adding the maximum among the two to the # running steps parameter minSteps += max(d1,d2) return (minSteps) # Main Driver Codeif __name__ == '__main__': points = [(0,0),(1,1),(1,2)] print (traversal_steps(points)) points = [(4,6),(1,2),(4,5),(10,12)] print (traversal_steps(points))",
"e": 32460,
"s": 31800,
"text": null
},
{
"code": "<script>// JacaScript program to cover a sequence of points// in minimum steps in a given order. // function to give minimum steps to// move from pop1 to p2function shortestPath(p1, p2){ // dx is total horizontal // distance to be covered let dx = Math.abs(p1[0] - p2[0]) // dy is total vertical // distance to be covered let dy = Math.abs(p1[1] - p2[1]) // required answer is // maximum of these two return Math.max(dx, dy) } // Function to return the minimum stepsfunction coverPoints(sequence, size){ let stepCount = 0 // finding steps for each // consecutive poin the sequence for(let i=0;i<(size-1);i++) stepCount += shortestPath(sequence[i],sequence[i + 1]) return stepCount } // Driver code// arr stores sequence of points// that are to be visitedlet arr = [[4, 6] ,[ 1, 2 ], [ 4, 5] , [ 10, 12]] let n = arr.lengthdocument.write(coverPoints(arr, n)) // This code is contributed by shivanisinghss2110.</script>",
"e": 33465,
"s": 32460,
"text": null
},
{
"code": null,
"e": 33469,
"s": 33465,
"text": "14\n"
},
{
"code": null,
"e": 33491,
"s": 33469,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 33501,
"s": 33491,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 33516,
"s": 33501,
"text": "Vikas Chitturi"
},
{
"code": null,
"e": 33535,
"s": 33516,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 33548,
"s": 33535,
"text": "shinjanpatra"
},
{
"code": null,
"e": 33566,
"s": 33548,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 33571,
"s": 33566,
"text": "math"
},
{
"code": null,
"e": 33584,
"s": 33571,
"text": "Mathematical"
},
{
"code": null,
"e": 33597,
"s": 33584,
"text": "Mathematical"
},
{
"code": null,
"e": 33695,
"s": 33597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33719,
"s": 33695,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33762,
"s": 33719,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33811,
"s": 33762,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33845,
"s": 33811,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 33866,
"s": 33845,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 33908,
"s": 33866,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 33971,
"s": 33908,
"text": "Efficient program to print all prime factors of a given number"
},
{
"code": null,
"e": 34024,
"s": 33971,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 34061,
"s": 34024,
"text": "Minimum number of jumps to reach end"
}
] |
time.Time.Unix() Function in Golang with Examples - GeeksforGeeks | 21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Unix() function in Go language is used to yield “t” as a Unix time that is the number of seconds passed from January 1, 1970, in UTC and the output here doesn’t rely upon the location connected with t. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) Unix() int64
Here, “t” is the stated time.
Note: A Unix like operating system frequently stores time as a 32-bit count of seconds. And on the other hand, the Unix() method here returns a 64-bit value so it’s period of validity is for billions of years into the past or the future.
Return value: It returns “t” as a Unix time which is of type int64.
Example 1:
// Golang program to illustrate the usage of// Time.Unix() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t in UTC for Unix method t := time.Date(2020, 11, 14, 11, 30, 32, 0, time.UTC) // Calling Unix method unix := t.Unix() // Prints output fmt.Printf("%v\n", unix)}
Output:
1605353432
Example 2:
// Golang program to illustrate the usage of// Time.Unix() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t in UTC for Unix method t := time.Date(2013, 11, 14, 1e3, 3e5, 7e1, 0, time.UTC) // Calling Unix method unix := t.Unix() // Prints output fmt.Printf("%v\n", unix)}
Output:
1405987270
Here, the time “t” stated in the above code has values which contain constant “e” which are converted in usual range while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fmt.Sprintf() Function in Golang With Examples
Inheritance in GoLang
Slices in Golang
How to Trim a String in Golang?
How to Split a String in Golang?
How to compare times in Golang?
How to print string with double quotes in Golang?
Command Line Arguments in Golang
fmt.print() Function in Golang With Examples
strings.Replace() Function in Golang With Examples | [
{
"code": null,
"e": 24161,
"s": 24133,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 24602,
"s": 24161,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Unix() function in Go language is used to yield “t” as a Unix time that is the number of seconds passed from January 1, 1970, in UTC and the output here doesn’t rely upon the location connected with t. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 24610,
"s": 24602,
"text": "Syntax:"
},
{
"code": null,
"e": 24638,
"s": 24610,
"text": "func (t Time) Unix() int64\n"
},
{
"code": null,
"e": 24668,
"s": 24638,
"text": "Here, “t” is the stated time."
},
{
"code": null,
"e": 24906,
"s": 24668,
"text": "Note: A Unix like operating system frequently stores time as a 32-bit count of seconds. And on the other hand, the Unix() method here returns a 64-bit value so it’s period of validity is for billions of years into the past or the future."
},
{
"code": null,
"e": 24974,
"s": 24906,
"text": "Return value: It returns “t” as a Unix time which is of type int64."
},
{
"code": null,
"e": 24985,
"s": 24974,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Unix() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t in UTC for Unix method t := time.Date(2020, 11, 14, 11, 30, 32, 0, time.UTC) // Calling Unix method unix := t.Unix() // Prints output fmt.Printf(\"%v\\n\", unix)}",
"e": 25372,
"s": 24985,
"text": null
},
{
"code": null,
"e": 25380,
"s": 25372,
"text": "Output:"
},
{
"code": null,
"e": 25392,
"s": 25380,
"text": "1605353432\n"
},
{
"code": null,
"e": 25403,
"s": 25392,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Unix() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t in UTC for Unix method t := time.Date(2013, 11, 14, 1e3, 3e5, 7e1, 0, time.UTC) // Calling Unix method unix := t.Unix() // Prints output fmt.Printf(\"%v\\n\", unix)}",
"e": 25793,
"s": 25403,
"text": null
},
{
"code": null,
"e": 25801,
"s": 25793,
"text": "Output:"
},
{
"code": null,
"e": 25813,
"s": 25801,
"text": "1405987270\n"
},
{
"code": null,
"e": 25948,
"s": 25813,
"text": "Here, the time “t” stated in the above code has values which contain constant “e” which are converted in usual range while conversion."
},
{
"code": null,
"e": 25960,
"s": 25948,
"text": "GoLang-time"
},
{
"code": null,
"e": 25972,
"s": 25960,
"text": "Go Language"
},
{
"code": null,
"e": 26070,
"s": 25972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26079,
"s": 26070,
"text": "Comments"
},
{
"code": null,
"e": 26092,
"s": 26079,
"text": "Old Comments"
},
{
"code": null,
"e": 26139,
"s": 26092,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 26161,
"s": 26139,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 26178,
"s": 26161,
"text": "Slices in Golang"
},
{
"code": null,
"e": 26210,
"s": 26178,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 26243,
"s": 26210,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 26275,
"s": 26243,
"text": "How to compare times in Golang?"
},
{
"code": null,
"e": 26325,
"s": 26275,
"text": "How to print string with double quotes in Golang?"
},
{
"code": null,
"e": 26358,
"s": 26325,
"text": "Command Line Arguments in Golang"
},
{
"code": null,
"e": 26403,
"s": 26358,
"text": "fmt.print() Function in Golang With Examples"
}
] |
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks | 17 Sep, 2021
A variable x is said to be live at a statement Si in a program if the following three conditions hold simultaneously:
1. There exists a statement Sj that uses x
2. There is a path from Si to Sj in the flow
graph corresponding to the program
3. The path has no intervening assignment to x
including at Si and Sj
The variables which are live both at the statement in basic block 2 and at the statement in basic block 3 of the above control flow graph are(A) p, s, u(B) r, s, u(C) r, u(D) q, vAnswer: (C)Explanation: Live variable analysis is useful in compilers to find variables in each program that may be needed in future.
As per the definition given in question, a variable is live if it holds a value that may be needed in the future. In other words, it is used in future before any new assignment.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0040:22 / 59:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4ab8S2Qs7h8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2004 | Question 69
GATE | GATE-CS-2006 | Question 49 | [
{
"code": null,
"e": 24492,
"s": 24464,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 24610,
"s": 24492,
"text": "A variable x is said to be live at a statement Si in a program if the following three conditions hold simultaneously:"
},
{
"code": null,
"e": 24810,
"s": 24610,
"text": "1. There exists a statement Sj that uses x\n2. There is a path from Si to Sj in the flow\n graph corresponding to the program\n3. The path has no intervening assignment to x \n including at Si and Sj"
},
{
"code": null,
"e": 25123,
"s": 24810,
"text": "The variables which are live both at the statement in basic block 2 and at the statement in basic block 3 of the above control flow graph are(A) p, s, u(B) r, s, u(C) r, u(D) q, vAnswer: (C)Explanation: Live variable analysis is useful in compilers to find variables in each program that may be needed in future."
},
{
"code": null,
"e": 25302,
"s": 25123,
"text": "As per the definition given in question, a variable is live if it holds a value that may be needed in the future. In other words, it is used in future before any new assignment."
},
{
"code": null,
"e": 26217,
"s": 25302,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0040:22 / 59:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4ab8S2Qs7h8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 26238,
"s": 26217,
"text": "GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 26264,
"s": 26238,
"text": "GATE-GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 26269,
"s": 26264,
"text": "GATE"
},
{
"code": null,
"e": 26367,
"s": 26269,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26401,
"s": 26367,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 26443,
"s": 26401,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26476,
"s": 26443,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 26510,
"s": 26476,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 26543,
"s": 26510,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 26577,
"s": 26543,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 26619,
"s": 26577,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 61"
},
{
"code": null,
"e": 26661,
"s": 26619,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 26695,
"s": 26661,
"text": "GATE | GATE-CS-2004 | Question 69"
}
] |
Generate 3D meshes from point clouds with Python | Towards Data Science | In this article, I will give you my 3D surface reconstruction process for quickly creating a mesh from point clouds with python. You will be able to export, visualize and integrate results into your favorite 3D software, without any coding experience. Additionally, I will provide you with a simple way to generate multiple Levels of Details (LoD), useful if you want to create real-time applications (E.g. Virtual Reality with Unity).
3D meshes are geometric data structures most often composed of a bunch of connected triangles that explicitly describe a surface 🤔. They are used in a wide range of applications from geospatial reconstructions to VFX, movies and video games. I often create them when a physical replica is demanded or if I need to integrate environments in game engines, where point cloud support is limited.
They are well integrated in most of the software professionals work with. On top, if you want to explore the wonder of 3D printing, you need to be able to generate a consistent mesh from the data that you have. This article is designed to offer you an efficient workflow in 5 customizable steps along with my script remotely executable at the end of the article. Let us dive in!
In the previous article, we saw how to set-up an environment easily with Anaconda, and how to use the GUI Spyder for managing your code. We will continue in this fashion, using only 2 libraries.
towardsdatascience.com
For getting a 3D mesh automatically out of a point cloud, we will add another library to our environment, Open3D. It is an open-source library that allows the use of a set of efficient data structures and algorithms for 3D data processing. The installation necessitates to click on the ▶️ icon next to your environment.
Open the Terminal and run the following command:
conda install -c open3d-admin open3d==0.8.0.0
🤓 Note: The Open3D package is compatible with python version 2.7, 3.5 and 3.6. If you have another, you can either create a new environment (best) or if you start from the previous article, change the python version in your terminal by typing conda install python=3.5 in the Terminal.
This will install the package and its dependencies automatically, you can just input y when prompted in the terminal to allow this process. You are now set-up for the project.
Launch your python scripting tool (Spyder GUI, Jupyter or Google Colab), where we will call 2 libraries: Numpy and Open3D.
import numpy as npimport open3d as o3d
Then, we create variables that hold data paths and the point cloud data:
input_path="your_path_to_file/"output_path="your_path_to_output_folder/"dataname="sample.xyz"point_cloud= np.loadtxt(input_path+dataname,skiprows=1)
🤓 Note: As for the previous post, we will use a sampled point cloud that you can freely download from this repository. If you want to visualize it beforehand without installing anything, you can check the webGL version.
Finally, we transform the point_cloud variable type from Numpy to the Open3D o3d.geometry.PointCloud type for further processing:
pcd = o3d.geometry.PointCloud()pcd.points = o3d.utility.Vector3dVector(point_cloud[:,:3])pcd.colors = o3d.utility.Vector3dVector(point_cloud[:,3:6]/255)pcd.normals = o3d.utility.Vector3dVector(point_cloud[:,6:9])
🤓 Note: The following command first instantiates the Open3d point cloud object, then add points, color and normals to it from the original NumPy array.
For a quick visual of what you loaded, you can execute the following command (does not work in Google Colab):
o3d.visualization.draw_geometries([pcd])
Now we are ready to start the surface reconstruction process by meshing the pcd point cloud. I will give my favorite way to efficiently obtain results, but before we dive in, some condensed details ar necessary to grasp the underlying processes. I will limit myself to two meshing strategies.
The idea behind the Ball-Pivoting Algorithm (BPA) is to simulate the use of a virtual ball to generate a mesh from a point cloud. We first assume that the given point cloud consists of points sampled from the surface of an object. Points must strictly represent a surface (noise-free), that the reconstructed mesh explicit.
Using this assumption, imagine rolling a tiny ball across the point cloud “surface”. This tiny ball is dependent on the scale of the mesh, and should be slightly larger than the average space between points. When you drop a ball onto the surface of points, the ball will get caught and settle upon three points that will form the seed triangle. From that location, the ball rolls along the triangle edge formed from two points. The ball then settles in a new location: a new triangle is formed from two of the previous vertices and one new triangle is added to the mesh. As we continue rolling and pivoting the ball, new triangles are formed and added to the mesh. The ball continues rolling and rolling until the mesh is fully formed.
The idea behind the Ball-Pivoting Algorithm is simple, but of course, there are many caveats to the procedure as originally expressed here:
How is the ball radius chosen? The radius, is obtained empirically based on the size and scale of the input point cloud. In theory, the diameter of the ball should be slightly larger than the average distance between points.
What if the points are too far apart at some locations and the ball falls through? When the ball pivots along an edge, it may miss the appropriate point on the surface and instead hit another point on the object or even exactly its three old points. In this case, we check that the normal of the new triangle Facet is consistently oriented with the point's Vertex normals. If it is not, then we reject that triangle and create a hole.
What if the surface has a crease or valley, such that the distance between the surface and itself is less than the size of the ball? In this case, the ball would just roll over the crease and ignore the points within the crease. But, this is not ideal behavior as the reconstructed mesh is not accurate to the object.
What if the surface is spaced into regions of points such that the ball cannot successfully roll between the regions? The virtual ball is dropped onto the surface multiple times at varying locations. This ensures that the ball captures the entire mesh, even when the points are inconsistently spaced out.
The Poisson Reconstruction is a bit more technical/mathematical. Its approach is known as an implicit meshing method, which I would describe as trying to “envelop” the data in a smooth cloth. Without going into too many details, we try to fit a watertight surface from the original point set by creating an entirely new point set representing an isosurface linked to the normals. There are several parameters available that affect the result of the meshing:
Which depth? a tree-depth is used for the reconstruction. The higher the more detailed the mesh (Default: 8). With noisy data you keep vertices in the generated mesh that are outliers but the algorithm doesn’t detect them as such. So a low value (maybe between 5 and 7) provides a smoothing effect, but you will lose detail. The higher the depth-value the higher is the resulting amount of vertices of the generated mesh.
Which width? This specifies the target width of the finest level of the tree structure, which is called an octree 🤯. Don’t worry, I will cover this and best data structures for 3D in another article as it extends the scope of this one. Anyway, this parameter is ignored if the depth is specified.
Which scale? It describes the ratio between the diameter of the cube used for reconstruction and the diameter of the samples’ bounding cube. Very abstract, the default parameter usually works well (1.1).
Which fit? the linear_fit parameter if set to true, let the reconstructor use linear interpolation to estimate the positions of iso-vertices.
We first compute the necessary radius parameter based on the average distances computed from all the distances between points:
distances = pcd.compute_nearest_neighbor_distance()avg_dist = np.mean(distances)radius = 3 * avg_dist
In one command line, we can then create a mesh and store it in the bpa_mesh variable:
bpa_mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_ball_pivoting(pcd,o3d.utility.DoubleVector([radius, radius * 2]))
Before exporting the mesh, we can downsample the result to an acceptable number of triangles, for example, 100k triangles:
dec_mesh = mesh.simplify_quadric_decimation(100000)
Additionally, if you think the mesh can present some weird artifacts, you can run the following commands to ensure its consistency:
dec_mesh.remove_degenerate_triangles()dec_mesh.remove_duplicated_triangles()dec_mesh.remove_duplicated_vertices()dec_mesh.remove_non_manifold_edges()
🤓 Note: The strategy is available starting the version 0.9.0.0 of Open3D, thus, it will only work remotely at the moment. You can execute it through my provided google colab code offered here.
To get results with Poisson, it is very straightforward. You just have to adjust the parameters that you pass to the function as described above:
poisson_mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd, depth=8, width=0, scale=1.1, linear_fit=False)[0]
🤓 Note: The function output a list composed of an o3d.geometry object followed by a Numpy array. You want to select only the o3d.geometry justifying the [0] at the end.
To get a clean result, it is often necessary to add a cropping step to clean unwanted artifacts highlighted as yellow from the left image below:
For this, we compute the initial bounding-box containing the raw point cloud, and we use it to filter all surfaces from the mesh outside the bounding-box:
bbox = pcd.get_axis_aligned_bounding_box()p_mesh_crop = poisson_mesh.crop(bbox)
You now have one or more variables that each hold the mesh geometry, well Well done! The final step to get it in your application is to export it!
Exporting the data is straightforward with the write_triangle_mesh function. We just specify within the name of the created file, the extension that we want from .ply, .obj, .stl or .gltf, and the mesh to export. Below, we export both the BPA and Poisson’s reconstructions as .ply files:
o3d.io.write_triangle_mesh(output_path+"bpa_mesh.ply", dec_mesh)o3d.io.write_triangle_mesh(output_path+"p_mesh_c.ply", p_mesh_crop)
To quickly generate Levels of Details (LoD), let us write your first function. It will be really simple. The function will take as parameters a mesh, a list of LoD (as a target number of triangles), the file format of the resulting files and the path to write the files to. The function (to write in the script) looks like this:
def lod_mesh_export(mesh, lods, extension, path): mesh_lods={} for i in lods: mesh_lod = mesh.simplify_quadric_decimation(i) o3d.io.write_triangle_mesh(path+"lod_"+str(i)+extension, mesh_lod) mesh_lods[i]=mesh_lod print("generation of "+str(i)+" LoD successful") return mesh_lods
💡 Hint: I will cover the basics of what the function does and how it is structured in another article. At this point, it is useful to know that the function will (1) export the data to a specified location of your choice in the desire file format, and (2) give the possibility to store the results in a variable if more processing is needed within python.
The function makes some magic, but once executed, it looks like nothing happens. Don’t worry, your program now knows what lod_mesh_export is, and you can directly call it in the console, where we just change the parameters by the desired values:
my_lods = lod_mesh_export(bpa_mesh, [100000,50000,10000,1000,100], ".ply", output_path)
What is very interesting, is that now you don’t need to rewrite a bunch of code every time for different LoDs. You just have to pass different parameters to the function:
my_lods2 = lod_mesh_export(bpa_mesh, [8000,800,300], ".ply", output_path)
If you want to visualize within python a specific LoD, let us say the LoD with 100 triangles, you can access and visualize it through the command:
o3d.visualization.draw_geometries([my_lods[100]])
To visualize outside of python, you can use the software of your choosing (E.g Open-source Blender, MeshLab and CloudCompare) and load exported files within the GUI. Directly on the web through WebGL, you can use Three.js editor or Flyvast to simply access the mesh as well.
Finally, you can import it in any 3D printing software and get quotations about how much it would cost through online printing services 🤑.
Bravo. In this 5-Step guide, we covered how to set-up an automatic python 3D mesh creator from a point cloud. This is a very nice tool that will prove very handy in many 3D automation projects! However, we assumed that the point cloud is already noise-free, and that the normals are well-oriented.
If this is not the case, then some additional steps are needed and some great insights already discussed in the article below will be cover in another article
The full code is accessible here: Google Colab notebook
You just learned how to import, mesh, export and visualize a point cloud composed of millions of points, with different LoD! Well done! But the path does not end here, and future posts will dive deeper in point cloud spatial analysis, file formats, data structures, visualization, animation and meshing. We will especially look into how to manage big point cloud data as defined in the article below.
towardsdatascience.com
My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy
learngeodata.eu
1. Bernardini, F.; Mittleman, J.; Rushmeier, H.; Silva, C.; Taubin, G. The ball-pivoting algorithm for surface reconstruction. Transactions on Visualization and Computer Graphics 1999, 5, 349–359.
2. Kazhdan, M.; Bolitho, M.; Hoppe, H. Poisson surface reconstruction. Eurographics symposium on Geometry processing 2006, 1–10. | [
{
"code": null,
"e": 608,
"s": 172,
"text": "In this article, I will give you my 3D surface reconstruction process for quickly creating a mesh from point clouds with python. You will be able to export, visualize and integrate results into your favorite 3D software, without any coding experience. Additionally, I will provide you with a simple way to generate multiple Levels of Details (LoD), useful if you want to create real-time applications (E.g. Virtual Reality with Unity)."
},
{
"code": null,
"e": 1000,
"s": 608,
"text": "3D meshes are geometric data structures most often composed of a bunch of connected triangles that explicitly describe a surface 🤔. They are used in a wide range of applications from geospatial reconstructions to VFX, movies and video games. I often create them when a physical replica is demanded or if I need to integrate environments in game engines, where point cloud support is limited."
},
{
"code": null,
"e": 1379,
"s": 1000,
"text": "They are well integrated in most of the software professionals work with. On top, if you want to explore the wonder of 3D printing, you need to be able to generate a consistent mesh from the data that you have. This article is designed to offer you an efficient workflow in 5 customizable steps along with my script remotely executable at the end of the article. Let us dive in!"
},
{
"code": null,
"e": 1574,
"s": 1379,
"text": "In the previous article, we saw how to set-up an environment easily with Anaconda, and how to use the GUI Spyder for managing your code. We will continue in this fashion, using only 2 libraries."
},
{
"code": null,
"e": 1597,
"s": 1574,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1917,
"s": 1597,
"text": "For getting a 3D mesh automatically out of a point cloud, we will add another library to our environment, Open3D. It is an open-source library that allows the use of a set of efficient data structures and algorithms for 3D data processing. The installation necessitates to click on the ▶️ icon next to your environment."
},
{
"code": null,
"e": 1966,
"s": 1917,
"text": "Open the Terminal and run the following command:"
},
{
"code": null,
"e": 2012,
"s": 1966,
"text": "conda install -c open3d-admin open3d==0.8.0.0"
},
{
"code": null,
"e": 2297,
"s": 2012,
"text": "🤓 Note: The Open3D package is compatible with python version 2.7, 3.5 and 3.6. If you have another, you can either create a new environment (best) or if you start from the previous article, change the python version in your terminal by typing conda install python=3.5 in the Terminal."
},
{
"code": null,
"e": 2473,
"s": 2297,
"text": "This will install the package and its dependencies automatically, you can just input y when prompted in the terminal to allow this process. You are now set-up for the project."
},
{
"code": null,
"e": 2596,
"s": 2473,
"text": "Launch your python scripting tool (Spyder GUI, Jupyter or Google Colab), where we will call 2 libraries: Numpy and Open3D."
},
{
"code": null,
"e": 2635,
"s": 2596,
"text": "import numpy as npimport open3d as o3d"
},
{
"code": null,
"e": 2708,
"s": 2635,
"text": "Then, we create variables that hold data paths and the point cloud data:"
},
{
"code": null,
"e": 2857,
"s": 2708,
"text": "input_path=\"your_path_to_file/\"output_path=\"your_path_to_output_folder/\"dataname=\"sample.xyz\"point_cloud= np.loadtxt(input_path+dataname,skiprows=1)"
},
{
"code": null,
"e": 3077,
"s": 2857,
"text": "🤓 Note: As for the previous post, we will use a sampled point cloud that you can freely download from this repository. If you want to visualize it beforehand without installing anything, you can check the webGL version."
},
{
"code": null,
"e": 3207,
"s": 3077,
"text": "Finally, we transform the point_cloud variable type from Numpy to the Open3D o3d.geometry.PointCloud type for further processing:"
},
{
"code": null,
"e": 3420,
"s": 3207,
"text": "pcd = o3d.geometry.PointCloud()pcd.points = o3d.utility.Vector3dVector(point_cloud[:,:3])pcd.colors = o3d.utility.Vector3dVector(point_cloud[:,3:6]/255)pcd.normals = o3d.utility.Vector3dVector(point_cloud[:,6:9])"
},
{
"code": null,
"e": 3572,
"s": 3420,
"text": "🤓 Note: The following command first instantiates the Open3d point cloud object, then add points, color and normals to it from the original NumPy array."
},
{
"code": null,
"e": 3682,
"s": 3572,
"text": "For a quick visual of what you loaded, you can execute the following command (does not work in Google Colab):"
},
{
"code": null,
"e": 3723,
"s": 3682,
"text": "o3d.visualization.draw_geometries([pcd])"
},
{
"code": null,
"e": 4016,
"s": 3723,
"text": "Now we are ready to start the surface reconstruction process by meshing the pcd point cloud. I will give my favorite way to efficiently obtain results, but before we dive in, some condensed details ar necessary to grasp the underlying processes. I will limit myself to two meshing strategies."
},
{
"code": null,
"e": 4340,
"s": 4016,
"text": "The idea behind the Ball-Pivoting Algorithm (BPA) is to simulate the use of a virtual ball to generate a mesh from a point cloud. We first assume that the given point cloud consists of points sampled from the surface of an object. Points must strictly represent a surface (noise-free), that the reconstructed mesh explicit."
},
{
"code": null,
"e": 5076,
"s": 4340,
"text": "Using this assumption, imagine rolling a tiny ball across the point cloud “surface”. This tiny ball is dependent on the scale of the mesh, and should be slightly larger than the average space between points. When you drop a ball onto the surface of points, the ball will get caught and settle upon three points that will form the seed triangle. From that location, the ball rolls along the triangle edge formed from two points. The ball then settles in a new location: a new triangle is formed from two of the previous vertices and one new triangle is added to the mesh. As we continue rolling and pivoting the ball, new triangles are formed and added to the mesh. The ball continues rolling and rolling until the mesh is fully formed."
},
{
"code": null,
"e": 5216,
"s": 5076,
"text": "The idea behind the Ball-Pivoting Algorithm is simple, but of course, there are many caveats to the procedure as originally expressed here:"
},
{
"code": null,
"e": 5441,
"s": 5216,
"text": "How is the ball radius chosen? The radius, is obtained empirically based on the size and scale of the input point cloud. In theory, the diameter of the ball should be slightly larger than the average distance between points."
},
{
"code": null,
"e": 5876,
"s": 5441,
"text": "What if the points are too far apart at some locations and the ball falls through? When the ball pivots along an edge, it may miss the appropriate point on the surface and instead hit another point on the object or even exactly its three old points. In this case, we check that the normal of the new triangle Facet is consistently oriented with the point's Vertex normals. If it is not, then we reject that triangle and create a hole."
},
{
"code": null,
"e": 6194,
"s": 5876,
"text": "What if the surface has a crease or valley, such that the distance between the surface and itself is less than the size of the ball? In this case, the ball would just roll over the crease and ignore the points within the crease. But, this is not ideal behavior as the reconstructed mesh is not accurate to the object."
},
{
"code": null,
"e": 6499,
"s": 6194,
"text": "What if the surface is spaced into regions of points such that the ball cannot successfully roll between the regions? The virtual ball is dropped onto the surface multiple times at varying locations. This ensures that the ball captures the entire mesh, even when the points are inconsistently spaced out."
},
{
"code": null,
"e": 6957,
"s": 6499,
"text": "The Poisson Reconstruction is a bit more technical/mathematical. Its approach is known as an implicit meshing method, which I would describe as trying to “envelop” the data in a smooth cloth. Without going into too many details, we try to fit a watertight surface from the original point set by creating an entirely new point set representing an isosurface linked to the normals. There are several parameters available that affect the result of the meshing:"
},
{
"code": null,
"e": 7379,
"s": 6957,
"text": "Which depth? a tree-depth is used for the reconstruction. The higher the more detailed the mesh (Default: 8). With noisy data you keep vertices in the generated mesh that are outliers but the algorithm doesn’t detect them as such. So a low value (maybe between 5 and 7) provides a smoothing effect, but you will lose detail. The higher the depth-value the higher is the resulting amount of vertices of the generated mesh."
},
{
"code": null,
"e": 7676,
"s": 7379,
"text": "Which width? This specifies the target width of the finest level of the tree structure, which is called an octree 🤯. Don’t worry, I will cover this and best data structures for 3D in another article as it extends the scope of this one. Anyway, this parameter is ignored if the depth is specified."
},
{
"code": null,
"e": 7880,
"s": 7676,
"text": "Which scale? It describes the ratio between the diameter of the cube used for reconstruction and the diameter of the samples’ bounding cube. Very abstract, the default parameter usually works well (1.1)."
},
{
"code": null,
"e": 8022,
"s": 7880,
"text": "Which fit? the linear_fit parameter if set to true, let the reconstructor use linear interpolation to estimate the positions of iso-vertices."
},
{
"code": null,
"e": 8149,
"s": 8022,
"text": "We first compute the necessary radius parameter based on the average distances computed from all the distances between points:"
},
{
"code": null,
"e": 8251,
"s": 8149,
"text": "distances = pcd.compute_nearest_neighbor_distance()avg_dist = np.mean(distances)radius = 3 * avg_dist"
},
{
"code": null,
"e": 8337,
"s": 8251,
"text": "In one command line, we can then create a mesh and store it in the bpa_mesh variable:"
},
{
"code": null,
"e": 8464,
"s": 8337,
"text": "bpa_mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_ball_pivoting(pcd,o3d.utility.DoubleVector([radius, radius * 2]))"
},
{
"code": null,
"e": 8587,
"s": 8464,
"text": "Before exporting the mesh, we can downsample the result to an acceptable number of triangles, for example, 100k triangles:"
},
{
"code": null,
"e": 8639,
"s": 8587,
"text": "dec_mesh = mesh.simplify_quadric_decimation(100000)"
},
{
"code": null,
"e": 8771,
"s": 8639,
"text": "Additionally, if you think the mesh can present some weird artifacts, you can run the following commands to ensure its consistency:"
},
{
"code": null,
"e": 8921,
"s": 8771,
"text": "dec_mesh.remove_degenerate_triangles()dec_mesh.remove_duplicated_triangles()dec_mesh.remove_duplicated_vertices()dec_mesh.remove_non_manifold_edges()"
},
{
"code": null,
"e": 9114,
"s": 8921,
"text": "🤓 Note: The strategy is available starting the version 0.9.0.0 of Open3D, thus, it will only work remotely at the moment. You can execute it through my provided google colab code offered here."
},
{
"code": null,
"e": 9260,
"s": 9114,
"text": "To get results with Poisson, it is very straightforward. You just have to adjust the parameters that you pass to the function as described above:"
},
{
"code": null,
"e": 9388,
"s": 9260,
"text": "poisson_mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(pcd, depth=8, width=0, scale=1.1, linear_fit=False)[0]"
},
{
"code": null,
"e": 9557,
"s": 9388,
"text": "🤓 Note: The function output a list composed of an o3d.geometry object followed by a Numpy array. You want to select only the o3d.geometry justifying the [0] at the end."
},
{
"code": null,
"e": 9702,
"s": 9557,
"text": "To get a clean result, it is often necessary to add a cropping step to clean unwanted artifacts highlighted as yellow from the left image below:"
},
{
"code": null,
"e": 9857,
"s": 9702,
"text": "For this, we compute the initial bounding-box containing the raw point cloud, and we use it to filter all surfaces from the mesh outside the bounding-box:"
},
{
"code": null,
"e": 9937,
"s": 9857,
"text": "bbox = pcd.get_axis_aligned_bounding_box()p_mesh_crop = poisson_mesh.crop(bbox)"
},
{
"code": null,
"e": 10084,
"s": 9937,
"text": "You now have one or more variables that each hold the mesh geometry, well Well done! The final step to get it in your application is to export it!"
},
{
"code": null,
"e": 10372,
"s": 10084,
"text": "Exporting the data is straightforward with the write_triangle_mesh function. We just specify within the name of the created file, the extension that we want from .ply, .obj, .stl or .gltf, and the mesh to export. Below, we export both the BPA and Poisson’s reconstructions as .ply files:"
},
{
"code": null,
"e": 10504,
"s": 10372,
"text": "o3d.io.write_triangle_mesh(output_path+\"bpa_mesh.ply\", dec_mesh)o3d.io.write_triangle_mesh(output_path+\"p_mesh_c.ply\", p_mesh_crop)"
},
{
"code": null,
"e": 10833,
"s": 10504,
"text": "To quickly generate Levels of Details (LoD), let us write your first function. It will be really simple. The function will take as parameters a mesh, a list of LoD (as a target number of triangles), the file format of the resulting files and the path to write the files to. The function (to write in the script) looks like this:"
},
{
"code": null,
"e": 11146,
"s": 10833,
"text": "def lod_mesh_export(mesh, lods, extension, path): mesh_lods={} for i in lods: mesh_lod = mesh.simplify_quadric_decimation(i) o3d.io.write_triangle_mesh(path+\"lod_\"+str(i)+extension, mesh_lod) mesh_lods[i]=mesh_lod print(\"generation of \"+str(i)+\" LoD successful\") return mesh_lods"
},
{
"code": null,
"e": 11502,
"s": 11146,
"text": "💡 Hint: I will cover the basics of what the function does and how it is structured in another article. At this point, it is useful to know that the function will (1) export the data to a specified location of your choice in the desire file format, and (2) give the possibility to store the results in a variable if more processing is needed within python."
},
{
"code": null,
"e": 11748,
"s": 11502,
"text": "The function makes some magic, but once executed, it looks like nothing happens. Don’t worry, your program now knows what lod_mesh_export is, and you can directly call it in the console, where we just change the parameters by the desired values:"
},
{
"code": null,
"e": 11836,
"s": 11748,
"text": "my_lods = lod_mesh_export(bpa_mesh, [100000,50000,10000,1000,100], \".ply\", output_path)"
},
{
"code": null,
"e": 12007,
"s": 11836,
"text": "What is very interesting, is that now you don’t need to rewrite a bunch of code every time for different LoDs. You just have to pass different parameters to the function:"
},
{
"code": null,
"e": 12081,
"s": 12007,
"text": "my_lods2 = lod_mesh_export(bpa_mesh, [8000,800,300], \".ply\", output_path)"
},
{
"code": null,
"e": 12228,
"s": 12081,
"text": "If you want to visualize within python a specific LoD, let us say the LoD with 100 triangles, you can access and visualize it through the command:"
},
{
"code": null,
"e": 12278,
"s": 12228,
"text": "o3d.visualization.draw_geometries([my_lods[100]])"
},
{
"code": null,
"e": 12553,
"s": 12278,
"text": "To visualize outside of python, you can use the software of your choosing (E.g Open-source Blender, MeshLab and CloudCompare) and load exported files within the GUI. Directly on the web through WebGL, you can use Three.js editor or Flyvast to simply access the mesh as well."
},
{
"code": null,
"e": 12692,
"s": 12553,
"text": "Finally, you can import it in any 3D printing software and get quotations about how much it would cost through online printing services 🤑."
},
{
"code": null,
"e": 12990,
"s": 12692,
"text": "Bravo. In this 5-Step guide, we covered how to set-up an automatic python 3D mesh creator from a point cloud. This is a very nice tool that will prove very handy in many 3D automation projects! However, we assumed that the point cloud is already noise-free, and that the normals are well-oriented."
},
{
"code": null,
"e": 13149,
"s": 12990,
"text": "If this is not the case, then some additional steps are needed and some great insights already discussed in the article below will be cover in another article"
},
{
"code": null,
"e": 13205,
"s": 13149,
"text": "The full code is accessible here: Google Colab notebook"
},
{
"code": null,
"e": 13606,
"s": 13205,
"text": "You just learned how to import, mesh, export and visualize a point cloud composed of millions of points, with different LoD! Well done! But the path does not end here, and future posts will dive deeper in point cloud spatial analysis, file formats, data structures, visualization, animation and meshing. We will especially look into how to manage big point cloud data as defined in the article below."
},
{
"code": null,
"e": 13629,
"s": 13606,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 13836,
"s": 13629,
"text": "My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy"
},
{
"code": null,
"e": 13852,
"s": 13836,
"text": "learngeodata.eu"
},
{
"code": null,
"e": 14049,
"s": 13852,
"text": "1. Bernardini, F.; Mittleman, J.; Rushmeier, H.; Silva, C.; Taubin, G. The ball-pivoting algorithm for surface reconstruction. Transactions on Visualization and Computer Graphics 1999, 5, 349–359."
}
] |
Difference between ‘function declaration’ and ‘function expression' in JavaScript - GeeksforGeeks | 21 Sep, 2021
Functions in JavaScript allow us to carry out some set of actions, important decisions, or calculations and even makes our website more interactive. Most of us coding enthusiasts know what a function is. But do we know what’s the difference between function declarations and function expressions? This article let us learn the difference between ‘function declaration’ and ‘function expression’. The similarity is both use the keyword function and the most prominent difference being the function declaration has a function name while the latter doesn’t have one.
Function Declaration:
A function declaration also known as a function statement declares a function with a function keyword. The function declaration must have a function name.
Function declaration does not require a variable assignment as they are standalone constructs and they cannot be nested inside a functional block.
These are executed before any other code.
The function in function declaration can be accessed before and after the function definition.
Syntax:
function geeksforGeeks(paramA, paramB) {
// Set of statements
}
Function Expression:
A function Expression is similar to a function declaration without the function name.
Function expressions can be stored in a variable assignment.
Function expressions load and execute only when the program interpreter reaches the line of code.
The function in function declaration can be accessed only after the function definition.
Syntax:
var geeksforGeeks= function(paramA, paramB) {
// Set of statements
}
Example 1: Function Declaration
The following example illustrates a function declaration where we do the addition of two numbers.
HTML
<!DOCTYPE html><html> <head> <title>Function Declaration</title></head> <body> <h1 style="color:green">GFG</h1> <h2>Function Declaration</h2> <script> // Function Declaration function geeksforGeeks(paramA, paramB) { return paramA + paramB; } var result = geeksforGeeks(5, 5); document.write('Sum=', result); </script></body> </html>
Output:
Example 2: Function Expression
The following example illustrates a function expression where we do the addition of two numbers.
HTML
<!DOCTYPE html><html> <head> <title>Function Declaration</title></head> <body> <h1 style="color:green">GFG</h1> <h2>Function Expression</h2> <script> // Function Expression var geeksforGeeks = function (paramA, paramB) { return paramA + paramB; } var result = geeksforGeeks(5, 5); document.write('Sum=', result); </script></body> </html>
Output:
Difference between Function Declaration and Function Expression:
Blogathon-2021
javascript-functions
JavaScript-Questions
Picked
Blogathon
Difference Between
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
SQL Query to Convert Datetime to Date
SQL Query to Create Table With a Primary Key
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between == and .equals() Method in Java | [
{
"code": null,
"e": 24840,
"s": 24812,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 25404,
"s": 24840,
"text": "Functions in JavaScript allow us to carry out some set of actions, important decisions, or calculations and even makes our website more interactive. Most of us coding enthusiasts know what a function is. But do we know what’s the difference between function declarations and function expressions? This article let us learn the difference between ‘function declaration’ and ‘function expression’. The similarity is both use the keyword function and the most prominent difference being the function declaration has a function name while the latter doesn’t have one."
},
{
"code": null,
"e": 25426,
"s": 25404,
"text": "Function Declaration:"
},
{
"code": null,
"e": 25581,
"s": 25426,
"text": "A function declaration also known as a function statement declares a function with a function keyword. The function declaration must have a function name."
},
{
"code": null,
"e": 25728,
"s": 25581,
"text": "Function declaration does not require a variable assignment as they are standalone constructs and they cannot be nested inside a functional block."
},
{
"code": null,
"e": 25770,
"s": 25728,
"text": "These are executed before any other code."
},
{
"code": null,
"e": 25865,
"s": 25770,
"text": "The function in function declaration can be accessed before and after the function definition."
},
{
"code": null,
"e": 25873,
"s": 25865,
"text": "Syntax:"
},
{
"code": null,
"e": 25941,
"s": 25873,
"text": "function geeksforGeeks(paramA, paramB) {\n // Set of statements\n}"
},
{
"code": null,
"e": 25962,
"s": 25941,
"text": "Function Expression:"
},
{
"code": null,
"e": 26048,
"s": 25962,
"text": "A function Expression is similar to a function declaration without the function name."
},
{
"code": null,
"e": 26109,
"s": 26048,
"text": "Function expressions can be stored in a variable assignment."
},
{
"code": null,
"e": 26207,
"s": 26109,
"text": "Function expressions load and execute only when the program interpreter reaches the line of code."
},
{
"code": null,
"e": 26296,
"s": 26207,
"text": "The function in function declaration can be accessed only after the function definition."
},
{
"code": null,
"e": 26306,
"s": 26298,
"text": "Syntax:"
},
{
"code": null,
"e": 26379,
"s": 26306,
"text": "var geeksforGeeks= function(paramA, paramB) {\n // Set of statements\n}"
},
{
"code": null,
"e": 26411,
"s": 26379,
"text": "Example 1: Function Declaration"
},
{
"code": null,
"e": 26509,
"s": 26411,
"text": "The following example illustrates a function declaration where we do the addition of two numbers."
},
{
"code": null,
"e": 26514,
"s": 26509,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Function Declaration</title></head> <body> <h1 style=\"color:green\">GFG</h1> <h2>Function Declaration</h2> <script> // Function Declaration function geeksforGeeks(paramA, paramB) { return paramA + paramB; } var result = geeksforGeeks(5, 5); document.write('Sum=', result); </script></body> </html>",
"e": 26921,
"s": 26514,
"text": null
},
{
"code": null,
"e": 26929,
"s": 26921,
"text": "Output:"
},
{
"code": null,
"e": 26960,
"s": 26929,
"text": "Example 2: Function Expression"
},
{
"code": null,
"e": 27057,
"s": 26960,
"text": "The following example illustrates a function expression where we do the addition of two numbers."
},
{
"code": null,
"e": 27062,
"s": 27057,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Function Declaration</title></head> <body> <h1 style=\"color:green\">GFG</h1> <h2>Function Expression</h2> <script> // Function Expression var geeksforGeeks = function (paramA, paramB) { return paramA + paramB; } var result = geeksforGeeks(5, 5); document.write('Sum=', result); </script></body> </html>",
"e": 27474,
"s": 27062,
"text": null
},
{
"code": null,
"e": 27482,
"s": 27474,
"text": "Output:"
},
{
"code": null,
"e": 27547,
"s": 27482,
"text": "Difference between Function Declaration and Function Expression:"
},
{
"code": null,
"e": 27562,
"s": 27547,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 27583,
"s": 27562,
"text": "javascript-functions"
},
{
"code": null,
"e": 27604,
"s": 27583,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 27611,
"s": 27604,
"text": "Picked"
},
{
"code": null,
"e": 27621,
"s": 27611,
"text": "Blogathon"
},
{
"code": null,
"e": 27640,
"s": 27621,
"text": "Difference Between"
},
{
"code": null,
"e": 27651,
"s": 27640,
"text": "JavaScript"
},
{
"code": null,
"e": 27668,
"s": 27651,
"text": "Web Technologies"
},
{
"code": null,
"e": 27766,
"s": 27668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27807,
"s": 27766,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 27864,
"s": 27807,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27899,
"s": 27864,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 27937,
"s": 27899,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 27982,
"s": 27937,
"text": "SQL Query to Create Table With a Primary Key"
},
{
"code": null,
"e": 28013,
"s": 27982,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 28053,
"s": 28013,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 28085,
"s": 28053,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 28146,
"s": 28085,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Watir - Cookies | In this chapter, we will learn how to work with cookies using Watir.
A simple example that will fetch the cookies for a URL given is discussed here.
browser.cookies.to_a
require 'watir'
b = Watir::Browser.new :chrome
b.goto 'https://www.tutorialspoint.com'
puts b.cookies.to_a
{:name=>"_gat_gtag_UA_232293_6", :value=>"1", :path=>"/",
:domain=>".tutorialspoint.com", :expires=>2019-05-03 08:33:58 +0000,
:secure=>false}
{:name=>"_gid", :value=> "GA1.2.282573155.1556872379", :path=>"/",
:domain=>".tutorialspoint.com", :expires=>2019-05-04 08:32:57 +0000,
:secure=>false}
{:name=>"_ga", :value=>"GA1.2.2087825339.1556872379", :path=>"/",
:domain=>".tutorialspoint.com", :expires=>
2021-05-02 08:32:57 +0000, :secure=>false}
Now let us add cookies as shown below −
browser.cookies.add 'cookiename', 'cookievalue', path: '/', expires:
(Time.now + 10000), secure: true
require 'watir'
b = Watir::Browser.new :chrome
b.goto 'https://www.tutorialspoint.com'
puts b.cookies.to_a
b.cookies.add 'cookie1', 'testing_cookie', path: '/', expires:
(Time.now + 10000), secure: true
puts b.cookies.to_a
{:name=>"_gat_gtag_UA_232293_6", :value=>"1", :path=>"/",
:domain=>".tutorialspoint.com", :expires=>2019-05-03 08:44:23 +0000,
:secure=>false}
{:name=>"_gid", :value=>"GA1.2.1541488984.1556873004",
:path=>"/", :domain=>".tutorialspoint.com",
:expires=>2019-05-04 08:43:24 +0000, :secure=>false}
{:name=>"_ga", :value=>"GA1.2.1236163943.1556873004",
:path=>"/", :domain=>".tutorialspoint.com",
:expires=>2021-05-02 08:43:24 +0000, :secure=>false}
{:name=>"_gat_gtag_UA_232293_6", :value=>"1", :path=>"/",
:domain=>".tutorialspoint.com", :expires=>2019-05-03 08:44:23 +0000,
:secure=>false}
{:name=>"_gid", :value=>"GA1.2.1541488984.1556873004",
:path=>"/", :domain=>".tutorialspoint.com",
:expires=>2019-05-04 08:43:24 +0000, :secure=>false}
{:name=>"_ga", :value=>"GA1.2.1236163943.1556873004",
:path=>"/", :domain=>".tutorialspoint.com",
:expires=>2021-05-02 08:43:24 +0000, :secure=>false}
{:name=>"cookie1", :value=>"testing_cookie", :path=>"/",
:domain=>"www.tutorialspoint.com", :expires=>2039-04-28 08:43:35 +0000,
:secure=>true}
Note that the last one is the one we added using watir.
browser.cookies.clear
require 'watir'
b = Watir::Browser.new :chrome
b.goto 'https://www.tutorialspoint.com'
puts b.cookies.to_a
b.cookies.clear
puts b.cookies.to_a
{:name=>"_gat_gtag_UA_232293_6", :value=>"1", :path=>"/",
:domain=>".tutorialspoint.com", :expires=>2019-05-03 08:48:29 +0000,
:secure=>false}
{:name=>"_gid", :value=>"GA1.2.1264249563.1556873251",
:path=>"/", :domain=>".tutorialspoint.com",
:expires=>2019-05-04 08:47:30 +0000, :secure=>false}
{:name=>"_ga", :value=>"GA1.2.1001488637.1556873251",
:path=>"/", :domain=>".tutorialspoint.com",
:expires=>2021-05-02 08:47:30 +0000, :secure=>false
Empty response ie a blank line will get printed after cookie.clear is called.
browser.cookies.delete 'nameofthecookie'
require 'watir'
b = Watir::Browser.new :chrome
b.goto 'https://www.tutorialspoint.com'
puts b.cookies.to_a
puts b.cookies.delete "_ga"
puts b.cookies.to_a
All cookies:
{:name=>"_gat_gtag_UA_232293_6", :value=>"1", :path=>"/",
:domain=>".tutorialspoint.com", :expires=>2019-05-03 08:52:38 +0000,
:secure=>false}
{:name=>"_gid", :value=>"GA1.2.1385195240.1556873499",
:path=>"/", :domain=>".tutorialspoint.com",
:expires=>2019-05-04 08:51:37 +0000, :secure=>false}
{:name=>"_ga", :value=>"GA1.2.1383421835.1556873499",
:path=>"/", :domain=>".tutorialspoint.com",
:expires=>2021-05-02 08:51:37 +0000, :secure=>false}
After delete cookie with name _ga
{:name=>"_gat_gtag_UA_232293_6",
:value=>"1", :path=>"/", :domain=>".tutorialspoint.com",
:expires=>2019-05-03 08:52:38 +0000, :secure=>false}
{:name=>"_gid", :value=>"GA1.2.1385195240.1556873499",
:path=>"/", :domain=>".tutorialspoint.com",
:expires=>2019-05-04 08:51:37 +0000, :secure=>false}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2089,
"s": 2020,
"text": "In this chapter, we will learn how to work with cookies using Watir."
},
{
"code": null,
"e": 2169,
"s": 2089,
"text": "A simple example that will fetch the cookies for a URL given is discussed here."
},
{
"code": null,
"e": 2191,
"s": 2169,
"text": "browser.cookies.to_a\n"
},
{
"code": null,
"e": 2299,
"s": 2191,
"text": "require 'watir'\n\nb = Watir::Browser.new :chrome\nb.goto 'https://www.tutorialspoint.com'\nputs b.cookies.to_a"
},
{
"code": null,
"e": 2754,
"s": 2299,
"text": "{:name=>\"_gat_gtag_UA_232293_6\", :value=>\"1\", :path=>\"/\", \n:domain=>\".tutorialspoint.com\", :expires=>2019-05-03 08:33:58 +0000, \n:secure=>false}\n\n{:name=>\"_gid\", :value=> \"GA1.2.282573155.1556872379\", :path=>\"/\", \n:domain=>\".tutorialspoint.com\", :expires=>2019-05-04 08:32:57 +0000, \n:secure=>false}\n\n{:name=>\"_ga\", :value=>\"GA1.2.2087825339.1556872379\", :path=>\"/\", \n:domain=>\".tutorialspoint.com\", :expires=>\n2021-05-02 08:32:57 +0000, :secure=>false}\n"
},
{
"code": null,
"e": 2794,
"s": 2754,
"text": "Now let us add cookies as shown below −"
},
{
"code": null,
"e": 2898,
"s": 2794,
"text": "browser.cookies.add 'cookiename', 'cookievalue', path: '/', expires: \n(Time.now + 10000), secure: true\n"
},
{
"code": null,
"e": 3122,
"s": 2898,
"text": "require 'watir'\nb = Watir::Browser.new :chrome\nb.goto 'https://www.tutorialspoint.com'\nputs b.cookies.to_a\nb.cookies.add 'cookie1', 'testing_cookie', path: '/', expires: \n(Time.now + 10000), secure: true\nputs b.cookies.to_a"
},
{
"code": null,
"e": 3577,
"s": 3122,
"text": "{:name=>\"_gat_gtag_UA_232293_6\", :value=>\"1\", :path=>\"/\", \n:domain=>\".tutorialspoint.com\", :expires=>2019-05-03 08:44:23 +0000, \n:secure=>false}\n\n{:name=>\"_gid\", :value=>\"GA1.2.1541488984.1556873004\", \n:path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2019-05-04 08:43:24 +0000, :secure=>false}\n\n{:name=>\"_ga\", :value=>\"GA1.2.1236163943.1556873004\", \n:path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2021-05-02 08:43:24 +0000, :secure=>false}\n"
},
{
"code": null,
"e": 4179,
"s": 3577,
"text": "{:name=>\"_gat_gtag_UA_232293_6\", :value=>\"1\", :path=>\"/\", \n:domain=>\".tutorialspoint.com\", :expires=>2019-05-03 08:44:23 +0000, \n:secure=>false}\n\n{:name=>\"_gid\", :value=>\"GA1.2.1541488984.1556873004\", \n:path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2019-05-04 08:43:24 +0000, :secure=>false}\n\n{:name=>\"_ga\", :value=>\"GA1.2.1236163943.1556873004\", \n:path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2021-05-02 08:43:24 +0000, :secure=>false}\n\n{:name=>\"cookie1\", :value=>\"testing_cookie\", :path=>\"/\", \n:domain=>\"www.tutorialspoint.com\", :expires=>2039-04-28 08:43:35 +0000, \n:secure=>true}\n"
},
{
"code": null,
"e": 4235,
"s": 4179,
"text": "Note that the last one is the one we added using watir."
},
{
"code": null,
"e": 4258,
"s": 4235,
"text": "browser.cookies.clear\n"
},
{
"code": null,
"e": 4402,
"s": 4258,
"text": "require 'watir'\n\nb = Watir::Browser.new :chrome\nb.goto 'https://www.tutorialspoint.com'\nputs b.cookies.to_a\nb.cookies.clear\nputs b.cookies.to_a"
},
{
"code": null,
"e": 4935,
"s": 4402,
"text": "{:name=>\"_gat_gtag_UA_232293_6\", :value=>\"1\", :path=>\"/\", \n:domain=>\".tutorialspoint.com\", :expires=>2019-05-03 08:48:29 +0000, \n:secure=>false}\n\n{:name=>\"_gid\", :value=>\"GA1.2.1264249563.1556873251\", \n:path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2019-05-04 08:47:30 +0000, :secure=>false}\n\n{:name=>\"_ga\", :value=>\"GA1.2.1001488637.1556873251\", \n:path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2021-05-02 08:47:30 +0000, :secure=>false\n\nEmpty response ie a blank line will get printed after cookie.clear is called.\n"
},
{
"code": null,
"e": 4977,
"s": 4935,
"text": "browser.cookies.delete 'nameofthecookie'\n"
},
{
"code": null,
"e": 5132,
"s": 4977,
"text": "require 'watir'\nb = Watir::Browser.new :chrome\nb.goto 'https://www.tutorialspoint.com'\nputs b.cookies.to_a\nputs b.cookies.delete \"_ga\"\nputs b.cookies.to_a"
},
{
"code": null,
"e": 5935,
"s": 5132,
"text": "All cookies:\n{:name=>\"_gat_gtag_UA_232293_6\", :value=>\"1\", :path=>\"/\", \n:domain=>\".tutorialspoint.com\", :expires=>2019-05-03 08:52:38 +0000, \n:secure=>false}\n\n{:name=>\"_gid\", :value=>\"GA1.2.1385195240.1556873499\", \n:path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2019-05-04 08:51:37 +0000, :secure=>false}\n\n{:name=>\"_ga\", :value=>\"GA1.2.1383421835.1556873499\", \n:path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2021-05-02 08:51:37 +0000, :secure=>false}\n\nAfter delete cookie with name _ga\n{:name=>\"_gat_gtag_UA_232293_6\", \n:value=>\"1\", :path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2019-05-03 08:52:38 +0000, :secure=>false}\n\n{:name=>\"_gid\", :value=>\"GA1.2.1385195240.1556873499\", \n:path=>\"/\", :domain=>\".tutorialspoint.com\", \n:expires=>2019-05-04 08:51:37 +0000, :secure=>false}\n"
},
{
"code": null,
"e": 5942,
"s": 5935,
"text": " Print"
},
{
"code": null,
"e": 5953,
"s": 5942,
"text": " Add Notes"
}
] |
Using Mixed-Effects Models For Linear Regression | by Guido Vivaldi | Towards Data Science | Mixed-effects regression models are a powerful tool for linear regression models when your data contains global and group-level trends. This article walks through an example using fictitious data relating exercise to mood to introduce this concept. R has had an undeserved rough time in the news lately, so this post will use R as a small condolence to the language, though a robust framework exist in Python as well.
Mixed-effect models are common in political polling analysis where national-level characteristics are assumed to occur at a state-level while state-level sample sizes may be too small to drive those characteristics on their own. They are also common in scientific experiments where a given effect is assumed to be present among all study individuals which needs to be teased out from a specific effect on a treatment group. In a similar vein, this framework can be helpful in pre/post studies of interventions.
Data Analysis
This data simulates a survey of residents of 4 states who were asked about their daily exercise habits and their overall mood on a scale from 1–10. We’ll assume for purposes of example that mood scores are linear, but in the real world we may want to treat this as an ordinal variable. What we will see (because I made up the data) is that exercise improves mood, however there are strong state-level effects.
summary(data)
First Try: Fixed-Effect Linear Regression
There are clear positive correlations between exercise and mood, though the model fit is not great: exercise is a significant predictor, though adjusted r-squared is fairly low. By the way, I love using R for quick regression questions: a clear, comprehensive output is often easy to find.
reg1 <- lm(Mood ~ Exercise, data = data) summary(reg1) with(data, plot(Exercise, Mood))abline(reg1)
We may conclude at this point that the data is noisy, but let’s dig a little deeper. Recall that one of the assumptions of linear regression is “homoscedasticity”, i.e. that variance is constant among for all independent variables. When heteroscedasticity is present (and homoscedasticity is violated), the regression may give too much weight to the subset of data where the error variance is the largest. You can validate this assumption by looking at a residuals plot.
For reference, below is a linear regression that does not violate homoscedasticity.
x <- rnorm(25, 0, 1)y = 2*x - 0.5 + rnorm(25, 0, 0.25)reg.test <- lm(y ~ x) plot(x, y)abline(reg.test)plot(x, resid(reg.test), ylab="Residuals", xlab="x") abline(0, 0)
And then there is our data:
plot(data$Mood, resid(reg1), ylab="Residuals", xlab="Mood") abline(0, 0)
This plot shows that a simple linear regression is not appropriate — the model consistently produces negative residuals for low mood scores, and positive residuals for high mood scores. We might suspect at this point that mood and state are correlated in a way or model is not incorporating, which is a good guess => variance in residuals differs by state.
plot(data$State, resid(reg1), ylab="Residuals", xlab="Mood") abline(0, 0)
Second Try: A More Robust Linear Regression
But wait — if state is a predictor, let’s include it in our regression and fix everything. We’ll see that this is mostly correct.
reg2 <- lm(Mood ~ Exercise + State, data = data) summary(reg1) with(data, plot(Exercise, Mood))abline(reg2)plot(data$State, resid(reg2), ylab="Residuals", xlab="State") abline(0, 0)
R-squared improves significantly, but now the plotted line looks awfully goofy — we consistently undershoot, and the coefficient estimate for Exercise is near zero (and has a non-significant p-value). This is an example of the effect of heteroskedasticity — the groups (i.e. states) with larger variance override groups with smaller variance.
We’re getting somewhere. What if we did a separate linear regression for each state? That way we’re not going to have problems with group interactions skewing our coefficients, right?
library(ggplot2)ggplot(data, aes(x = Exercise, y = Mood, color = State)) + geom_point() + geom_smooth(method='lm',formula=y~x)
Well, we have an opposite problem now — notice that in state C exercise is now decreasing mood. and the slope coefficient in other states is much lower than the 0.42951 that we saw in the Mood ~ Exercise regression. So now there is information in the high-level model that we’re neglecting because of our focus on the state-level models.
Mixed-Effect Models
The final example above leads right into a mixed-effect model. In this model, we can allow the state-level regressions to incorporate some of the information from the overall regression, but also retain some state-level components. We can use the lme4 library to do this.
The notation is similar to an lm regression with a key difference: the (1 + Exercise | State) notation allows the model to use a term with different slopes and intercepts for Mood ~ Exercise for each State value. See the coefficient values below.
library(lme4)reg3 <- lmer(Mood ~ Exercise + (1 + Exercise | State), data = data, REML = FALSE)summary(reg3)coef(reg3)
We have run 3 models now:
Mood ~ ExerciseMood ~ Exercise + StateMood ~ Exercise + (1 + Exercise | State)
Mood ~ Exercise
Mood ~ Exercise + State
Mood ~ Exercise + (1 + Exercise | State)
We can calculate the RMSE of each model.
reg1_predict <- predict(reg1, data[1:2])reg2_predict <- predict(reg2, data[1:2])reg3_predict <- predict(reg3, data[1:2])sqrt(sum((data[3] - reg1_predict)**2))sqrt(sum((data[3] - reg2_predict)**2))sqrt(sum((data[3] - reg3_predict)**2))
RMSE improved significantly moving from models 2 to 3 — this suggests that the majority of the difference between states and mood is due to average mood in each state. Moving from model 2 to 3 captured this state-level intercept information, but also calculated a slope coefficient for Mood ~ Exercise for each state which incorporated information from the total dataset and from the state-level information (recall that using only state-level slope information produced a negative slope in State C).
A few final notes on Mixed-Effect Models. There are multiple approaches and ongoing research into how to determine p-values for mixed-effect models. One can use an anova likelihood test to determine if an added variable is significant with respect to a model without that added variable.
Conclusion
Mixed-Effect models provide a framework for smoothing global and group level characteristics in your data.
I learned about these models primarily from Richard McElreath and his wonderful text Statistical Rethinking. I’d recommend it highly to any reader: it is a great help in rethinking many of the statistical assumptions that were made for me in entry-level classes that I never knew to reconsider.
OJ Watson also has a well-done Kaggle post that presents a python-based framework for mixed-effect models. | [
{
"code": null,
"e": 590,
"s": 172,
"text": "Mixed-effects regression models are a powerful tool for linear regression models when your data contains global and group-level trends. This article walks through an example using fictitious data relating exercise to mood to introduce this concept. R has had an undeserved rough time in the news lately, so this post will use R as a small condolence to the language, though a robust framework exist in Python as well."
},
{
"code": null,
"e": 1101,
"s": 590,
"text": "Mixed-effect models are common in political polling analysis where national-level characteristics are assumed to occur at a state-level while state-level sample sizes may be too small to drive those characteristics on their own. They are also common in scientific experiments where a given effect is assumed to be present among all study individuals which needs to be teased out from a specific effect on a treatment group. In a similar vein, this framework can be helpful in pre/post studies of interventions."
},
{
"code": null,
"e": 1115,
"s": 1101,
"text": "Data Analysis"
},
{
"code": null,
"e": 1525,
"s": 1115,
"text": "This data simulates a survey of residents of 4 states who were asked about their daily exercise habits and their overall mood on a scale from 1–10. We’ll assume for purposes of example that mood scores are linear, but in the real world we may want to treat this as an ordinal variable. What we will see (because I made up the data) is that exercise improves mood, however there are strong state-level effects."
},
{
"code": null,
"e": 1539,
"s": 1525,
"text": "summary(data)"
},
{
"code": null,
"e": 1581,
"s": 1539,
"text": "First Try: Fixed-Effect Linear Regression"
},
{
"code": null,
"e": 1871,
"s": 1581,
"text": "There are clear positive correlations between exercise and mood, though the model fit is not great: exercise is a significant predictor, though adjusted r-squared is fairly low. By the way, I love using R for quick regression questions: a clear, comprehensive output is often easy to find."
},
{
"code": null,
"e": 1971,
"s": 1871,
"text": "reg1 <- lm(Mood ~ Exercise, data = data) summary(reg1) with(data, plot(Exercise, Mood))abline(reg1)"
},
{
"code": null,
"e": 2442,
"s": 1971,
"text": "We may conclude at this point that the data is noisy, but let’s dig a little deeper. Recall that one of the assumptions of linear regression is “homoscedasticity”, i.e. that variance is constant among for all independent variables. When heteroscedasticity is present (and homoscedasticity is violated), the regression may give too much weight to the subset of data where the error variance is the largest. You can validate this assumption by looking at a residuals plot."
},
{
"code": null,
"e": 2526,
"s": 2442,
"text": "For reference, below is a linear regression that does not violate homoscedasticity."
},
{
"code": null,
"e": 2694,
"s": 2526,
"text": "x <- rnorm(25, 0, 1)y = 2*x - 0.5 + rnorm(25, 0, 0.25)reg.test <- lm(y ~ x) plot(x, y)abline(reg.test)plot(x, resid(reg.test), ylab=\"Residuals\", xlab=\"x\") abline(0, 0)"
},
{
"code": null,
"e": 2722,
"s": 2694,
"text": "And then there is our data:"
},
{
"code": null,
"e": 2795,
"s": 2722,
"text": "plot(data$Mood, resid(reg1), ylab=\"Residuals\", xlab=\"Mood\") abline(0, 0)"
},
{
"code": null,
"e": 3152,
"s": 2795,
"text": "This plot shows that a simple linear regression is not appropriate — the model consistently produces negative residuals for low mood scores, and positive residuals for high mood scores. We might suspect at this point that mood and state are correlated in a way or model is not incorporating, which is a good guess => variance in residuals differs by state."
},
{
"code": null,
"e": 3226,
"s": 3152,
"text": "plot(data$State, resid(reg1), ylab=\"Residuals\", xlab=\"Mood\") abline(0, 0)"
},
{
"code": null,
"e": 3270,
"s": 3226,
"text": "Second Try: A More Robust Linear Regression"
},
{
"code": null,
"e": 3400,
"s": 3270,
"text": "But wait — if state is a predictor, let’s include it in our regression and fix everything. We’ll see that this is mostly correct."
},
{
"code": null,
"e": 3582,
"s": 3400,
"text": "reg2 <- lm(Mood ~ Exercise + State, data = data) summary(reg1) with(data, plot(Exercise, Mood))abline(reg2)plot(data$State, resid(reg2), ylab=\"Residuals\", xlab=\"State\") abline(0, 0)"
},
{
"code": null,
"e": 3925,
"s": 3582,
"text": "R-squared improves significantly, but now the plotted line looks awfully goofy — we consistently undershoot, and the coefficient estimate for Exercise is near zero (and has a non-significant p-value). This is an example of the effect of heteroskedasticity — the groups (i.e. states) with larger variance override groups with smaller variance."
},
{
"code": null,
"e": 4109,
"s": 3925,
"text": "We’re getting somewhere. What if we did a separate linear regression for each state? That way we’re not going to have problems with group interactions skewing our coefficients, right?"
},
{
"code": null,
"e": 4238,
"s": 4109,
"text": "library(ggplot2)ggplot(data, aes(x = Exercise, y = Mood, color = State)) + geom_point() + geom_smooth(method='lm',formula=y~x)"
},
{
"code": null,
"e": 4576,
"s": 4238,
"text": "Well, we have an opposite problem now — notice that in state C exercise is now decreasing mood. and the slope coefficient in other states is much lower than the 0.42951 that we saw in the Mood ~ Exercise regression. So now there is information in the high-level model that we’re neglecting because of our focus on the state-level models."
},
{
"code": null,
"e": 4596,
"s": 4576,
"text": "Mixed-Effect Models"
},
{
"code": null,
"e": 4868,
"s": 4596,
"text": "The final example above leads right into a mixed-effect model. In this model, we can allow the state-level regressions to incorporate some of the information from the overall regression, but also retain some state-level components. We can use the lme4 library to do this."
},
{
"code": null,
"e": 5115,
"s": 4868,
"text": "The notation is similar to an lm regression with a key difference: the (1 + Exercise | State) notation allows the model to use a term with different slopes and intercepts for Mood ~ Exercise for each State value. See the coefficient values below."
},
{
"code": null,
"e": 5233,
"s": 5115,
"text": "library(lme4)reg3 <- lmer(Mood ~ Exercise + (1 + Exercise | State), data = data, REML = FALSE)summary(reg3)coef(reg3)"
},
{
"code": null,
"e": 5259,
"s": 5233,
"text": "We have run 3 models now:"
},
{
"code": null,
"e": 5338,
"s": 5259,
"text": "Mood ~ ExerciseMood ~ Exercise + StateMood ~ Exercise + (1 + Exercise | State)"
},
{
"code": null,
"e": 5354,
"s": 5338,
"text": "Mood ~ Exercise"
},
{
"code": null,
"e": 5378,
"s": 5354,
"text": "Mood ~ Exercise + State"
},
{
"code": null,
"e": 5419,
"s": 5378,
"text": "Mood ~ Exercise + (1 + Exercise | State)"
},
{
"code": null,
"e": 5460,
"s": 5419,
"text": "We can calculate the RMSE of each model."
},
{
"code": null,
"e": 5695,
"s": 5460,
"text": "reg1_predict <- predict(reg1, data[1:2])reg2_predict <- predict(reg2, data[1:2])reg3_predict <- predict(reg3, data[1:2])sqrt(sum((data[3] - reg1_predict)**2))sqrt(sum((data[3] - reg2_predict)**2))sqrt(sum((data[3] - reg3_predict)**2))"
},
{
"code": null,
"e": 6196,
"s": 5695,
"text": "RMSE improved significantly moving from models 2 to 3 — this suggests that the majority of the difference between states and mood is due to average mood in each state. Moving from model 2 to 3 captured this state-level intercept information, but also calculated a slope coefficient for Mood ~ Exercise for each state which incorporated information from the total dataset and from the state-level information (recall that using only state-level slope information produced a negative slope in State C)."
},
{
"code": null,
"e": 6484,
"s": 6196,
"text": "A few final notes on Mixed-Effect Models. There are multiple approaches and ongoing research into how to determine p-values for mixed-effect models. One can use an anova likelihood test to determine if an added variable is significant with respect to a model without that added variable."
},
{
"code": null,
"e": 6495,
"s": 6484,
"text": "Conclusion"
},
{
"code": null,
"e": 6602,
"s": 6495,
"text": "Mixed-Effect models provide a framework for smoothing global and group level characteristics in your data."
},
{
"code": null,
"e": 6897,
"s": 6602,
"text": "I learned about these models primarily from Richard McElreath and his wonderful text Statistical Rethinking. I’d recommend it highly to any reader: it is a great help in rethinking many of the statistical assumptions that were made for me in entry-level classes that I never knew to reconsider."
}
] |
Object detection via color-based image segmentation using python | by Salma Ghoneim | Towards Data Science | If you already have jupyter notebook or an IDE with which you can run python & OpenCV installed, just skip to Execution.
Our hero today is Anaconda. a free open-source distribution that helps with installing different packages & sorts out their messes into isolated environments.
What Wikipedia’s telling us about Anaconda
Anaconda is a free and open-source distribution of the Python and R programming languages for scientific computing (data science, machine learning applications, large-scale data processing, predictive analytics, etc.), that aims to simplify package management and deployment. Package versions are managed by the package management system conda. The Anaconda distribution is used by over 12 million users and includes more than 1400 popular data-science packages suitable for Windows, Linux, and MacOS.
Here are detailed tutorials on how to download Anaconda.anaconda for Windows & anaconda for Linux.
Open the bash (cmd) and type this
$ conda create -n myEnv python=3
Type y (for yes) when prompted to download the packages.
$ source activate myEnv$ conda install anaconda$ conda activate myEnv$ conda install opencv$ jupyter notebook
This will open jupyter notebook in the browser for you.
Contours can be explained simply as a curve joining all the continuous points (along with the boundary), having the same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition.
Applying thresholding on a grayscale image makes it a binary image. You set a threshold value, in which all values below this threshold are turned to black and all values above go white.
Now you have all you need to start.We’re gonna start with a simple example just to show you how color-based segmentation works.
Bear with me till we get to the good stuff.
If you want to try this with me, you can get this image for free from here.In the following code, I’m gonna segment this image into 17 gray levels. Then measure each level’s area using contouring.
import cv2import numpy as npdef viewImage(image): cv2.namedWindow('Display', cv2.WINDOW_NORMAL) cv2.imshow('Display', image) cv2.waitKey(0) cv2.destroyAllWindows()def grayscale_17_levels (image): high = 255 while(1): low = high - 15 col_to_be_changed_low = np.array([low]) col_to_be_changed_high = np.array([high]) curr_mask = cv2.inRange(gray, col_to_be_changed_low,col_to_be_changed_high) gray[curr_mask > 0] = (high) high -= 15 if(low == 0 ): breakimage = cv2.imread('./path/to/image')viewImage(image)gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)grayscale_17_levels(gray)viewImage(gray)
def get_area_of_each_gray_level(im):## convert image to gray scale (must br done before contouring) image = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) output = [] high = 255 first = True while(1):low = high - 15 if(first == False):# making values that are of a greater gray level black ## so it won't get detected to_be_black_again_low = np.array([high]) to_be_black_again_high = np.array([255]) curr_mask = cv2.inRange(image, to_be_black_again_low, to_be_black_again_high) image[curr_mask > 0] = (0) # making values of this gray level white so we can calculate # it's area ret, threshold = cv2.threshold(image, low, 255, 0) contours, hirerchy = cv2.findContours(threshold, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)if(len(contours) > 0):output.append([cv2.contourArea(contours[0])]) cv2.drawContours(im, contours, -1, (0,0,255), 3)high -= 15 first = False if(low == 0 ):breakreturn output
In this function, I simply convert the range (of intensities) of gray that I want to contour (highlight) in this iteration by unifying all of those which lie within this range to one intensity. I turn every other intensity but this range to black (including greater & smaller intensities).The second step I threshold the image so that only the color that I want to contour right now appears white and all others convert to black. This step doesn’t change much here but it must be done because contouring works best with black and white (thresholds) images.Before applying this step (thresholding) the image below would be the same except the white ring would’ve been gray (the gray intensity of the 10th gray level (255–15*10 ) )
image = cv2.imread('./path/to/image')print(get_area_of_each_gray_level(image))viewImage(image)
This way we obtain the area of each gray level.
Before we move on, I want to stress the importance of this topic.I’m a Computer Engineering student and I’m working on a project called Machine learning for intelligent tumor detection and identification.Color-based image segmentation is used in this project to help the computer learn how to detect the tumor. When dealing with an MRI scan, the program has to detect the cancer level of said MRI scan. It does that by segmenting the scan into different grayscale levels in which the darkest is the most filled with cancerous cells and the closest to white is the healthier parts. Then it calculates the degree of membership of the tumor to each grayscale level. With this information, the program is able to identify the tumor and its stage.This project is based on soft computing, fuzzy logic & machine learning, you can learn more about it on Fuzzy logic and how it is curing cancer.
You can get this image for free on Pexels from here. You just need to crop it.
In this image, we want to contour the leaf only. Since the texture of this image is very irregular and uneven, meaning that although there aren’t many colors. The intensity of the green color in this image changes, also, its brightness. So, the best thing to do here is to unify all these different shades of green into one shade. This way when we apply contouring, it will deal with the leaf as one whole object.
Note: This is the result if you apply contouring on the image without any pre-processing. I just wanted you to see how the uneven nature of the leaf makes OpenCV not understand that this is just one object.
import cv2import numpy as npdef viewImage(image): cv2.namedWindow('Display', cv2.WINDOW_NORMAL) cv2.imshow('Display', image) cv2.waitKey(0) cv2.destroyAllWindows()
First, you have to know the HSV representation of your color, you can know it by converting its RGB to HSV just like the following.
## getting green HSV color representationgreen = np.uint8([[[0, 255, 0 ]]])green_hsv = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)print( green_hsv)
Converting the image to HSV: It’s easier with HSV to get the complete range of one color. HSV, H stands for Hue, S for Saturation, V for value. We already know that the green color is [60, 255, 255]. All the greens in the world lie within [45, 100, 50] to [75, 255, 255] that is [60–15, 100, 50] to [60+15, 255, 255]. 15 is just an approximation value.We take this range and convert it to [75, 255, 200] or any other light color (3rd value must be relatively large) cause that’s the brightness of the color, that’s the value that will make this part be white when we threshold the image.
image = cv2.imread('./path/to/image.jpg')hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)viewImage(hsv_img) ## 1green_low = np.array([45 , 100, 50] )green_high = np.array([75, 255, 255])curr_mask = cv2.inRange(hsv_img, green_low, green_high)hsv_img[curr_mask > 0] = ([75,255,200])viewImage(hsv_img) ## 2## converting the HSV image to Gray inorder to be able to apply ## contouringRGB_again = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB)gray = cv2.cvtColor(RGB_again, cv2.COLOR_RGB2GRAY)viewImage(gray) ## 3ret, threshold = cv2.threshold(gray, 90, 255, 0)viewImage(threshold) ## 4contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)cv2.drawContours(image, contours, -1, (0, 0, 255), 3)viewImage(image) ## 5
Since there seem to be irregularities in the background as well, We can get the largest contour using this method, The largest contour is, of course, the leaf.We can get the index of the leaf contour in the contours array, from that we get the area and center of the leaf. Contours have many other features that you can make use of such as the contour perimeter, convex hull, bounding rectangle, and many others. You can learn more about it from here.
def findGreatesContour(contours): largest_area = 0 largest_contour_index = -1 i = 0 total_contours = len(contours) while (i < total_contours ): area = cv2.contourArea(contours[i]) if(area > largest_area): largest_area = area largest_contour_index = i i+=1 return largest_area, largest_contour_index# to get the center of the contourcnt = contours[13]M = cv2.moments(cnt)cX = int(M["m10"] / M["m00"])cY = int(M["m01"] / M["m00"])largest_area, largest_contour_index = findGreatesContour(contours)print(largest_area)print(largest_contour_index)print(len(contours))print(cX)print(cY) | [
{
"code": null,
"e": 293,
"s": 172,
"text": "If you already have jupyter notebook or an IDE with which you can run python & OpenCV installed, just skip to Execution."
},
{
"code": null,
"e": 452,
"s": 293,
"text": "Our hero today is Anaconda. a free open-source distribution that helps with installing different packages & sorts out their messes into isolated environments."
},
{
"code": null,
"e": 495,
"s": 452,
"text": "What Wikipedia’s telling us about Anaconda"
},
{
"code": null,
"e": 997,
"s": 495,
"text": "Anaconda is a free and open-source distribution of the Python and R programming languages for scientific computing (data science, machine learning applications, large-scale data processing, predictive analytics, etc.), that aims to simplify package management and deployment. Package versions are managed by the package management system conda. The Anaconda distribution is used by over 12 million users and includes more than 1400 popular data-science packages suitable for Windows, Linux, and MacOS."
},
{
"code": null,
"e": 1096,
"s": 997,
"text": "Here are detailed tutorials on how to download Anaconda.anaconda for Windows & anaconda for Linux."
},
{
"code": null,
"e": 1130,
"s": 1096,
"text": "Open the bash (cmd) and type this"
},
{
"code": null,
"e": 1163,
"s": 1130,
"text": "$ conda create -n myEnv python=3"
},
{
"code": null,
"e": 1220,
"s": 1163,
"text": "Type y (for yes) when prompted to download the packages."
},
{
"code": null,
"e": 1330,
"s": 1220,
"text": "$ source activate myEnv$ conda install anaconda$ conda activate myEnv$ conda install opencv$ jupyter notebook"
},
{
"code": null,
"e": 1386,
"s": 1330,
"text": "This will open jupyter notebook in the browser for you."
},
{
"code": null,
"e": 1615,
"s": 1386,
"text": "Contours can be explained simply as a curve joining all the continuous points (along with the boundary), having the same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition."
},
{
"code": null,
"e": 1802,
"s": 1615,
"text": "Applying thresholding on a grayscale image makes it a binary image. You set a threshold value, in which all values below this threshold are turned to black and all values above go white."
},
{
"code": null,
"e": 1930,
"s": 1802,
"text": "Now you have all you need to start.We’re gonna start with a simple example just to show you how color-based segmentation works."
},
{
"code": null,
"e": 1974,
"s": 1930,
"text": "Bear with me till we get to the good stuff."
},
{
"code": null,
"e": 2171,
"s": 1974,
"text": "If you want to try this with me, you can get this image for free from here.In the following code, I’m gonna segment this image into 17 gray levels. Then measure each level’s area using contouring."
},
{
"code": null,
"e": 2842,
"s": 2171,
"text": "import cv2import numpy as npdef viewImage(image): cv2.namedWindow('Display', cv2.WINDOW_NORMAL) cv2.imshow('Display', image) cv2.waitKey(0) cv2.destroyAllWindows()def grayscale_17_levels (image): high = 255 while(1): low = high - 15 col_to_be_changed_low = np.array([low]) col_to_be_changed_high = np.array([high]) curr_mask = cv2.inRange(gray, col_to_be_changed_low,col_to_be_changed_high) gray[curr_mask > 0] = (high) high -= 15 if(low == 0 ): breakimage = cv2.imread('./path/to/image')viewImage(image)gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)grayscale_17_levels(gray)viewImage(gray)"
},
{
"code": null,
"e": 3886,
"s": 2842,
"text": "def get_area_of_each_gray_level(im):## convert image to gray scale (must br done before contouring) image = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) output = [] high = 255 first = True while(1):low = high - 15 if(first == False):# making values that are of a greater gray level black ## so it won't get detected to_be_black_again_low = np.array([high]) to_be_black_again_high = np.array([255]) curr_mask = cv2.inRange(image, to_be_black_again_low, to_be_black_again_high) image[curr_mask > 0] = (0) # making values of this gray level white so we can calculate # it's area ret, threshold = cv2.threshold(image, low, 255, 0) contours, hirerchy = cv2.findContours(threshold, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)if(len(contours) > 0):output.append([cv2.contourArea(contours[0])]) cv2.drawContours(im, contours, -1, (0,0,255), 3)high -= 15 first = False if(low == 0 ):breakreturn output"
},
{
"code": null,
"e": 4616,
"s": 3886,
"text": "In this function, I simply convert the range (of intensities) of gray that I want to contour (highlight) in this iteration by unifying all of those which lie within this range to one intensity. I turn every other intensity but this range to black (including greater & smaller intensities).The second step I threshold the image so that only the color that I want to contour right now appears white and all others convert to black. This step doesn’t change much here but it must be done because contouring works best with black and white (thresholds) images.Before applying this step (thresholding) the image below would be the same except the white ring would’ve been gray (the gray intensity of the 10th gray level (255–15*10 ) )"
},
{
"code": null,
"e": 4711,
"s": 4616,
"text": "image = cv2.imread('./path/to/image')print(get_area_of_each_gray_level(image))viewImage(image)"
},
{
"code": null,
"e": 4759,
"s": 4711,
"text": "This way we obtain the area of each gray level."
},
{
"code": null,
"e": 5646,
"s": 4759,
"text": "Before we move on, I want to stress the importance of this topic.I’m a Computer Engineering student and I’m working on a project called Machine learning for intelligent tumor detection and identification.Color-based image segmentation is used in this project to help the computer learn how to detect the tumor. When dealing with an MRI scan, the program has to detect the cancer level of said MRI scan. It does that by segmenting the scan into different grayscale levels in which the darkest is the most filled with cancerous cells and the closest to white is the healthier parts. Then it calculates the degree of membership of the tumor to each grayscale level. With this information, the program is able to identify the tumor and its stage.This project is based on soft computing, fuzzy logic & machine learning, you can learn more about it on Fuzzy logic and how it is curing cancer."
},
{
"code": null,
"e": 5725,
"s": 5646,
"text": "You can get this image for free on Pexels from here. You just need to crop it."
},
{
"code": null,
"e": 6139,
"s": 5725,
"text": "In this image, we want to contour the leaf only. Since the texture of this image is very irregular and uneven, meaning that although there aren’t many colors. The intensity of the green color in this image changes, also, its brightness. So, the best thing to do here is to unify all these different shades of green into one shade. This way when we apply contouring, it will deal with the leaf as one whole object."
},
{
"code": null,
"e": 6346,
"s": 6139,
"text": "Note: This is the result if you apply contouring on the image without any pre-processing. I just wanted you to see how the uneven nature of the leaf makes OpenCV not understand that this is just one object."
},
{
"code": null,
"e": 6522,
"s": 6346,
"text": "import cv2import numpy as npdef viewImage(image): cv2.namedWindow('Display', cv2.WINDOW_NORMAL) cv2.imshow('Display', image) cv2.waitKey(0) cv2.destroyAllWindows()"
},
{
"code": null,
"e": 6654,
"s": 6522,
"text": "First, you have to know the HSV representation of your color, you can know it by converting its RGB to HSV just like the following."
},
{
"code": null,
"e": 6796,
"s": 6654,
"text": "## getting green HSV color representationgreen = np.uint8([[[0, 255, 0 ]]])green_hsv = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)print( green_hsv)"
},
{
"code": null,
"e": 7384,
"s": 6796,
"text": "Converting the image to HSV: It’s easier with HSV to get the complete range of one color. HSV, H stands for Hue, S for Saturation, V for value. We already know that the green color is [60, 255, 255]. All the greens in the world lie within [45, 100, 50] to [75, 255, 255] that is [60–15, 100, 50] to [60+15, 255, 255]. 15 is just an approximation value.We take this range and convert it to [75, 255, 200] or any other light color (3rd value must be relatively large) cause that’s the brightness of the color, that’s the value that will make this part be white when we threshold the image."
},
{
"code": null,
"e": 8122,
"s": 7384,
"text": "image = cv2.imread('./path/to/image.jpg')hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)viewImage(hsv_img) ## 1green_low = np.array([45 , 100, 50] )green_high = np.array([75, 255, 255])curr_mask = cv2.inRange(hsv_img, green_low, green_high)hsv_img[curr_mask > 0] = ([75,255,200])viewImage(hsv_img) ## 2## converting the HSV image to Gray inorder to be able to apply ## contouringRGB_again = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB)gray = cv2.cvtColor(RGB_again, cv2.COLOR_RGB2GRAY)viewImage(gray) ## 3ret, threshold = cv2.threshold(gray, 90, 255, 0)viewImage(threshold) ## 4contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)cv2.drawContours(image, contours, -1, (0, 0, 255), 3)viewImage(image) ## 5"
},
{
"code": null,
"e": 8574,
"s": 8122,
"text": "Since there seem to be irregularities in the background as well, We can get the largest contour using this method, The largest contour is, of course, the leaf.We can get the index of the leaf contour in the contours array, from that we get the area and center of the leaf. Contours have many other features that you can make use of such as the contour perimeter, convex hull, bounding rectangle, and many others. You can learn more about it from here."
}
] |
HTML DOM Button type Property | The HTML DOM Button type property is associated with the HTML <button> element. The button element by default has type=”submit” i.e clicking on any button on the form will submit the form. The button type property sets or returns the type of button.
Following is the syntax for −
Setting the button type property −
buttonObject.type = "submit|button|reset"
Here, the submit|button|reset are button type values. Submit is set by default.
Submit − Makes the button a submit button.
Button − Makes a normal clickable button.
Reset − Makes a reset button that resets the form data.
Let us see an example of the HTML DOM button type property −
<!DOCTYPE html>
<html>
<body>
<form id="Form1" action="/sample.php">
<label>First Name: <input type="text" name="fname"><br><br></label>
<label>Surname: <input type="text" name="lname"><br><br></label>
<button id="Button1" type="submit">Submit</button>
</form>
<p>Click the below button below to change the type of the above button from "submit" to "reset".</p>
<button onclick="changeType()">CHANGE</button>
<p id="Sample"></p>
<script>
function changeType() {
document.getElementById("Button1").type = "reset";
document.getElementById("Sample").innerHTML = "The Submit button is now a reset
button";
}
</script>
</body>
</html>
This will produce the following output −
On filling the details and clicking CHANGE −
Now clicking on Submit (which is now reset) −
In the above example −
We have first created two text fields and a button with type “submit” that will submit our data −
<label>First Name: <input type="text" name="fname"><br><br></label>
<label>Surname: <input type="text" name="lname"><br><br></label>
<button id="Button1" type="submit">Submit</button>
We have then created the CHANGE button that will execute changeType() method on click −
<button onclick="changeType()">CHANGE</button>
The changeType() method gets the button element by using its id and sets its type to reset. Then the message regarding the change is reflected in the paragraph with “Id” sample. Now when you click on the submit button it will reset i.e clear the form data instead of submitting it −
function changeType() {
document.getElementById("Button1").type = "reset";
document.getElementById("Sample").innerHTML = "The Submit button is now a reset button";
} | [
{
"code": null,
"e": 1312,
"s": 1062,
"text": "The HTML DOM Button type property is associated with the HTML <button> element. The button element by default has type=”submit” i.e clicking on any button on the form will submit the form. The button type property sets or returns the type of button."
},
{
"code": null,
"e": 1342,
"s": 1312,
"text": "Following is the syntax for −"
},
{
"code": null,
"e": 1377,
"s": 1342,
"text": "Setting the button type property −"
},
{
"code": null,
"e": 1419,
"s": 1377,
"text": "buttonObject.type = \"submit|button|reset\""
},
{
"code": null,
"e": 1499,
"s": 1419,
"text": "Here, the submit|button|reset are button type values. Submit is set by default."
},
{
"code": null,
"e": 1542,
"s": 1499,
"text": "Submit − Makes the button a submit button."
},
{
"code": null,
"e": 1584,
"s": 1542,
"text": "Button − Makes a normal clickable button."
},
{
"code": null,
"e": 1640,
"s": 1584,
"text": "Reset − Makes a reset button that resets the form data."
},
{
"code": null,
"e": 1701,
"s": 1640,
"text": "Let us see an example of the HTML DOM button type property −"
},
{
"code": null,
"e": 2355,
"s": 1701,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<form id=\"Form1\" action=\"/sample.php\">\n<label>First Name: <input type=\"text\" name=\"fname\"><br><br></label>\n<label>Surname: <input type=\"text\" name=\"lname\"><br><br></label>\n<button id=\"Button1\" type=\"submit\">Submit</button>\n</form>\n<p>Click the below button below to change the type of the above button from \"submit\" to \"reset\".</p>\n<button onclick=\"changeType()\">CHANGE</button>\n<p id=\"Sample\"></p>\n<script>\n function changeType() {\n document.getElementById(\"Button1\").type = \"reset\";\n document.getElementById(\"Sample\").innerHTML = \"The Submit button is now a reset\n button\";\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2396,
"s": 2355,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2441,
"s": 2396,
"text": "On filling the details and clicking CHANGE −"
},
{
"code": null,
"e": 2487,
"s": 2441,
"text": "Now clicking on Submit (which is now reset) −"
},
{
"code": null,
"e": 2510,
"s": 2487,
"text": "In the above example −"
},
{
"code": null,
"e": 2608,
"s": 2510,
"text": "We have first created two text fields and a button with type “submit” that will submit our data −"
},
{
"code": null,
"e": 2792,
"s": 2608,
"text": "<label>First Name: <input type=\"text\" name=\"fname\"><br><br></label>\n<label>Surname: <input type=\"text\" name=\"lname\"><br><br></label>\n<button id=\"Button1\" type=\"submit\">Submit</button>"
},
{
"code": null,
"e": 2880,
"s": 2792,
"text": "We have then created the CHANGE button that will execute changeType() method on click −"
},
{
"code": null,
"e": 2927,
"s": 2880,
"text": "<button onclick=\"changeType()\">CHANGE</button>"
},
{
"code": null,
"e": 3210,
"s": 2927,
"text": "The changeType() method gets the button element by using its id and sets its type to reset. Then the message regarding the change is reflected in the paragraph with “Id” sample. Now when you click on the submit button it will reset i.e clear the form data instead of submitting it −"
},
{
"code": null,
"e": 3382,
"s": 3210,
"text": "function changeType() {\n document.getElementById(\"Button1\").type = \"reset\";\n document.getElementById(\"Sample\").innerHTML = \"The Submit button is now a reset button\";\n}"
}
] |
Spring MVC - Generate RSS Feed Example | The following example shows how to generate RSS Feed using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and then consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
package com.tutorialspoint;
import java.util.Date;
public class RSSMessage {
String title;
String url;
String summary;
Date createdDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Content;
import com.rometools.rome.feed.rss.Item;
public class RSSFeedViewer extends AbstractRssFeedView {
@Override
protected void buildFeedMetadata(Map<String, Object> model, Channel feed,
HttpServletRequest request) {
feed.setTitle("TutorialsPoint Dot Com");
feed.setDescription("Java Tutorials and Examples");
feed.setLink("http://www.tutorialspoint.com");
super.buildFeedMetadata(model, feed, request);
}
@Override
protected List<Item> buildFeedItems(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<RSSMessage> listContent = (List<RSSMessage>) model.get("feedContent");
List<Item> items = new ArrayList<Item>(listContent.size());
for(RSSMessage tempContent : listContent ){
Item item = new Item();
Content content = new Content();
content.setValue(tempContent.getSummary());
item.setContent(content);
item.setTitle(tempContent.getTitle());
item.setLink(tempContent.getUrl());
item.setPubDate(tempContent.getCreatedDate());
items.add(item);
}
return items;
}
}
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class RSSController {
@RequestMapping(value="/rssfeed", method = RequestMethod.GET)
public ModelAndView getFeedInRss() {
List<RSSMessage> items = new ArrayList<RSSMessage>();
RSSMessage content = new RSSMessage();
content.setTitle("Spring Tutorial");
content.setUrl("http://www.tutorialspoint/spring");
content.setSummary("Spring tutorial summary...");
content.setCreatedDate(new Date());
items.add(content);
RSSMessage content2 = new RSSMessage();
content2.setTitle("Spring MVC");
content2.setUrl("http://www.tutorialspoint/springmvc");
content2.setSummary("Spring MVC tutorial summary...");
content2.setCreatedDate(new Date());
items.add(content2);
ModelAndView mav = new ModelAndView();
mav.setViewName("rssViewer");
mav.addObject("feedContent", items);
return mav;
}
}
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean id = "rssViewer" class = "com.tutorialspoint.RSSFeedViewer" />
</beans>
Here, we have created a RSS feed POJO RSSMessage and a RSS Message Viewer, which extends the AbstractRssFeedView and overrides its method. In RSSController, we have generated a sample RSS Feed.
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat's webapps folder.
Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL − http://localhost:8080/TestWeb/rssfeed and we will see the following screen.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3056,
"s": 2791,
"text": "The following example shows how to generate RSS Feed using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and then consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework."
},
{
"code": null,
"e": 3746,
"s": 3056,
"text": "package com.tutorialspoint;\n\nimport java.util.Date;\n\npublic class RSSMessage {\n String title;\n String url;\n String summary;\n Date createdDate;\n public String getTitle() {\n return title;\n }\n public void setTitle(String title) {\n this.title = title;\n }\n public String getUrl() {\n return url;\n }\n public void setUrl(String url) {\n this.url = url;\n }\n public String getSummary() {\n return summary;\n }\n public void setSummary(String summary) {\n this.summary = summary;\n }\n public Date getCreatedDate() {\n return createdDate;\n }\n public void setCreatedDate(Date createdDate) {\n this.createdDate = createdDate;\n }\t\n}"
},
{
"code": null,
"e": 5292,
"s": 3746,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.web.servlet.view.feed.AbstractRssFeedView;\n\nimport com.rometools.rome.feed.rss.Channel;\nimport com.rometools.rome.feed.rss.Content;\nimport com.rometools.rome.feed.rss.Item;\n\npublic class RSSFeedViewer extends AbstractRssFeedView {\n\n @Override\n protected void buildFeedMetadata(Map<String, Object> model, Channel feed,\n HttpServletRequest request) {\n\n feed.setTitle(\"TutorialsPoint Dot Com\");\n feed.setDescription(\"Java Tutorials and Examples\");\n feed.setLink(\"http://www.tutorialspoint.com\");\n\n super.buildFeedMetadata(model, feed, request);\n }\n\n @Override\n protected List<Item> buildFeedItems(Map<String, Object> model,\n HttpServletRequest request, HttpServletResponse response) throws Exception {\n \n List<RSSMessage> listContent = (List<RSSMessage>) model.get(\"feedContent\");\n List<Item> items = new ArrayList<Item>(listContent.size());\n\n for(RSSMessage tempContent : listContent ){\n\n Item item = new Item();\n\n Content content = new Content();\n content.setValue(tempContent.getSummary());\n item.setContent(content);\n\n item.setTitle(tempContent.getTitle());\n item.setLink(tempContent.getUrl());\n item.setPubDate(tempContent.getCreatedDate());\n\n items.add(item);\n }\n\n return items;\t\t\n }\n}"
},
{
"code": null,
"e": 6535,
"s": 5292,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.servlet.ModelAndView;\n\n@Controller\npublic class RSSController {\n @RequestMapping(value=\"/rssfeed\", method = RequestMethod.GET)\n public ModelAndView getFeedInRss() {\n\n List<RSSMessage> items = new ArrayList<RSSMessage>();\n\n RSSMessage content = new RSSMessage();\n content.setTitle(\"Spring Tutorial\");\n content.setUrl(\"http://www.tutorialspoint/spring\");\n content.setSummary(\"Spring tutorial summary...\");\n content.setCreatedDate(new Date());\n items.add(content);\n\n RSSMessage content2 = new RSSMessage();\n content2.setTitle(\"Spring MVC\");\n content2.setUrl(\"http://www.tutorialspoint/springmvc\");\n content2.setSummary(\"Spring MVC tutorial summary...\");\n content2.setCreatedDate(new Date());\n items.add(content2);\n\n ModelAndView mav = new ModelAndView();\n mav.setViewName(\"rssViewer\");\n mav.addObject(\"feedContent\", items);\n\n return mav;\n }\n}"
},
{
"code": null,
"e": 7224,
"s": 6535,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n <context:component-scan base-package = \"com.tutorialspoint\" />\n\n <bean class = \"org.springframework.web.servlet.view.BeanNameViewResolver\" />\n\n <bean id = \"rssViewer\" class = \"com.tutorialspoint.RSSFeedViewer\" />\n</beans>"
},
{
"code": null,
"e": 7418,
"s": 7224,
"text": "Here, we have created a RSS feed POJO RSSMessage and a RSS Message Viewer, which extends the AbstractRssFeedView and overrides its method. In RSSController, we have generated a sample RSS Feed."
},
{
"code": null,
"e": 7627,
"s": 7418,
"text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat's webapps folder."
},
{
"code": null,
"e": 7847,
"s": 7627,
"text": "Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL − http://localhost:8080/TestWeb/rssfeed and we will see the following screen."
},
{
"code": null,
"e": 7854,
"s": 7847,
"text": " Print"
},
{
"code": null,
"e": 7865,
"s": 7854,
"text": " Add Notes"
}
] |
Armstrong number within a range in JavaScript | Armstrong Numbers: A positive integer is called an Armstrong number (of order n) if −
abcd... = a^n + b^n + c^n + d^n + ...
We are required to write a JavaScript function that takes in an array of exactly two numbers
specifying a range.
The function should return an array of all the Armstrong numbers that falls in that range
(including the start and end numbers if they are Armstrong).
We will first separately write a function to detect Armstrong numbers and then iterate through
the range to fill the array with desired numbers.
Following is the code −
const range = [11, 1111];
const isArmstrong = (num) => {
const numberOfDigits = ('' + num).length;
let sum = 0;
let temp = num;
while (temp > 0) {
let remainder = temp % 10;
sum += remainder ** numberOfDigits;
temp = parseInt(temp / 10);
}
return sum === num;
};
const findAllArmstrong = ([start, end]) => {
const res = [];
for(let i = start; i <= end; i++){
if(isArmstrong(i)){
res.push(i);
};
};
return res;
};
console.log(findAllArmstrong(range));
Following is the console output −
[ 153, 370, 371, 407 ] | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "Armstrong Numbers: A positive integer is called an Armstrong number (of order n) if −"
},
{
"code": null,
"e": 1186,
"s": 1148,
"text": "abcd... = a^n + b^n + c^n + d^n + ..."
},
{
"code": null,
"e": 1299,
"s": 1186,
"text": "We are required to write a JavaScript function that takes in an array of exactly two numbers\nspecifying a range."
},
{
"code": null,
"e": 1450,
"s": 1299,
"text": "The function should return an array of all the Armstrong numbers that falls in that range\n(including the start and end numbers if they are Armstrong)."
},
{
"code": null,
"e": 1595,
"s": 1450,
"text": "We will first separately write a function to detect Armstrong numbers and then iterate through\nthe range to fill the array with desired numbers."
},
{
"code": null,
"e": 1619,
"s": 1595,
"text": "Following is the code −"
},
{
"code": null,
"e": 2139,
"s": 1619,
"text": "const range = [11, 1111];\nconst isArmstrong = (num) => {\n const numberOfDigits = ('' + num).length;\n let sum = 0;\n let temp = num;\n while (temp > 0) {\n let remainder = temp % 10;\n sum += remainder ** numberOfDigits;\n temp = parseInt(temp / 10);\n }\n return sum === num;\n};\nconst findAllArmstrong = ([start, end]) => {\n const res = [];\n for(let i = start; i <= end; i++){\n if(isArmstrong(i)){\n res.push(i);\n };\n };\n return res;\n};\nconsole.log(findAllArmstrong(range));"
},
{
"code": null,
"e": 2173,
"s": 2139,
"text": "Following is the console output −"
},
{
"code": null,
"e": 2196,
"s": 2173,
"text": "[ 153, 370, 371, 407 ]"
}
] |
Python Tutorial: A Name Lookup Table for Fuzzy Name Data Sets | by Felix Kuestahler | Towards Data Science | This is the sixth article of our journey into the Python data exploration world. Click on the link above the Title to get a list of all articles.
Let’s recap what we have achieved in our last lesson. We established a person’s name “fuzzy” name matching algorithm by using a normalization step as well as the power of the double metaphone algorithm.
The algorithm may handle typos, special characters and other differences in the name attribute BUT it fails if any of the name components are missing on the twitter account name side.
The problem is that the Twitter account name is concatenated by the user and therefore not deterministic (well we assume he isn’t using a pseudonym and there is a chance for a match). As we have seen in the last tutorial, we tried to fix certain anomalies but the worked out solution seems not robust enough. So we have to invest additional time to build up a more robust solution, which tackles the “Missing Name Components” problem by using combinatorics.
As part of my own ramp up into the Python data science world, I started recently to play around with Jupyter Notebook for Python.
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.
It’s just awesome and via the Ancaconda distribution installed in minutes (well you need some spare disk space on your machine).
I integrated it into my tutorial work-out process and from now on will describe the build out of algorithms and the coding in more detail in dedicated Jupyter notebooks.
You can find the Jupyter notebook for this tutorial in my Github project. Using the Jupyter Notebook (side by side with this tutorial), allows you to play around and do real-time modifications of code sequences in the notebook. Amazingly Github renders a Jupyter Notebook file in its origin and easily readable Web view format. In case you want to look at the read-only format!
What we want to achieve is that our algorithm is capable of managing missing name components. In the below example we could achieve a match by omitting the 2nd name component on both sides.
Obviously, we want a generic algorithm which can handle any complexity in the twitter account name, i.e. a match should be possible as well in a naming construct like:
“Dr. med. Peter A. Escher (Zurich)” or
“Dr. med. Peteer A. Escher (Zurich)”, where the user had a typo.
The first problem we tackle with combinatorics, the second one, we solved already by applying the well known double metaphone algorithm.
To derive any kind of Name Component constellations in case of missing elements, we have to understand the basic concepts in combinatorics.
Let’s answer this question first. Too long away from school? Check out this helpful six minutes video (from betterExplained.com) which freshes up the various concepts.
Python provides in its standard library itertools already the function permutations and combinations which we want to inspect a little bit further.
Let’s apply it on our name sample to understand its mechanism. First the combinations function
As well as the permutations function:
As you can see within the permutation the order of a name component plays a role. There is a tuple for ('peter','alfred') as well as one for ('alfred','peter'). Within the combination the order of a name component is irrelevant.
For us, the order plays not a role, 'peter escher' is treated as'escher peter' We anyway sort the name components before we apply the double methaphone algorithm. Therefore we use the combination function.
Always think about “pin code” as a crib for “permutations”. Any pin code lock mechanism is based on the number of permutations of a given set of “digits” out of 10 elements: “1234” doesn’t unlock the screen which is locked with “4321”.
We now build up a lookup directory class which allows us to store name component combinations and compare them to a person name which we got from the Twitter API.
The method add_person_to_lookup_table calculates all combinations of the provided name tuple, generates for each combination the associated double metaphone key and stores the key together with the unique person id in the lookup directory.
The sequence diagram of the method is shown below, let’s look at the various helper methods which are required.
As a first step, we generate all combinations of name tuple. The following method calculates all combinations of a name tuple. For example for a 3 element tuple, the array built up consists of
the 3 element tuple itself
all tuples of the combination with 2 out of 3 elements
all tuples of the combination with 1 out of 3 elements
For example, the below 3 name tuple are resulting in the following list of combinations.
In this method, we build up the directory by adding each tuple to our lookup directory.
Our lookup directory is made of a tuple of two dictionaries, which are used store the key, value pairs. Our keys are the double metaphone tuple created from a name, and the value is the unique person identifier.
__lookup_dict = ({}, {})
The method is shown below
On code line 3 we create a normalized name string out of a name component tuple. The method looks as follows
The result is a lower case string of the sorted concatenated tuple name elements:
The string is used to generate the double metaphone tuple, which are our keys for the dictionaries.
On code line 5 and 10, we check if we have already an entry with the same key in the dictionary.
If not, we add the new key, value pair.
If there is already an entry, we check first if we have already the person_id stored. If not we add the person_id to the value array.
Finally, we have the method ready, which allows us to add name tuples to the lookup directory.
As an example, we add the following three persons to our lookup table.
As we can see in the output, our entry for Peter with the key 'PTR' has an array of three-person identifiers.
Our lookup directory is now ready and potentially filled with the person name data, which we retrieved via our Government API.
What is missing the match_name method which allows us to lookup a name which we retrieved via the Twitter API. We are going to tackle this now.
Our first step is to collect all lookup directory entries - which match our searched name tuple — into a result list.
In code line 3 we generate all name component combinations via our existing method and the is iterating over all combinations
In code line 5 and 6 we prepare the key tuple of a combination tuple for the lookup.
In code line 7 we check if our key exists. As you can see we do the check only with the first entry of double metaphone tuple, which is stored in the first entry of the lookup directory. We leave the full implementation based on the ranking feature of the double metaphone tuple as an exercise.
if metaphone_tuple[0] in self.__lookup_dict[0]:
Running the match_name method on our sample loaded lookup directory produces the following output:
As we can see, we have two tuples which point to one person_id and one tuple peter which points to 3 persons (Obviously surnames is re-used by multiple persons). The two tuples pointing to one person have the same id 'A123'. That means our match identified exactly one person. Would we have single person tuples in our result which are pointing to different persons would mean our match isn't unique.
So we enhance our method to do this uniqueness check, as well (code line 12–20):
Do we have in our match list one or multiple tuples which always point to one single person?
If yes we a found a unique record otherwise we return None
Let’s verify the algorithm on our test sample (as explained above all the content is also available as an interactive Jupyter notebook)
So we are ready to apply the new lookup strategy to our program.
We enhance our abstract GovAPI class by integrating a NameLookupDirectory class instance.
class GovAPI(ABC): def __init__(self): self._members = [] self._nameLookupDirectory = NameLookupDirectory()
We enhance add_person_record with the code sequence to build up our lookup directory (code line 22–29)
We also add a new method for the match_name check, which will be called when we try to merge table records.
def match_name(self, name_tuple): return self._nameLookupDirectory.match_name(name_tuple)
The belowcalculate_name_matching method is not required anymore.
In this class we have to refactor the calculate_name_matching method as well, we now call for the matching, thematch_name method of the govAPI class instance (line 5).
If we have a match (7–14), we retrieve the full person record from the govAPI class.
Remember that thecalculate_name_matching method gets called via the Panda apply method on each row record and as a result, the row will be complemented with the additional new columns:
panda_data = { 'ScreenName' : self.__col_screen_name, 'Name': self.__col_name, 'Description': self.__col_description, "FollowersCount": self.__col_followers_count, "FriendsCount": self.__col_friends_count, "Party": self.__col_party }df = DataFrame(panda_data, index=self.__labels)df = df.apply(self.__calculate_name_matching, axis=1)
When we execute our program once again, our table Twitter retrieved table looks like this:
In col_match1 we list the govAPI unique id and in col_match2 our result tuple list, which was analyzed. E.g.
For the Twitter Name ‘Christian Levrat’ we found three entries in our lookup table:
‘christian leverat ’which maps to 1 person id (1150)
‘christian’ which maps to 5 person id
‘leverat’ which maps to 1 person id (11509
Our matching algorithm had a positive match because both entries are pointing to the same person id.
Let’s check out algorithm for false positives.
What are false positives?
A false positive is where you receive a positive result for a test, when you should have received a negative results. It’s sometimes called a “false alarm” or “false positive error.” It’s usually used in the medical field, but it can also apply to other areas (like software testing). (Ref)
False positive means there are problems with the accuracy of our algorithm.
When we browse through our Twitter table, we encounter the records below.
They are both pointing to the same person id. When checking the govAPI table for the record, we get back the following record “74 Christoph Eymann”, which hasn’t a Twitter account and therefore cannot be found in the Twitter table.
What went wrong:
“Christophe Darbellay” as well as “Christoph Mörgeli” were in the past politicians of the Swiss council and therefore not part of the govAPI list which we filtered for active members only.
“Christophe” as well as “Christoph” are converted to the same double metaphone string and are matching to the govAPI record 74 of “Christoph Leymann”. Due to the fact that the govAPI list has only one person with a surname “Christoph” our algorithm returns a false positive for any person with a surname “Christoph(e)” and match it to “Christoph Leymann”. Would the govAPI list two persons with the surname “Christoph” the match record would point to two persons id and wouldn’t unique anymore. Our algorithm wouldn’t result in this case a false positive.
Solution:
Well, we have to readjust our algorithm and make it more strict. That means we change the condition of our name tuple generator that we
only allow name component tuples which have at least the last name as an element.
So we readjust our method and ask for the position of the last name in the tuple by the caller, when he adds a person to the directory.
def add_person_to_lookup_directory(self, person_id, name_tuple, last_name_pos): tuples = self.generate_combinations(name_tuple) self.add_combinations_to_directory(tuples, person_id, name_tuple[last_name_pos])
In the add_combinations_to_directory method we now add only tuples which contain the last_name (line 3).
Rerunning our program results in the following matching statistics.
This is actually not better as in our first attempt (refer to the following tutorial), but we got a more robust matching algorithm. It looks like that the used Twitter politician list isn’t really up-to-date in context active members of the federal assembly. However, that’s something for the next lesson, where we want to finalize the topic of data matching and move on.
The source code you can find in the corresponding Github project, a list of all other articles here.
Happy coding then. | [
{
"code": null,
"e": 318,
"s": 172,
"text": "This is the sixth article of our journey into the Python data exploration world. Click on the link above the Title to get a list of all articles."
},
{
"code": null,
"e": 521,
"s": 318,
"text": "Let’s recap what we have achieved in our last lesson. We established a person’s name “fuzzy” name matching algorithm by using a normalization step as well as the power of the double metaphone algorithm."
},
{
"code": null,
"e": 705,
"s": 521,
"text": "The algorithm may handle typos, special characters and other differences in the name attribute BUT it fails if any of the name components are missing on the twitter account name side."
},
{
"code": null,
"e": 1163,
"s": 705,
"text": "The problem is that the Twitter account name is concatenated by the user and therefore not deterministic (well we assume he isn’t using a pseudonym and there is a chance for a match). As we have seen in the last tutorial, we tried to fix certain anomalies but the worked out solution seems not robust enough. So we have to invest additional time to build up a more robust solution, which tackles the “Missing Name Components” problem by using combinatorics."
},
{
"code": null,
"e": 1293,
"s": 1163,
"text": "As part of my own ramp up into the Python data science world, I started recently to play around with Jupyter Notebook for Python."
},
{
"code": null,
"e": 1609,
"s": 1293,
"text": "The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more."
},
{
"code": null,
"e": 1738,
"s": 1609,
"text": "It’s just awesome and via the Ancaconda distribution installed in minutes (well you need some spare disk space on your machine)."
},
{
"code": null,
"e": 1908,
"s": 1738,
"text": "I integrated it into my tutorial work-out process and from now on will describe the build out of algorithms and the coding in more detail in dedicated Jupyter notebooks."
},
{
"code": null,
"e": 2286,
"s": 1908,
"text": "You can find the Jupyter notebook for this tutorial in my Github project. Using the Jupyter Notebook (side by side with this tutorial), allows you to play around and do real-time modifications of code sequences in the notebook. Amazingly Github renders a Jupyter Notebook file in its origin and easily readable Web view format. In case you want to look at the read-only format!"
},
{
"code": null,
"e": 2476,
"s": 2286,
"text": "What we want to achieve is that our algorithm is capable of managing missing name components. In the below example we could achieve a match by omitting the 2nd name component on both sides."
},
{
"code": null,
"e": 2644,
"s": 2476,
"text": "Obviously, we want a generic algorithm which can handle any complexity in the twitter account name, i.e. a match should be possible as well in a naming construct like:"
},
{
"code": null,
"e": 2683,
"s": 2644,
"text": "“Dr. med. Peter A. Escher (Zurich)” or"
},
{
"code": null,
"e": 2748,
"s": 2683,
"text": "“Dr. med. Peteer A. Escher (Zurich)”, where the user had a typo."
},
{
"code": null,
"e": 2885,
"s": 2748,
"text": "The first problem we tackle with combinatorics, the second one, we solved already by applying the well known double metaphone algorithm."
},
{
"code": null,
"e": 3025,
"s": 2885,
"text": "To derive any kind of Name Component constellations in case of missing elements, we have to understand the basic concepts in combinatorics."
},
{
"code": null,
"e": 3193,
"s": 3025,
"text": "Let’s answer this question first. Too long away from school? Check out this helpful six minutes video (from betterExplained.com) which freshes up the various concepts."
},
{
"code": null,
"e": 3341,
"s": 3193,
"text": "Python provides in its standard library itertools already the function permutations and combinations which we want to inspect a little bit further."
},
{
"code": null,
"e": 3436,
"s": 3341,
"text": "Let’s apply it on our name sample to understand its mechanism. First the combinations function"
},
{
"code": null,
"e": 3474,
"s": 3436,
"text": "As well as the permutations function:"
},
{
"code": null,
"e": 3703,
"s": 3474,
"text": "As you can see within the permutation the order of a name component plays a role. There is a tuple for ('peter','alfred') as well as one for ('alfred','peter'). Within the combination the order of a name component is irrelevant."
},
{
"code": null,
"e": 3909,
"s": 3703,
"text": "For us, the order plays not a role, 'peter escher' is treated as'escher peter' We anyway sort the name components before we apply the double methaphone algorithm. Therefore we use the combination function."
},
{
"code": null,
"e": 4145,
"s": 3909,
"text": "Always think about “pin code” as a crib for “permutations”. Any pin code lock mechanism is based on the number of permutations of a given set of “digits” out of 10 elements: “1234” doesn’t unlock the screen which is locked with “4321”."
},
{
"code": null,
"e": 4308,
"s": 4145,
"text": "We now build up a lookup directory class which allows us to store name component combinations and compare them to a person name which we got from the Twitter API."
},
{
"code": null,
"e": 4548,
"s": 4308,
"text": "The method add_person_to_lookup_table calculates all combinations of the provided name tuple, generates for each combination the associated double metaphone key and stores the key together with the unique person id in the lookup directory."
},
{
"code": null,
"e": 4660,
"s": 4548,
"text": "The sequence diagram of the method is shown below, let’s look at the various helper methods which are required."
},
{
"code": null,
"e": 4853,
"s": 4660,
"text": "As a first step, we generate all combinations of name tuple. The following method calculates all combinations of a name tuple. For example for a 3 element tuple, the array built up consists of"
},
{
"code": null,
"e": 4880,
"s": 4853,
"text": "the 3 element tuple itself"
},
{
"code": null,
"e": 4935,
"s": 4880,
"text": "all tuples of the combination with 2 out of 3 elements"
},
{
"code": null,
"e": 4990,
"s": 4935,
"text": "all tuples of the combination with 1 out of 3 elements"
},
{
"code": null,
"e": 5079,
"s": 4990,
"text": "For example, the below 3 name tuple are resulting in the following list of combinations."
},
{
"code": null,
"e": 5167,
"s": 5079,
"text": "In this method, we build up the directory by adding each tuple to our lookup directory."
},
{
"code": null,
"e": 5379,
"s": 5167,
"text": "Our lookup directory is made of a tuple of two dictionaries, which are used store the key, value pairs. Our keys are the double metaphone tuple created from a name, and the value is the unique person identifier."
},
{
"code": null,
"e": 5404,
"s": 5379,
"text": "__lookup_dict = ({}, {})"
},
{
"code": null,
"e": 5430,
"s": 5404,
"text": "The method is shown below"
},
{
"code": null,
"e": 5539,
"s": 5430,
"text": "On code line 3 we create a normalized name string out of a name component tuple. The method looks as follows"
},
{
"code": null,
"e": 5621,
"s": 5539,
"text": "The result is a lower case string of the sorted concatenated tuple name elements:"
},
{
"code": null,
"e": 5721,
"s": 5621,
"text": "The string is used to generate the double metaphone tuple, which are our keys for the dictionaries."
},
{
"code": null,
"e": 5818,
"s": 5721,
"text": "On code line 5 and 10, we check if we have already an entry with the same key in the dictionary."
},
{
"code": null,
"e": 5858,
"s": 5818,
"text": "If not, we add the new key, value pair."
},
{
"code": null,
"e": 5992,
"s": 5858,
"text": "If there is already an entry, we check first if we have already the person_id stored. If not we add the person_id to the value array."
},
{
"code": null,
"e": 6087,
"s": 5992,
"text": "Finally, we have the method ready, which allows us to add name tuples to the lookup directory."
},
{
"code": null,
"e": 6158,
"s": 6087,
"text": "As an example, we add the following three persons to our lookup table."
},
{
"code": null,
"e": 6268,
"s": 6158,
"text": "As we can see in the output, our entry for Peter with the key 'PTR' has an array of three-person identifiers."
},
{
"code": null,
"e": 6395,
"s": 6268,
"text": "Our lookup directory is now ready and potentially filled with the person name data, which we retrieved via our Government API."
},
{
"code": null,
"e": 6539,
"s": 6395,
"text": "What is missing the match_name method which allows us to lookup a name which we retrieved via the Twitter API. We are going to tackle this now."
},
{
"code": null,
"e": 6657,
"s": 6539,
"text": "Our first step is to collect all lookup directory entries - which match our searched name tuple — into a result list."
},
{
"code": null,
"e": 6783,
"s": 6657,
"text": "In code line 3 we generate all name component combinations via our existing method and the is iterating over all combinations"
},
{
"code": null,
"e": 6868,
"s": 6783,
"text": "In code line 5 and 6 we prepare the key tuple of a combination tuple for the lookup."
},
{
"code": null,
"e": 7163,
"s": 6868,
"text": "In code line 7 we check if our key exists. As you can see we do the check only with the first entry of double metaphone tuple, which is stored in the first entry of the lookup directory. We leave the full implementation based on the ranking feature of the double metaphone tuple as an exercise."
},
{
"code": null,
"e": 7211,
"s": 7163,
"text": "if metaphone_tuple[0] in self.__lookup_dict[0]:"
},
{
"code": null,
"e": 7310,
"s": 7211,
"text": "Running the match_name method on our sample loaded lookup directory produces the following output:"
},
{
"code": null,
"e": 7711,
"s": 7310,
"text": "As we can see, we have two tuples which point to one person_id and one tuple peter which points to 3 persons (Obviously surnames is re-used by multiple persons). The two tuples pointing to one person have the same id 'A123'. That means our match identified exactly one person. Would we have single person tuples in our result which are pointing to different persons would mean our match isn't unique."
},
{
"code": null,
"e": 7792,
"s": 7711,
"text": "So we enhance our method to do this uniqueness check, as well (code line 12–20):"
},
{
"code": null,
"e": 7885,
"s": 7792,
"text": "Do we have in our match list one or multiple tuples which always point to one single person?"
},
{
"code": null,
"e": 7944,
"s": 7885,
"text": "If yes we a found a unique record otherwise we return None"
},
{
"code": null,
"e": 8080,
"s": 7944,
"text": "Let’s verify the algorithm on our test sample (as explained above all the content is also available as an interactive Jupyter notebook)"
},
{
"code": null,
"e": 8145,
"s": 8080,
"text": "So we are ready to apply the new lookup strategy to our program."
},
{
"code": null,
"e": 8235,
"s": 8145,
"text": "We enhance our abstract GovAPI class by integrating a NameLookupDirectory class instance."
},
{
"code": null,
"e": 8351,
"s": 8235,
"text": "class GovAPI(ABC): def __init__(self): self._members = [] self._nameLookupDirectory = NameLookupDirectory()"
},
{
"code": null,
"e": 8454,
"s": 8351,
"text": "We enhance add_person_record with the code sequence to build up our lookup directory (code line 22–29)"
},
{
"code": null,
"e": 8562,
"s": 8454,
"text": "We also add a new method for the match_name check, which will be called when we try to merge table records."
},
{
"code": null,
"e": 8655,
"s": 8562,
"text": "def match_name(self, name_tuple): return self._nameLookupDirectory.match_name(name_tuple)"
},
{
"code": null,
"e": 8720,
"s": 8655,
"text": "The belowcalculate_name_matching method is not required anymore."
},
{
"code": null,
"e": 8888,
"s": 8720,
"text": "In this class we have to refactor the calculate_name_matching method as well, we now call for the matching, thematch_name method of the govAPI class instance (line 5)."
},
{
"code": null,
"e": 8973,
"s": 8888,
"text": "If we have a match (7–14), we retrieve the full person record from the govAPI class."
},
{
"code": null,
"e": 9158,
"s": 8973,
"text": "Remember that thecalculate_name_matching method gets called via the Panda apply method on each row record and as a result, the row will be complemented with the additional new columns:"
},
{
"code": null,
"e": 9576,
"s": 9158,
"text": "panda_data = { 'ScreenName' : self.__col_screen_name, 'Name': self.__col_name, 'Description': self.__col_description, \"FollowersCount\": self.__col_followers_count, \"FriendsCount\": self.__col_friends_count, \"Party\": self.__col_party }df = DataFrame(panda_data, index=self.__labels)df = df.apply(self.__calculate_name_matching, axis=1)"
},
{
"code": null,
"e": 9667,
"s": 9576,
"text": "When we execute our program once again, our table Twitter retrieved table looks like this:"
},
{
"code": null,
"e": 9776,
"s": 9667,
"text": "In col_match1 we list the govAPI unique id and in col_match2 our result tuple list, which was analyzed. E.g."
},
{
"code": null,
"e": 9860,
"s": 9776,
"text": "For the Twitter Name ‘Christian Levrat’ we found three entries in our lookup table:"
},
{
"code": null,
"e": 9913,
"s": 9860,
"text": "‘christian leverat ’which maps to 1 person id (1150)"
},
{
"code": null,
"e": 9951,
"s": 9913,
"text": "‘christian’ which maps to 5 person id"
},
{
"code": null,
"e": 9994,
"s": 9951,
"text": "‘leverat’ which maps to 1 person id (11509"
},
{
"code": null,
"e": 10095,
"s": 9994,
"text": "Our matching algorithm had a positive match because both entries are pointing to the same person id."
},
{
"code": null,
"e": 10142,
"s": 10095,
"text": "Let’s check out algorithm for false positives."
},
{
"code": null,
"e": 10168,
"s": 10142,
"text": "What are false positives?"
},
{
"code": null,
"e": 10459,
"s": 10168,
"text": "A false positive is where you receive a positive result for a test, when you should have received a negative results. It’s sometimes called a “false alarm” or “false positive error.” It’s usually used in the medical field, but it can also apply to other areas (like software testing). (Ref)"
},
{
"code": null,
"e": 10535,
"s": 10459,
"text": "False positive means there are problems with the accuracy of our algorithm."
},
{
"code": null,
"e": 10609,
"s": 10535,
"text": "When we browse through our Twitter table, we encounter the records below."
},
{
"code": null,
"e": 10841,
"s": 10609,
"text": "They are both pointing to the same person id. When checking the govAPI table for the record, we get back the following record “74 Christoph Eymann”, which hasn’t a Twitter account and therefore cannot be found in the Twitter table."
},
{
"code": null,
"e": 10858,
"s": 10841,
"text": "What went wrong:"
},
{
"code": null,
"e": 11048,
"s": 10858,
"text": "“Christophe Darbellay” as well as “Christoph Mörgeli” were in the past politicians of the Swiss council and therefore not part of the govAPI list which we filtered for active members only."
},
{
"code": null,
"e": 11604,
"s": 11048,
"text": "“Christophe” as well as “Christoph” are converted to the same double metaphone string and are matching to the govAPI record 74 of “Christoph Leymann”. Due to the fact that the govAPI list has only one person with a surname “Christoph” our algorithm returns a false positive for any person with a surname “Christoph(e)” and match it to “Christoph Leymann”. Would the govAPI list two persons with the surname “Christoph” the match record would point to two persons id and wouldn’t unique anymore. Our algorithm wouldn’t result in this case a false positive."
},
{
"code": null,
"e": 11614,
"s": 11604,
"text": "Solution:"
},
{
"code": null,
"e": 11750,
"s": 11614,
"text": "Well, we have to readjust our algorithm and make it more strict. That means we change the condition of our name tuple generator that we"
},
{
"code": null,
"e": 11832,
"s": 11750,
"text": "only allow name component tuples which have at least the last name as an element."
},
{
"code": null,
"e": 11968,
"s": 11832,
"text": "So we readjust our method and ask for the position of the last name in the tuple by the caller, when he adds a person to the directory."
},
{
"code": null,
"e": 12183,
"s": 11968,
"text": "def add_person_to_lookup_directory(self, person_id, name_tuple, last_name_pos): tuples = self.generate_combinations(name_tuple) self.add_combinations_to_directory(tuples, person_id, name_tuple[last_name_pos])"
},
{
"code": null,
"e": 12288,
"s": 12183,
"text": "In the add_combinations_to_directory method we now add only tuples which contain the last_name (line 3)."
},
{
"code": null,
"e": 12356,
"s": 12288,
"text": "Rerunning our program results in the following matching statistics."
},
{
"code": null,
"e": 12728,
"s": 12356,
"text": "This is actually not better as in our first attempt (refer to the following tutorial), but we got a more robust matching algorithm. It looks like that the used Twitter politician list isn’t really up-to-date in context active members of the federal assembly. However, that’s something for the next lesson, where we want to finalize the topic of data matching and move on."
},
{
"code": null,
"e": 12829,
"s": 12728,
"text": "The source code you can find in the corresponding Github project, a list of all other articles here."
}
] |
How to get all the services based on their status in PowerShell? | Below commands will filter out services based on their Status (Running, Stopped).
To get all the running services on the local computer.
Get-Service | where{$_.Status -eq "Running"}
Running TimeBrokerSvc Time Broker
Running TokenBroker Web Account Manager
Running TrkWks Distributed Link Tracking Client
Running UnistoreSvc_158379 User Data Storage_158379
Running UserDataSvc_158379 User Data Access_158379
Running UserManager User Manager
Running UsoSvc Update Orchestrator Service
Running VaultSvc Credential Manager
Running VMUSBArbService VMware USB Arbitration Service
Running WavesSysSvc Waves Audio Services
Running WbioSrvc Windows Biometric Service
To get all the stopped services on the local computer.
Get-Service | where{$_.Status -eq "Stopped"}
Stopped vmicvss Hyper-V Volume Shadow Copy Requestor
Stopped VSS Volume Shadow Copy
Stopped VSStandardColle... Visual Studio Standard Collector Se...
Stopped W32Time Windows Time
Stopped WaaSMedicSvc Windows Update Medic Service
Stopped WalletService WalletService
Stopped WarpJITSvc WarpJITSvc
Stopped wbengine Block Level Backup Engine Service
Stopped wcncsvc Windows Connect Now - Config Registrar
Stopped WdNisSvc Windows Defender Antivirus Network ...
Stopped Wecsvc Windows Event Collector
Stopped WEPHOSTSVC Windows Encryption Provider Host Se... | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Below commands will filter out services based on their Status (Running, Stopped)."
},
{
"code": null,
"e": 1199,
"s": 1144,
"text": "To get all the running services on the local computer."
},
{
"code": null,
"e": 1244,
"s": 1199,
"text": "Get-Service | where{$_.Status -eq \"Running\"}"
},
{
"code": null,
"e": 1804,
"s": 1244,
"text": "Running TimeBrokerSvc Time Broker\nRunning TokenBroker Web Account Manager\nRunning TrkWks Distributed Link Tracking Client\nRunning UnistoreSvc_158379 User Data Storage_158379\nRunning UserDataSvc_158379 User Data Access_158379\nRunning UserManager User Manager\nRunning UsoSvc Update Orchestrator Service\nRunning VaultSvc Credential Manager\nRunning VMUSBArbService VMware USB Arbitration Service\nRunning WavesSysSvc Waves Audio Services\nRunning WbioSrvc Windows Biometric Service"
},
{
"code": null,
"e": 1859,
"s": 1804,
"text": "To get all the stopped services on the local computer."
},
{
"code": null,
"e": 1905,
"s": 1859,
"text": "Get-Service | where{$_.Status -eq \"Stopped\"}\n"
},
{
"code": null,
"e": 2578,
"s": 1905,
"text": "Stopped vmicvss Hyper-V Volume Shadow Copy Requestor\nStopped VSS Volume Shadow Copy\nStopped VSStandardColle... Visual Studio Standard Collector Se...\nStopped W32Time Windows Time\nStopped WaaSMedicSvc Windows Update Medic Service\nStopped WalletService WalletService\nStopped WarpJITSvc WarpJITSvc\nStopped wbengine Block Level Backup Engine Service\nStopped wcncsvc Windows Connect Now - Config Registrar\nStopped WdNisSvc Windows Defender Antivirus Network ...\nStopped Wecsvc Windows Event Collector\nStopped WEPHOSTSVC Windows Encryption Provider Host Se..."
}
] |
Java 8 - Overview | JAVA 8 is a major feature release of JAVA programming language development. Its initial version was released on 18 March 2014. With the Java 8 release, Java provided supports for functional programming, new JavaScript engine, new APIs for date time manipulation, new streaming API, etc.
Lambda expression − Adds functional processing capability to Java.
Lambda expression − Adds functional processing capability to Java.
Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter.
Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter.
Default method − Interface to have default method implementation.
Default method − Interface to have default method implementation.
New tools − New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies.
New tools − New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies.
Stream API − New stream API to facilitate pipeline processing.
Stream API − New stream API to facilitate pipeline processing.
Date Time API − Improved date time API.
Date Time API − Improved date time API.
Optional − Emphasis on best practices to handle null values properly.
Optional − Emphasis on best practices to handle null values properly.
Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code.
Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code.
Consider the following code snippet.
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
public class Java8Tester {
public static void main(String args[]) {
List<String> names1 = new ArrayList<String>();
names1.add("Mahesh ");
names1.add("Suresh ");
names1.add("Ramesh ");
names1.add("Naresh ");
names1.add("Kalpesh ");
List<String> names2 = new ArrayList<String>();
names2.add("Mahesh ");
names2.add("Suresh ");
names2.add("Ramesh ");
names2.add("Naresh ");
names2.add("Kalpesh ");
Java8Tester tester = new Java8Tester();
System.out.println("Sort using Java 7 syntax: ");
tester.sortUsingJava7(names1);
System.out.println(names1);
System.out.println("Sort using Java 8 syntax: ");
tester.sortUsingJava8(names2);
System.out.println(names2);
}
//sort using java 7
private void sortUsingJava7(List<String> names) {
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
}
//sort using java 8
private void sortUsingJava8(List<String> names) {
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
}
}
Run the program to get the following result.
Sort using Java 7 syntax:
[ Kalpesh Mahesh Naresh Ramesh Suresh ]
Sort using Java 8 syntax:
[ Kalpesh Mahesh Naresh Ramesh Suresh ]
Here the sortUsingJava8() method uses sort function with a lambda expression as parameter to get the sorting criteria.
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2161,
"s": 1874,
"text": "JAVA 8 is a major feature release of JAVA programming language development. Its initial version was released on 18 March 2014. With the Java 8 release, Java provided supports for functional programming, new JavaScript engine, new APIs for date time manipulation, new streaming API, etc."
},
{
"code": null,
"e": 2228,
"s": 2161,
"text": "Lambda expression − Adds functional processing capability to Java."
},
{
"code": null,
"e": 2295,
"s": 2228,
"text": "Lambda expression − Adds functional processing capability to Java."
},
{
"code": null,
"e": 2417,
"s": 2295,
"text": "Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter."
},
{
"code": null,
"e": 2539,
"s": 2417,
"text": "Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter."
},
{
"code": null,
"e": 2605,
"s": 2539,
"text": "Default method − Interface to have default method implementation."
},
{
"code": null,
"e": 2671,
"s": 2605,
"text": "Default method − Interface to have default method implementation."
},
{
"code": null,
"e": 2767,
"s": 2671,
"text": "New tools − New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies."
},
{
"code": null,
"e": 2863,
"s": 2767,
"text": "New tools − New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies."
},
{
"code": null,
"e": 2926,
"s": 2863,
"text": "Stream API − New stream API to facilitate pipeline processing."
},
{
"code": null,
"e": 2989,
"s": 2926,
"text": "Stream API − New stream API to facilitate pipeline processing."
},
{
"code": null,
"e": 3029,
"s": 2989,
"text": "Date Time API − Improved date time API."
},
{
"code": null,
"e": 3069,
"s": 3029,
"text": "Date Time API − Improved date time API."
},
{
"code": null,
"e": 3139,
"s": 3069,
"text": "Optional − Emphasis on best practices to handle null values properly."
},
{
"code": null,
"e": 3209,
"s": 3139,
"text": "Optional − Emphasis on best practices to handle null values properly."
},
{
"code": null,
"e": 3286,
"s": 3209,
"text": "Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code."
},
{
"code": null,
"e": 3363,
"s": 3286,
"text": "Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code."
},
{
"code": null,
"e": 3400,
"s": 3363,
"text": "Consider the following code snippet."
},
{
"code": null,
"e": 4724,
"s": 3400,
"text": "import java.util.Collections;\nimport java.util.List;\nimport java.util.ArrayList;\nimport java.util.Comparator;\n\npublic class Java8Tester {\n\n public static void main(String args[]) {\n \n List<String> names1 = new ArrayList<String>();\n names1.add(\"Mahesh \");\n names1.add(\"Suresh \");\n names1.add(\"Ramesh \");\n names1.add(\"Naresh \");\n names1.add(\"Kalpesh \");\n\t\t\n List<String> names2 = new ArrayList<String>();\n names2.add(\"Mahesh \");\n names2.add(\"Suresh \");\n names2.add(\"Ramesh \");\n names2.add(\"Naresh \");\n names2.add(\"Kalpesh \");\n\t\t\n Java8Tester tester = new Java8Tester();\n System.out.println(\"Sort using Java 7 syntax: \");\n\t\t\n tester.sortUsingJava7(names1);\n System.out.println(names1);\n System.out.println(\"Sort using Java 8 syntax: \");\n\t\t\n tester.sortUsingJava8(names2);\n System.out.println(names2);\n }\n \n //sort using java 7\n private void sortUsingJava7(List<String> names) { \n Collections.sort(names, new Comparator<String>() {\n @Override\n public int compare(String s1, String s2) {\n return s1.compareTo(s2);\n }\n });\n }\n \n //sort using java 8\n private void sortUsingJava8(List<String> names) {\n Collections.sort(names, (s1, s2) -> s1.compareTo(s2));\n }\n}"
},
{
"code": null,
"e": 4769,
"s": 4724,
"text": "Run the program to get the following result."
},
{
"code": null,
"e": 4902,
"s": 4769,
"text": "Sort using Java 7 syntax:\n[ Kalpesh Mahesh Naresh Ramesh Suresh ]\nSort using Java 8 syntax:\n[ Kalpesh Mahesh Naresh Ramesh Suresh ]\n"
},
{
"code": null,
"e": 5021,
"s": 4902,
"text": "Here the sortUsingJava8() method uses sort function with a lambda expression as parameter to get the sorting criteria."
},
{
"code": null,
"e": 5054,
"s": 5021,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5070,
"s": 5054,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5103,
"s": 5070,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5119,
"s": 5103,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5154,
"s": 5119,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5168,
"s": 5154,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5202,
"s": 5168,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5216,
"s": 5202,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5253,
"s": 5216,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5268,
"s": 5253,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5301,
"s": 5268,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5320,
"s": 5301,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5327,
"s": 5320,
"text": " Print"
},
{
"code": null,
"e": 5338,
"s": 5327,
"text": " Add Notes"
}
] |
Tryit Editor v3.7 | HTML Input types
Tryit: HTML input element | [
{
"code": null,
"e": 27,
"s": 10,
"text": "HTML Input types"
}
] |
Demystifying Quantum Gates — One Qubit At A Time | by Jason Roell | Towards Data Science | (I’ve written an introduction to quantum computing found here. If you are brand new to the field, it will be a better place to start.)
If you want to get into quantum computing, there’s no way around it: you will have to master the cloudy concept of the quantum gate. Like everything in quantum computing, not to mention quantum mechanics, quantum gates are shrouded in an unfamiliar fog of jargon and matrix mathematics that reflects the quantum mystery. My goal in this post is to peel off a few layers of that mystery. But I’ll save you the suspense: no one can get rid of it completely. At least, not in 2018. All we can do today is reveal the striking similarities and alarming differences between classical gates and quantum gates, and explore the implications for the near and far future of computing.
If nothing else, classical logic gates and quantum logic gates are both logic gates. So let’s start there. A logic gate, whether classical or quantum, is any physical structure or system that takes a set of binary inputs (whether 0s and 1s, apples and oranges, spin-up electrons and spin-down electrons, you name it) and spits out a single binary output: a 1, an orange, a spin-up electron, or even one of two states of superposition. What governs the output is a Boolean function. That sounds fancy and foreboding, but trust me, it’s not. You can think of a Boolean function as nothing more than a rule for how to respond to Yes/No questions. It’s as simple as that. The gates are then combined into circuits, and the circuits into CPUs or other computational components. This is true whether we’re talking about Babbage’s Difference Engine, ENIAC, retired chess champion Deep Blue, or the latest room-filling, bone-chilling, headline-making quantum computer.
Classical gates operate on classical bits, while quantum gates operate on quantum bits (qubits). This means that quantum gates can leverage two key aspects of quantum mechanics that are entirely out of reach for classical gates: superposition and entanglement. These are the two concepts that you’ll hear about most often in the context of quantum computing, and here’s why. But there’s a lesser known concept that’s perhaps equally important: reversibility. Simply put, quantum gates are reversible. You’ll learn a lot about reversibility as you go further into quantum computing, so it’s worth really digging into it. For now, you can think of it this way — all quantum gates come with an undo button, while many classical gates don’t, at least not yet. This means that, at least in principle, quantum gates never lose information. Qubits that are entangled on their way into the quantum gate remain entangled on the way out, keeping their information safely sealed throughout the transition. Many of the classical gates found in conventional computers, on the other hand, do lose information, and therefore can’t retrace their steps. Interestingly enough, that information is not ultimately lost to the universe, but rather seeps out into your room or your lap as the heat in your classical computer.
We can’t talk about quantum gates without talking about matrices, and we can’t talk about matrices without talking about vectors. So let’s get on with it. In the language of quantum mechanics and computing, vectors are depicted in an admittedly pretty weird package called a ket, which comes from the second half of the word braket. And they look the part. Here’s a ket vector: |u>, where u represents the values in the vector. For starters, we’ll use two kets, |0> and |1>, which will stand-in for qubits in the form of electrons in the spin-up (|0>) and spin-down (|1>) states. These vectors can span any number of numbers, so to speak. But in the case of a binary state such as a spin up/down electron qubit, they have only two. So instead of looking like towering column vectors, they just looked like numbers stacked two-high. Here’s what |0> looks like:
/ 1 \
\ 0 /
Now, what gates/matrices do is transform these states, these vectors, these kets, these columns of numbers, into brand new ones. For example, a gate can transform an up-state (|0>) into a down state (|1>), like magic:
/ 1 \ → / 0 \
\ 0 / \ 1 /
This transformation of one vector into another takes place through the barely understood magic of matrix multiplication, which is completely different than the kind of multiplication we all learned in pre-quantum school. However, once you get the hang of this kind of math, it’s extremely rewarding, because you can apply it again and again to countless otherwise incomprehensible equations that leave the uninitiated stupefied. If you need some more motivation, just remember that it was through the language of matrix mathematics that Heisenberg unlocked the secrets of the all-encompassing uncertainty principle.
All the same, if you’re not familiar with this jet-fuel of a mathematical tool, your eyes will glaze over if I start filling this post with big square arrays of numbers at this point. And we can’t let that happen. So let’s wait a few more paragraphs for the matrix math and notation. Suffice it to say, for now, that we generally use a matrix to stand-in for a quantum gate. The size and outright fear-factor of the matrix will depend on the number of qubits it’s operating on. If there’s just one qubit to transform, the matrix will be nice and simple, just a 2 x 2 array with four elements. But the size of the matrix balloons with two, three or more qubits. This is because a decidedly exponential equation that’s well worth memorizing drives the size of the matrix (and thus the sophistication of the quantum gate):
2^n x 2^n = the total number of matrix elements
Here, n is the number of qubits the quantum gate is operating on. As you can see, this number goes through the roof as the number of qubits (n) increases. With one qubit, it’s 4. With two, it’s 16. With three, it’s 64. With four, it’s... hopeless. So for now, I’m sticking to one qubit, and it’s got Pauli written all over it.
The Pauli gates are named after Wolfgang Pauli, who not only has a cool name, but has managed to immortalize himself in two of the best-known principles of modern physics: the celebrated Pauli exclusion principle and the dreaded Pauli effect.
The Pauli gates are based on the better-known Pauli matrices (aka Pauli spin matrices) which are incredibly useful for calculating changes to the spin of a single electron. Since electron spin is the favored property to use for a qubit in today’s quantum gates, Pauli matrices and gates are right up our alley. In any event, there’s essentially one Pauli gate/matrix for each axis in space (X, Y and Z).
So you can picture each one of them wielding the power to change the direction of an electron’s spin along their corresponding axis in 3D space. Of course, like everything else in the quantum world, there’s a catch: this is not our ordinary 3D space, because it includes an imaginary dimension. But let’s let that slide for now, shall we?
Mercifully, the Pauli gates are just about the simplest quantum gates you’re ever going to meet. (At least the X and Z-gates are. The Y is a little weird.) So even if you’ve never seen a matrix in your life, Pauli makes them manageable. His gates act on one, and only one, qubit at a time. This translates to simple, 2 x 2 matrices with only 4 elements a piece.
The Pauli X-gate is a dream come true for those that fear matrix math. No imaginary numbers. No minus signs. And a simple operation: negation. This is only natural, because the Pauli X-gate corresponds to a classical NOT gate. For this reason, the X-gate is often called the quantum NOT gate as well.
In an actual real-world setting, the X-gate generally turns the spin-up state |0> of an electron into a spin-down state |1> and vice-versa.
|0> --> |1> OR |1> --> |0>
A capital “X” often stands in for the Pauli X-gate or matrix itself. Here’s what X looks like:
/ 0 1 \
\ 1 0 /
In terms of proper notation, applying a quantum gate to a qubit is a matter of multiplying a ket vector by a matrix. In this case, we are multiplying the spin-up ket vector |0> by the Pauli X-gate or matrix X. Here’s what X|0> looks like:
/ 0 1 \ /1\
\ 1 0 / \0/
Note that you always place the matrix to the left of the ket. As you may have heard, matrix multiplication, unlike ordinary multiplication, does not commute, which goes against everything we were taught in school. It’s as if 2 x 4 was not always equal to 4 x 2. But that’s how matrix multiplication works, and once you get the hang of it, you’ll see why. Meanwhile, keeping the all-important ordering of elements in mind, the complete notation for applying the quantum NOT-gate to our qubit (in this case the spin-up state of an electron), looks like this:
X|0> = / 0 1 \ /1\ = /0\ = |1>
\ 1 0 / \0/ \1/
Applied to a spin-down vector, the complete notation looks like this:
X|1> = / 0 1 \ /0\ = /1\ = |0>
\ 1 0 / \1/ \0/
Despite all the foreign notation, in both of these cases what’s actually happening here is that a qubit in the form of a single electron is passing through a quantum gate and coming out the other side with its spin flipped completely over.
I’ll spare you the math with these two. But you should at least know about them in passing.
Of the three Pauli gates, the Pauli Y-gate is the fancy one. It looks a lot like the X-gate, but with an i (yep, the insane square root of -1) in place of the regular 1, and a negative sign in the upper right. Here’s what Y looks like:
/ 0 -i \
\ i 0 /
The Pauli Z-gate is far easier to follow. It looks kind of like a mirror image of the X-gate above, but with a negative sign thrown into the mix. Here’s what Z looks like:
/ 1 0 \
\ 0 -1 /
The Y-gate and the Z-gate also change the spin of our qubit electron. But I’d probably need to delve into the esoteric mysteries of the Bloch sphere to really explain how, and I’ve got another gate to go through at the moment...
While the Pauli gates are a lot like classic logic gates in some respects, the Hadamard gate, or H-gate, is a bona fide quantum beast. It shows up everywhere in quantum computing, and for good reason. The Hadamard gate has the characteristically quantum capacity to transform a definite quantum state, such as spin-up, into a murky one, such as a superposition of both spin-up and spin-down at the same time.
Once you send a spin-up or spin-down electron through an H-gate, it will become like a penny standing on its end, with precisely 50/50 odds that it will end up heads (spin-up) or tails (spin-down) when toppled and measured. This H-gate is extremely useful for performing the first computation in any quantum program because it transforms pre-set, or initialized, qubits back into their natural fluid state in order to leverage their full quantum powers.
There are a number of other quantum gates you’re bound to run into. Many of them operate on several qubits at a time, leading to 4x4 or even 8x8 matrices with complex-numbered elements. These are pretty hairy if you don’t already have some serious matrix skills under your belt. So I’ll spare you the details.
The main gates that you will want to be familiar are the ones we covered shown in the graph below:
You should know that other gates exist so here’s a quick list of some of the most widely used other quantum gates, just so you can get a feel for the jargon:
Toffoli gateFredkin gate
Deutsch gate
Swap gate (and swap-gate square root)
NOT-gate square root
Controlled-NOT gate (C-NOT) and other controlled gates
There are many more. But don’t let the numbers fool you. Just as you can perform any classical computation with a combination of NOT + OR = NOR gates or AND + NOT= NAND gates, you can reduce the list of quantum gates to a simple set of universal quantum gates. But we’ll save that deed for another day.
As a recent Quanta Magazine article points out, the quantum computers of 2018 aren’t quite ready for prime time. Before they can step into the ring with classical computers with billions of times as many logic gates, they will need to face a few of their own demons. The most deadly is probably the demon of decoherence. Right now, quantum decoherence will destroy your quantum computation in just “a few microseconds.” However, the faster your quantum gates perform their operations, the more likely your quantum algorithm will beat the demon of decoherence to the finish line, and the longer the race will last. Alongside speed, another important factor is the sheer number of operations performed by quantum gates to complete a calculation. This is known as a computation’s depth. So another current quest is to deepen the quantum playing field. By this logic, as the rapidly evolving quantum computer gets faster, its calculations deeper, and the countdown-to-decoherence longer, the classical computer will eventually find itself facing a formidable challenger, if not successor, in the (quite possibly) not too far future.
If you liked this article I would be super excited if you hit the clap button :) or share with your curious friends. I’ve got much more like it over at my personal blog (jasonroell.com) or you can just subscribe to my medium profile and get all my articles sent to you as soon as I write them! (how awesome?!)
Anyway, thanks again for reading have a great day! | [
{
"code": null,
"e": 307,
"s": 172,
"text": "(I’ve written an introduction to quantum computing found here. If you are brand new to the field, it will be a better place to start.)"
},
{
"code": null,
"e": 981,
"s": 307,
"text": "If you want to get into quantum computing, there’s no way around it: you will have to master the cloudy concept of the quantum gate. Like everything in quantum computing, not to mention quantum mechanics, quantum gates are shrouded in an unfamiliar fog of jargon and matrix mathematics that reflects the quantum mystery. My goal in this post is to peel off a few layers of that mystery. But I’ll save you the suspense: no one can get rid of it completely. At least, not in 2018. All we can do today is reveal the striking similarities and alarming differences between classical gates and quantum gates, and explore the implications for the near and far future of computing."
},
{
"code": null,
"e": 1942,
"s": 981,
"text": "If nothing else, classical logic gates and quantum logic gates are both logic gates. So let’s start there. A logic gate, whether classical or quantum, is any physical structure or system that takes a set of binary inputs (whether 0s and 1s, apples and oranges, spin-up electrons and spin-down electrons, you name it) and spits out a single binary output: a 1, an orange, a spin-up electron, or even one of two states of superposition. What governs the output is a Boolean function. That sounds fancy and foreboding, but trust me, it’s not. You can think of a Boolean function as nothing more than a rule for how to respond to Yes/No questions. It’s as simple as that. The gates are then combined into circuits, and the circuits into CPUs or other computational components. This is true whether we’re talking about Babbage’s Difference Engine, ENIAC, retired chess champion Deep Blue, or the latest room-filling, bone-chilling, headline-making quantum computer."
},
{
"code": null,
"e": 3246,
"s": 1942,
"text": "Classical gates operate on classical bits, while quantum gates operate on quantum bits (qubits). This means that quantum gates can leverage two key aspects of quantum mechanics that are entirely out of reach for classical gates: superposition and entanglement. These are the two concepts that you’ll hear about most often in the context of quantum computing, and here’s why. But there’s a lesser known concept that’s perhaps equally important: reversibility. Simply put, quantum gates are reversible. You’ll learn a lot about reversibility as you go further into quantum computing, so it’s worth really digging into it. For now, you can think of it this way — all quantum gates come with an undo button, while many classical gates don’t, at least not yet. This means that, at least in principle, quantum gates never lose information. Qubits that are entangled on their way into the quantum gate remain entangled on the way out, keeping their information safely sealed throughout the transition. Many of the classical gates found in conventional computers, on the other hand, do lose information, and therefore can’t retrace their steps. Interestingly enough, that information is not ultimately lost to the universe, but rather seeps out into your room or your lap as the heat in your classical computer."
},
{
"code": null,
"e": 4106,
"s": 3246,
"text": "We can’t talk about quantum gates without talking about matrices, and we can’t talk about matrices without talking about vectors. So let’s get on with it. In the language of quantum mechanics and computing, vectors are depicted in an admittedly pretty weird package called a ket, which comes from the second half of the word braket. And they look the part. Here’s a ket vector: |u>, where u represents the values in the vector. For starters, we’ll use two kets, |0> and |1>, which will stand-in for qubits in the form of electrons in the spin-up (|0>) and spin-down (|1>) states. These vectors can span any number of numbers, so to speak. But in the case of a binary state such as a spin up/down electron qubit, they have only two. So instead of looking like towering column vectors, they just looked like numbers stacked two-high. Here’s what |0> looks like:"
},
{
"code": null,
"e": 4112,
"s": 4106,
"text": "/ 1 \\"
},
{
"code": null,
"e": 4118,
"s": 4112,
"text": "\\ 0 /"
},
{
"code": null,
"e": 4336,
"s": 4118,
"text": "Now, what gates/matrices do is transform these states, these vectors, these kets, these columns of numbers, into brand new ones. For example, a gate can transform an up-state (|0>) into a down state (|1>), like magic:"
},
{
"code": null,
"e": 4350,
"s": 4336,
"text": "/ 1 \\ → / 0 \\"
},
{
"code": null,
"e": 4362,
"s": 4350,
"text": "\\ 0 / \\ 1 /"
},
{
"code": null,
"e": 4978,
"s": 4362,
"text": "This transformation of one vector into another takes place through the barely understood magic of matrix multiplication, which is completely different than the kind of multiplication we all learned in pre-quantum school. However, once you get the hang of this kind of math, it’s extremely rewarding, because you can apply it again and again to countless otherwise incomprehensible equations that leave the uninitiated stupefied. If you need some more motivation, just remember that it was through the language of matrix mathematics that Heisenberg unlocked the secrets of the all-encompassing uncertainty principle."
},
{
"code": null,
"e": 5798,
"s": 4978,
"text": "All the same, if you’re not familiar with this jet-fuel of a mathematical tool, your eyes will glaze over if I start filling this post with big square arrays of numbers at this point. And we can’t let that happen. So let’s wait a few more paragraphs for the matrix math and notation. Suffice it to say, for now, that we generally use a matrix to stand-in for a quantum gate. The size and outright fear-factor of the matrix will depend on the number of qubits it’s operating on. If there’s just one qubit to transform, the matrix will be nice and simple, just a 2 x 2 array with four elements. But the size of the matrix balloons with two, three or more qubits. This is because a decidedly exponential equation that’s well worth memorizing drives the size of the matrix (and thus the sophistication of the quantum gate):"
},
{
"code": null,
"e": 5846,
"s": 5798,
"text": "2^n x 2^n = the total number of matrix elements"
},
{
"code": null,
"e": 6173,
"s": 5846,
"text": "Here, n is the number of qubits the quantum gate is operating on. As you can see, this number goes through the roof as the number of qubits (n) increases. With one qubit, it’s 4. With two, it’s 16. With three, it’s 64. With four, it’s... hopeless. So for now, I’m sticking to one qubit, and it’s got Pauli written all over it."
},
{
"code": null,
"e": 6416,
"s": 6173,
"text": "The Pauli gates are named after Wolfgang Pauli, who not only has a cool name, but has managed to immortalize himself in two of the best-known principles of modern physics: the celebrated Pauli exclusion principle and the dreaded Pauli effect."
},
{
"code": null,
"e": 6820,
"s": 6416,
"text": "The Pauli gates are based on the better-known Pauli matrices (aka Pauli spin matrices) which are incredibly useful for calculating changes to the spin of a single electron. Since electron spin is the favored property to use for a qubit in today’s quantum gates, Pauli matrices and gates are right up our alley. In any event, there’s essentially one Pauli gate/matrix for each axis in space (X, Y and Z)."
},
{
"code": null,
"e": 7159,
"s": 6820,
"text": "So you can picture each one of them wielding the power to change the direction of an electron’s spin along their corresponding axis in 3D space. Of course, like everything else in the quantum world, there’s a catch: this is not our ordinary 3D space, because it includes an imaginary dimension. But let’s let that slide for now, shall we?"
},
{
"code": null,
"e": 7521,
"s": 7159,
"text": "Mercifully, the Pauli gates are just about the simplest quantum gates you’re ever going to meet. (At least the X and Z-gates are. The Y is a little weird.) So even if you’ve never seen a matrix in your life, Pauli makes them manageable. His gates act on one, and only one, qubit at a time. This translates to simple, 2 x 2 matrices with only 4 elements a piece."
},
{
"code": null,
"e": 7822,
"s": 7521,
"text": "The Pauli X-gate is a dream come true for those that fear matrix math. No imaginary numbers. No minus signs. And a simple operation: negation. This is only natural, because the Pauli X-gate corresponds to a classical NOT gate. For this reason, the X-gate is often called the quantum NOT gate as well."
},
{
"code": null,
"e": 7962,
"s": 7822,
"text": "In an actual real-world setting, the X-gate generally turns the spin-up state |0> of an electron into a spin-down state |1> and vice-versa."
},
{
"code": null,
"e": 7997,
"s": 7962,
"text": "|0> --> |1> OR |1> --> |0>"
},
{
"code": null,
"e": 8092,
"s": 7997,
"text": "A capital “X” often stands in for the Pauli X-gate or matrix itself. Here’s what X looks like:"
},
{
"code": null,
"e": 8100,
"s": 8092,
"text": "/ 0 1 \\"
},
{
"code": null,
"e": 8108,
"s": 8100,
"text": "\\ 1 0 /"
},
{
"code": null,
"e": 8347,
"s": 8108,
"text": "In terms of proper notation, applying a quantum gate to a qubit is a matter of multiplying a ket vector by a matrix. In this case, we are multiplying the spin-up ket vector |0> by the Pauli X-gate or matrix X. Here’s what X|0> looks like:"
},
{
"code": null,
"e": 8359,
"s": 8347,
"text": "/ 0 1 \\ /1\\"
},
{
"code": null,
"e": 8371,
"s": 8359,
"text": "\\ 1 0 / \\0/"
},
{
"code": null,
"e": 8928,
"s": 8371,
"text": "Note that you always place the matrix to the left of the ket. As you may have heard, matrix multiplication, unlike ordinary multiplication, does not commute, which goes against everything we were taught in school. It’s as if 2 x 4 was not always equal to 4 x 2. But that’s how matrix multiplication works, and once you get the hang of it, you’ll see why. Meanwhile, keeping the all-important ordering of elements in mind, the complete notation for applying the quantum NOT-gate to our qubit (in this case the spin-up state of an electron), looks like this:"
},
{
"code": null,
"e": 8959,
"s": 8928,
"text": "X|0> = / 0 1 \\ /1\\ = /0\\ = |1>"
},
{
"code": null,
"e": 8975,
"s": 8959,
"text": "\\ 1 0 / \\0/ \\1/"
},
{
"code": null,
"e": 9045,
"s": 8975,
"text": "Applied to a spin-down vector, the complete notation looks like this:"
},
{
"code": null,
"e": 9076,
"s": 9045,
"text": "X|1> = / 0 1 \\ /0\\ = /1\\ = |0>"
},
{
"code": null,
"e": 9092,
"s": 9076,
"text": "\\ 1 0 / \\1/ \\0/"
},
{
"code": null,
"e": 9332,
"s": 9092,
"text": "Despite all the foreign notation, in both of these cases what’s actually happening here is that a qubit in the form of a single electron is passing through a quantum gate and coming out the other side with its spin flipped completely over."
},
{
"code": null,
"e": 9424,
"s": 9332,
"text": "I’ll spare you the math with these two. But you should at least know about them in passing."
},
{
"code": null,
"e": 9660,
"s": 9424,
"text": "Of the three Pauli gates, the Pauli Y-gate is the fancy one. It looks a lot like the X-gate, but with an i (yep, the insane square root of -1) in place of the regular 1, and a negative sign in the upper right. Here’s what Y looks like:"
},
{
"code": null,
"e": 9669,
"s": 9660,
"text": "/ 0 -i \\"
},
{
"code": null,
"e": 9677,
"s": 9669,
"text": "\\ i 0 /"
},
{
"code": null,
"e": 9849,
"s": 9677,
"text": "The Pauli Z-gate is far easier to follow. It looks kind of like a mirror image of the X-gate above, but with a negative sign thrown into the mix. Here’s what Z looks like:"
},
{
"code": null,
"e": 9857,
"s": 9849,
"text": "/ 1 0 \\"
},
{
"code": null,
"e": 9866,
"s": 9857,
"text": "\\ 0 -1 /"
},
{
"code": null,
"e": 10095,
"s": 9866,
"text": "The Y-gate and the Z-gate also change the spin of our qubit electron. But I’d probably need to delve into the esoteric mysteries of the Bloch sphere to really explain how, and I’ve got another gate to go through at the moment..."
},
{
"code": null,
"e": 10504,
"s": 10095,
"text": "While the Pauli gates are a lot like classic logic gates in some respects, the Hadamard gate, or H-gate, is a bona fide quantum beast. It shows up everywhere in quantum computing, and for good reason. The Hadamard gate has the characteristically quantum capacity to transform a definite quantum state, such as spin-up, into a murky one, such as a superposition of both spin-up and spin-down at the same time."
},
{
"code": null,
"e": 10958,
"s": 10504,
"text": "Once you send a spin-up or spin-down electron through an H-gate, it will become like a penny standing on its end, with precisely 50/50 odds that it will end up heads (spin-up) or tails (spin-down) when toppled and measured. This H-gate is extremely useful for performing the first computation in any quantum program because it transforms pre-set, or initialized, qubits back into their natural fluid state in order to leverage their full quantum powers."
},
{
"code": null,
"e": 11268,
"s": 10958,
"text": "There are a number of other quantum gates you’re bound to run into. Many of them operate on several qubits at a time, leading to 4x4 or even 8x8 matrices with complex-numbered elements. These are pretty hairy if you don’t already have some serious matrix skills under your belt. So I’ll spare you the details."
},
{
"code": null,
"e": 11367,
"s": 11268,
"text": "The main gates that you will want to be familiar are the ones we covered shown in the graph below:"
},
{
"code": null,
"e": 11525,
"s": 11367,
"text": "You should know that other gates exist so here’s a quick list of some of the most widely used other quantum gates, just so you can get a feel for the jargon:"
},
{
"code": null,
"e": 11550,
"s": 11525,
"text": "Toffoli gateFredkin gate"
},
{
"code": null,
"e": 11563,
"s": 11550,
"text": "Deutsch gate"
},
{
"code": null,
"e": 11601,
"s": 11563,
"text": "Swap gate (and swap-gate square root)"
},
{
"code": null,
"e": 11622,
"s": 11601,
"text": "NOT-gate square root"
},
{
"code": null,
"e": 11677,
"s": 11622,
"text": "Controlled-NOT gate (C-NOT) and other controlled gates"
},
{
"code": null,
"e": 11980,
"s": 11677,
"text": "There are many more. But don’t let the numbers fool you. Just as you can perform any classical computation with a combination of NOT + OR = NOR gates or AND + NOT= NAND gates, you can reduce the list of quantum gates to a simple set of universal quantum gates. But we’ll save that deed for another day."
},
{
"code": null,
"e": 13109,
"s": 11980,
"text": "As a recent Quanta Magazine article points out, the quantum computers of 2018 aren’t quite ready for prime time. Before they can step into the ring with classical computers with billions of times as many logic gates, they will need to face a few of their own demons. The most deadly is probably the demon of decoherence. Right now, quantum decoherence will destroy your quantum computation in just “a few microseconds.” However, the faster your quantum gates perform their operations, the more likely your quantum algorithm will beat the demon of decoherence to the finish line, and the longer the race will last. Alongside speed, another important factor is the sheer number of operations performed by quantum gates to complete a calculation. This is known as a computation’s depth. So another current quest is to deepen the quantum playing field. By this logic, as the rapidly evolving quantum computer gets faster, its calculations deeper, and the countdown-to-decoherence longer, the classical computer will eventually find itself facing a formidable challenger, if not successor, in the (quite possibly) not too far future."
},
{
"code": null,
"e": 13419,
"s": 13109,
"text": "If you liked this article I would be super excited if you hit the clap button :) or share with your curious friends. I’ve got much more like it over at my personal blog (jasonroell.com) or you can just subscribe to my medium profile and get all my articles sent to you as soon as I write them! (how awesome?!)"
}
] |
Exploratory Data Analysis (EDA) techniques for Kaggle competition beginners | by Nikita sharma | Towards Data Science | Exploratory Data Analysis (EDA) is an approach to analysing data sets to summarize their main characteristics, often with visual methods. Following are the different steps involved in EDA :
Data CollectionData CleaningData PreprocessingData Visualisation
Data Collection
Data Cleaning
Data Preprocessing
Data Visualisation
Data collection is the process of gathering information in an established systematic way that enables one to test hypothesis and evaluate outcomes easily.
After getting data we need to check the data-type of features.
There are following types of features :
numeric
categorical
ordinal
datetime
coordinates
In order to know the data types/features of data, we need to run following command:
train_data.dtypes
or
train_data.info()
Let’s have a look to the statistical summary about our dataset.
train_data.describe()
Data cleaning is the process of ensuring that your data is correct and useable by identifying any errors in the data, or missing data by correcting or deleting them. Refer to this link for data cleaning.
Once the data is clean we can go further for data preprocessing.
Data preprocessing is a data mining technique that involves transforming raw data into an understandable format. It includes normalisation and standardisation, transformation, feature extraction and selection, etc. The product of data preprocessing is the final training dataset.
Data visualisation is the graphical representation of information and data. It uses statistical graphics, plots, information graphics and other tools to communicate information clearly and efficiently.
Here we will focus on commonly used Seaborn visualisation. Seaborn is a Python data visualisation library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
Following are the common used seaborn visualisation :-
Scatter PlotBox PlotHistogramCat PlotViolin PlotPair PlotJoint plotHeat Map
Scatter Plot
Box Plot
Histogram
Cat Plot
Violin Plot
Pair Plot
Joint plot
Heat Map
# import seaborn library
import seaborn as sns
A scatter plot is a set of points plotted on a horizontal and vertical axes.
Scatter plot below shows the relationship between the passenger age and passenger fare based on pclass (Ticket class) from data taken from Titanic dataset
sns.scatterplot(x="Age", y="Fare", hue = 'Pclass', data=train_data)
Box plot is a simple way of representing statistical data on a plot in which a rectangle is drawn to represent the second and third quartiles, usually with a vertical line inside to indicate the median value. The lower and upper quartiles are shown as horizontal lines either side of the rectangle.
Box plot below shows how the passenger fare varies based on ticket class.
sns.boxplot(x="Pclass", y="Fare",data= train_data)
A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable
sns.distplot( train_data['Pclass'], kde=False)
Cat plot provides access to several axes-level functions that show the relationship between a numerical and one or more categorical variables using one of several visual representations. We can used different kind of plot to draw (corresponds to the name of a categorical plotting function)Options are: “point”, “bar”, “strip”, “swarm”, “box”, or “violin”. More details about Cat plot is here
Below we do a cat plot with bar kind
sns.catplot(x="Embarked", y="Survived", hue="Sex",col="Pclass", kind = 'bar',data=train_data, palette = "rainbow")
Let’s have a look on same cat plot with violin kind
sns.catplot(x="Embarked", y="Survived", hue="Sex",col="Pclass", kind = 'violin',data=train_data, palette = "rainbow")
A violin plot plays a similar role as a box and whisker plot. It shows the distribution of quantitative data across several levels of one (or more) categorical variables such that those distributions can be compared. More details about Violin plot is here
sns.violinplot(x='Sex', y='Survived',data=train_data)
Pair plot in seaborn only plots numerical columns although later we will use the categorical variables for coloring. More about pair plot is here.
sns.pairplot(train_data, hue="Sex")
Jointplot is seaborn library specific and can be used to quickly visualize and analyze the relationship between two variables and describe their individual distributions on the same plot.
More about Joint plot is here.
sns.jointplot(x="Age", y="Fare", data=train_data, color ='green')
Heat map is a representation of data in the form of a map or diagram in which data values are represented as colours.
sns.heatmap(train_data.corr(), fmt = ".2f")
That’s all for this post, hope it was helpful. Cheers!
Originally published at confusedcoders.com on November 25, 2018. | [
{
"code": null,
"e": 362,
"s": 172,
"text": "Exploratory Data Analysis (EDA) is an approach to analysing data sets to summarize their main characteristics, often with visual methods. Following are the different steps involved in EDA :"
},
{
"code": null,
"e": 427,
"s": 362,
"text": "Data CollectionData CleaningData PreprocessingData Visualisation"
},
{
"code": null,
"e": 443,
"s": 427,
"text": "Data Collection"
},
{
"code": null,
"e": 457,
"s": 443,
"text": "Data Cleaning"
},
{
"code": null,
"e": 476,
"s": 457,
"text": "Data Preprocessing"
},
{
"code": null,
"e": 495,
"s": 476,
"text": "Data Visualisation"
},
{
"code": null,
"e": 650,
"s": 495,
"text": "Data collection is the process of gathering information in an established systematic way that enables one to test hypothesis and evaluate outcomes easily."
},
{
"code": null,
"e": 713,
"s": 650,
"text": "After getting data we need to check the data-type of features."
},
{
"code": null,
"e": 753,
"s": 713,
"text": "There are following types of features :"
},
{
"code": null,
"e": 761,
"s": 753,
"text": "numeric"
},
{
"code": null,
"e": 773,
"s": 761,
"text": "categorical"
},
{
"code": null,
"e": 781,
"s": 773,
"text": "ordinal"
},
{
"code": null,
"e": 790,
"s": 781,
"text": "datetime"
},
{
"code": null,
"e": 802,
"s": 790,
"text": "coordinates"
},
{
"code": null,
"e": 886,
"s": 802,
"text": "In order to know the data types/features of data, we need to run following command:"
},
{
"code": null,
"e": 904,
"s": 886,
"text": "train_data.dtypes"
},
{
"code": null,
"e": 907,
"s": 904,
"text": "or"
},
{
"code": null,
"e": 925,
"s": 907,
"text": "train_data.info()"
},
{
"code": null,
"e": 989,
"s": 925,
"text": "Let’s have a look to the statistical summary about our dataset."
},
{
"code": null,
"e": 1011,
"s": 989,
"text": "train_data.describe()"
},
{
"code": null,
"e": 1215,
"s": 1011,
"text": "Data cleaning is the process of ensuring that your data is correct and useable by identifying any errors in the data, or missing data by correcting or deleting them. Refer to this link for data cleaning."
},
{
"code": null,
"e": 1280,
"s": 1215,
"text": "Once the data is clean we can go further for data preprocessing."
},
{
"code": null,
"e": 1560,
"s": 1280,
"text": "Data preprocessing is a data mining technique that involves transforming raw data into an understandable format. It includes normalisation and standardisation, transformation, feature extraction and selection, etc. The product of data preprocessing is the final training dataset."
},
{
"code": null,
"e": 1762,
"s": 1560,
"text": "Data visualisation is the graphical representation of information and data. It uses statistical graphics, plots, information graphics and other tools to communicate information clearly and efficiently."
},
{
"code": null,
"e": 1985,
"s": 1762,
"text": "Here we will focus on commonly used Seaborn visualisation. Seaborn is a Python data visualisation library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics."
},
{
"code": null,
"e": 2040,
"s": 1985,
"text": "Following are the common used seaborn visualisation :-"
},
{
"code": null,
"e": 2116,
"s": 2040,
"text": "Scatter PlotBox PlotHistogramCat PlotViolin PlotPair PlotJoint plotHeat Map"
},
{
"code": null,
"e": 2129,
"s": 2116,
"text": "Scatter Plot"
},
{
"code": null,
"e": 2138,
"s": 2129,
"text": "Box Plot"
},
{
"code": null,
"e": 2148,
"s": 2138,
"text": "Histogram"
},
{
"code": null,
"e": 2157,
"s": 2148,
"text": "Cat Plot"
},
{
"code": null,
"e": 2169,
"s": 2157,
"text": "Violin Plot"
},
{
"code": null,
"e": 2179,
"s": 2169,
"text": "Pair Plot"
},
{
"code": null,
"e": 2190,
"s": 2179,
"text": "Joint plot"
},
{
"code": null,
"e": 2199,
"s": 2190,
"text": "Heat Map"
},
{
"code": null,
"e": 2224,
"s": 2199,
"text": "# import seaborn library"
},
{
"code": null,
"e": 2246,
"s": 2224,
"text": "import seaborn as sns"
},
{
"code": null,
"e": 2323,
"s": 2246,
"text": "A scatter plot is a set of points plotted on a horizontal and vertical axes."
},
{
"code": null,
"e": 2478,
"s": 2323,
"text": "Scatter plot below shows the relationship between the passenger age and passenger fare based on pclass (Ticket class) from data taken from Titanic dataset"
},
{
"code": null,
"e": 2546,
"s": 2478,
"text": "sns.scatterplot(x=\"Age\", y=\"Fare\", hue = 'Pclass', data=train_data)"
},
{
"code": null,
"e": 2845,
"s": 2546,
"text": "Box plot is a simple way of representing statistical data on a plot in which a rectangle is drawn to represent the second and third quartiles, usually with a vertical line inside to indicate the median value. The lower and upper quartiles are shown as horizontal lines either side of the rectangle."
},
{
"code": null,
"e": 2919,
"s": 2845,
"text": "Box plot below shows how the passenger fare varies based on ticket class."
},
{
"code": null,
"e": 2970,
"s": 2919,
"text": "sns.boxplot(x=\"Pclass\", y=\"Fare\",data= train_data)"
},
{
"code": null,
"e": 3126,
"s": 2970,
"text": "A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable"
},
{
"code": null,
"e": 3173,
"s": 3126,
"text": "sns.distplot( train_data['Pclass'], kde=False)"
},
{
"code": null,
"e": 3566,
"s": 3173,
"text": "Cat plot provides access to several axes-level functions that show the relationship between a numerical and one or more categorical variables using one of several visual representations. We can used different kind of plot to draw (corresponds to the name of a categorical plotting function)Options are: “point”, “bar”, “strip”, “swarm”, “box”, or “violin”. More details about Cat plot is here"
},
{
"code": null,
"e": 3603,
"s": 3566,
"text": "Below we do a cat plot with bar kind"
},
{
"code": null,
"e": 3718,
"s": 3603,
"text": "sns.catplot(x=\"Embarked\", y=\"Survived\", hue=\"Sex\",col=\"Pclass\", kind = 'bar',data=train_data, palette = \"rainbow\")"
},
{
"code": null,
"e": 3770,
"s": 3718,
"text": "Let’s have a look on same cat plot with violin kind"
},
{
"code": null,
"e": 3888,
"s": 3770,
"text": "sns.catplot(x=\"Embarked\", y=\"Survived\", hue=\"Sex\",col=\"Pclass\", kind = 'violin',data=train_data, palette = \"rainbow\")"
},
{
"code": null,
"e": 4144,
"s": 3888,
"text": "A violin plot plays a similar role as a box and whisker plot. It shows the distribution of quantitative data across several levels of one (or more) categorical variables such that those distributions can be compared. More details about Violin plot is here"
},
{
"code": null,
"e": 4198,
"s": 4144,
"text": "sns.violinplot(x='Sex', y='Survived',data=train_data)"
},
{
"code": null,
"e": 4345,
"s": 4198,
"text": "Pair plot in seaborn only plots numerical columns although later we will use the categorical variables for coloring. More about pair plot is here."
},
{
"code": null,
"e": 4381,
"s": 4345,
"text": "sns.pairplot(train_data, hue=\"Sex\")"
},
{
"code": null,
"e": 4569,
"s": 4381,
"text": "Jointplot is seaborn library specific and can be used to quickly visualize and analyze the relationship between two variables and describe their individual distributions on the same plot."
},
{
"code": null,
"e": 4600,
"s": 4569,
"text": "More about Joint plot is here."
},
{
"code": null,
"e": 4666,
"s": 4600,
"text": "sns.jointplot(x=\"Age\", y=\"Fare\", data=train_data, color ='green')"
},
{
"code": null,
"e": 4784,
"s": 4666,
"text": "Heat map is a representation of data in the form of a map or diagram in which data values are represented as colours."
},
{
"code": null,
"e": 4828,
"s": 4784,
"text": "sns.heatmap(train_data.corr(), fmt = \".2f\")"
},
{
"code": null,
"e": 4883,
"s": 4828,
"text": "That’s all for this post, hope it was helpful. Cheers!"
}
] |
PyBrain - Training Datasets on Networks | So far, we have seen how to create a network and a dataset. To work with datasets and networks together, we have to do it with the help of trainers.
Below is a working example to see how to add a dataset to the network created, and later trained and tested using trainers.
from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure import TanhLayer
from pybrain.datasets import SupervisedDataSet
from pybrain.supervised.trainers import BackpropTrainer
# Create a network with two inputs, three hidden, and one output
nn = buildNetwork(2, 3, 1, bias=True, hiddenclass=TanhLayer)
# Create a dataset that matches network input and output sizes:
norgate = SupervisedDataSet(2, 1)
# Create a dataset to be used for testing.
nortrain = SupervisedDataSet(2, 1)
# Add input and target values to dataset
# Values for NOR truth table
norgate.addSample((0, 0), (1,))
norgate.addSample((0, 1), (0,))
norgate.addSample((1, 0), (0,))
norgate.addSample((1, 1), (0,))
# Add input and target values to dataset
# Values for NOR truth table
nortrain.addSample((0, 0), (1,))
nortrain.addSample((0, 1), (0,))
nortrain.addSample((1, 0), (0,))
nortrain.addSample((1, 1), (0,))
#Training the network with dataset norgate.
trainer = BackpropTrainer(nn, norgate)
# will run the loop 1000 times to train it.
for epoch in range(1000):
trainer.train()
trainer.testOnData(dataset=nortrain, verbose = True)
To test the network and dataset, we need BackpropTrainer. BackpropTrainer is a trainer that trains the parameters of a module according to a supervised dataset (potentially sequential) by backpropagating the errors (through time).
We have created 2 datasets of class - SupervisedDataSet. We are making use of NOR data model which is as follows −
The above data model is used to train the network.
norgate = SupervisedDataSet(2, 1)
# Add input and target values to dataset
# Values for NOR truth table
norgate.addSample((0, 0), (1,))
norgate.addSample((0, 1), (0,))
norgate.addSample((1, 0), (0,))
norgate.addSample((1, 1), (0,))
Following is the dataset used to test −
# Create a dataset to be used for testing.
nortrain = SupervisedDataSet(2, 1)
# Add input and target values to dataset
# Values for NOR truth table
norgate.addSample((0, 0), (1,))
norgate.addSample((0, 1), (0,))
norgate.addSample((1, 0), (0,))
norgate.addSample((1, 1), (0,))
The trainer is used as follows −
#Training the network with dataset norgate.
trainer = BackpropTrainer(nn, norgate)
# will run the loop 1000 times to train it.
for epoch in range(1000):
trainer.train()
To test on the dataset, we can use the below code −
trainer.testOnData(dataset=nortrain, verbose = True)
C:\pybrain\pybrain\src>python testnetwork.py
Testing on data:
('out: ', '[0.887 ]')
('correct:', '[1 ]')
error: 0.00637334
('out: ', '[0.149 ]')
('correct:', '[0 ]')
error: 0.01110338
('out: ', '[0.102 ]')
('correct:', '[0 ]')
error: 0.00522736
('out: ', '[-0.163]')
('correct:', '[0 ]')
error: 0.01328650
('All errors:', [0.006373344564625953, 0.01110338071737218, 0.005227359234093431
, 0.01328649974219942])
('Average error:', 0.008997646064572746)
('Max error:', 0.01328649974219942, 'Median error:', 0.01110338071737218)
If you check the output, the test data almost matches with the dataset we have provided and hence the error is 0.008.
Let us now change the test data and see an average error. We have changed the output as shown below −
Following is the dataset used to test −
# Create a dataset to be used for testing.
nortrain = SupervisedDataSet(2, 1)
# Add input and target values to dataset
# Values for NOR truth table
norgate.addSample((0, 0), (0,))
norgate.addSample((0, 1), (1,))
norgate.addSample((1, 0), (1,))
norgate.addSample((1, 1), (0,))
Let us now test it.
C:\pybrain\pybrain\src>python testnetwork.py
Testing on data:
('out: ', '[0.988 ]')
('correct:', '[0 ]')
error: 0.48842978
('out: ', '[0.027 ]')
('correct:', '[1 ]')
error: 0.47382097
('out: ', '[0.021 ]')
('correct:', '[1 ]')
error: 0.47876379
('out: ', '[-0.04 ]')
('correct:', '[0 ]')
error: 0.00079160
('All errors:', [0.4884297811030845, 0.47382096780393873, 0.47876378995939756, 0
.0007915982149002194])
('Average error:', 0.3604515342703303)
('Max error:', 0.4884297811030845, 'Median error:', 0.47876378995939756)
We are getting the error as 0.36, which shows that our test data is not completely matching with the network trained.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2257,
"s": 2108,
"text": "So far, we have seen how to create a network and a dataset. To work with datasets and networks together, we have to do it with the help of trainers."
},
{
"code": null,
"e": 2381,
"s": 2257,
"text": "Below is a working example to see how to add a dataset to the network created, and later trained and tested using trainers."
},
{
"code": null,
"e": 3504,
"s": 2381,
"text": "from pybrain.tools.shortcuts import buildNetwork\nfrom pybrain.structure import TanhLayer\nfrom pybrain.datasets import SupervisedDataSet\nfrom pybrain.supervised.trainers import BackpropTrainer\n\n# Create a network with two inputs, three hidden, and one output\nnn = buildNetwork(2, 3, 1, bias=True, hiddenclass=TanhLayer)\n\n# Create a dataset that matches network input and output sizes:\nnorgate = SupervisedDataSet(2, 1)\n\n# Create a dataset to be used for testing.\nnortrain = SupervisedDataSet(2, 1)\n\n# Add input and target values to dataset\n# Values for NOR truth table\nnorgate.addSample((0, 0), (1,))\nnorgate.addSample((0, 1), (0,))\nnorgate.addSample((1, 0), (0,))\nnorgate.addSample((1, 1), (0,))\n\n# Add input and target values to dataset\n# Values for NOR truth table\nnortrain.addSample((0, 0), (1,))\nnortrain.addSample((0, 1), (0,))\nnortrain.addSample((1, 0), (0,))\nnortrain.addSample((1, 1), (0,))\n\n#Training the network with dataset norgate.\ntrainer = BackpropTrainer(nn, norgate)\n\n# will run the loop 1000 times to train it.\nfor epoch in range(1000):\ntrainer.train()\ntrainer.testOnData(dataset=nortrain, verbose = True)"
},
{
"code": null,
"e": 3735,
"s": 3504,
"text": "To test the network and dataset, we need BackpropTrainer. BackpropTrainer is a trainer that trains the parameters of a module according to a supervised dataset (potentially sequential) by backpropagating the errors (through time)."
},
{
"code": null,
"e": 3850,
"s": 3735,
"text": "We have created 2 datasets of class - SupervisedDataSet. We are making use of NOR data model which is as follows −"
},
{
"code": null,
"e": 3901,
"s": 3850,
"text": "The above data model is used to train the network."
},
{
"code": null,
"e": 4133,
"s": 3901,
"text": "norgate = SupervisedDataSet(2, 1)\n# Add input and target values to dataset\n# Values for NOR truth table\nnorgate.addSample((0, 0), (1,))\nnorgate.addSample((0, 1), (0,))\nnorgate.addSample((1, 0), (0,))\nnorgate.addSample((1, 1), (0,))"
},
{
"code": null,
"e": 4173,
"s": 4133,
"text": "Following is the dataset used to test −"
},
{
"code": null,
"e": 4450,
"s": 4173,
"text": "# Create a dataset to be used for testing.\nnortrain = SupervisedDataSet(2, 1)\n\n# Add input and target values to dataset\n# Values for NOR truth table\nnorgate.addSample((0, 0), (1,))\nnorgate.addSample((0, 1), (0,))\nnorgate.addSample((1, 0), (0,))\nnorgate.addSample((1, 1), (0,))"
},
{
"code": null,
"e": 4483,
"s": 4450,
"text": "The trainer is used as follows −"
},
{
"code": null,
"e": 4656,
"s": 4483,
"text": "#Training the network with dataset norgate.\ntrainer = BackpropTrainer(nn, norgate)\n\n# will run the loop 1000 times to train it.\nfor epoch in range(1000):\n trainer.train()"
},
{
"code": null,
"e": 4708,
"s": 4656,
"text": "To test on the dataset, we can use the below code −"
},
{
"code": null,
"e": 4762,
"s": 4708,
"text": "trainer.testOnData(dataset=nortrain, verbose = True)\n"
},
{
"code": null,
"e": 5289,
"s": 4762,
"text": "C:\\pybrain\\pybrain\\src>python testnetwork.py\nTesting on data:\n('out: ', '[0.887 ]')\n('correct:', '[1 ]')\nerror: 0.00637334\n('out: ', '[0.149 ]')\n('correct:', '[0 ]')\nerror: 0.01110338\n('out: ', '[0.102 ]')\n('correct:', '[0 ]')\nerror: 0.00522736\n('out: ', '[-0.163]')\n('correct:', '[0 ]')\nerror: 0.01328650\n('All errors:', [0.006373344564625953, 0.01110338071737218, 0.005227359234093431\n, 0.01328649974219942])\n('Average error:', 0.008997646064572746)\n('Max error:', 0.01328649974219942, 'Median error:', 0.01110338071737218)\n"
},
{
"code": null,
"e": 5407,
"s": 5289,
"text": "If you check the output, the test data almost matches with the dataset we have provided and hence the error is 0.008."
},
{
"code": null,
"e": 5509,
"s": 5407,
"text": "Let us now change the test data and see an average error. We have changed the output as shown below −"
},
{
"code": null,
"e": 5549,
"s": 5509,
"text": "Following is the dataset used to test −"
},
{
"code": null,
"e": 5826,
"s": 5549,
"text": "# Create a dataset to be used for testing.\nnortrain = SupervisedDataSet(2, 1)\n\n# Add input and target values to dataset\n# Values for NOR truth table\nnorgate.addSample((0, 0), (0,))\nnorgate.addSample((0, 1), (1,))\nnorgate.addSample((1, 0), (1,))\nnorgate.addSample((1, 1), (0,))"
},
{
"code": null,
"e": 5846,
"s": 5826,
"text": "Let us now test it."
},
{
"code": null,
"e": 6369,
"s": 5846,
"text": "C:\\pybrain\\pybrain\\src>python testnetwork.py\nTesting on data:\n('out: ', '[0.988 ]')\n('correct:', '[0 ]')\nerror: 0.48842978\n('out: ', '[0.027 ]')\n('correct:', '[1 ]')\nerror: 0.47382097\n('out: ', '[0.021 ]')\n('correct:', '[1 ]')\nerror: 0.47876379\n('out: ', '[-0.04 ]')\n('correct:', '[0 ]')\nerror: 0.00079160\n('All errors:', [0.4884297811030845, 0.47382096780393873, 0.47876378995939756, 0\n.0007915982149002194])\n('Average error:', 0.3604515342703303)\n('Max error:', 0.4884297811030845, 'Median error:', 0.47876378995939756)\n"
},
{
"code": null,
"e": 6487,
"s": 6369,
"text": "We are getting the error as 0.36, which shows that our test data is not completely matching with the network trained."
},
{
"code": null,
"e": 6494,
"s": 6487,
"text": " Print"
},
{
"code": null,
"e": 6505,
"s": 6494,
"text": " Add Notes"
}
] |
What are the rules for calling the superclass constructor C++? | In C++, we can derive some classes. Sometimes we need to call the super class (Base class) constructor when calling the constructor of the derived class. Unlike Java there is no reference variable for super class. If the constructor is non-parameterized, then it will be called automatically with the derived class, otherwise we have to put the super class constructor in the initializer list of the derived class.
In this example at first we will see constructor with no argument.
Live Demo
#include <iostream>
using namespace std;
class MyBaseClass {
public:
MyBaseClass() {
cout << "Constructor of base class" << endl;
}
};
class MyDerivedClass : public MyBaseClass {
public:
MyDerivedClass() {
cout << "Constructor of derived class" << endl;
}
};
int main() {
MyDerivedClass derived;
}
Constructor of base class
Constructor of derived class
Now let us see constructor which can take parameter.
Live Demo
#include <iostream>
using namespace std;
class MyBaseClass {
public:
MyBaseClass(int x) {
cout << "Constructor of base class: " << x << endl;
}
};
class MyDerivedClass : public MyBaseClass { //base constructor as initializer list
public:
MyDerivedClass(int y) : MyBaseClass(50) {
cout << "Constructor of derived class: " << y << endl;
}
};
int main() {
MyDerivedClass derived(100);
}
Constructor of base class: 50
Constructor of derived class: 100 | [
{
"code": null,
"e": 1477,
"s": 1062,
"text": "In C++, we can derive some classes. Sometimes we need to call the super class (Base class) constructor when calling the constructor of the derived class. Unlike Java there is no reference variable for super class. If the constructor is non-parameterized, then it will be called automatically with the derived class, otherwise we have to put the super class constructor in the initializer list of the derived class."
},
{
"code": null,
"e": 1544,
"s": 1477,
"text": "In this example at first we will see constructor with no argument."
},
{
"code": null,
"e": 1555,
"s": 1544,
"text": " Live Demo"
},
{
"code": null,
"e": 1904,
"s": 1555,
"text": "#include <iostream>\nusing namespace std;\nclass MyBaseClass {\n public:\n MyBaseClass() {\n cout << \"Constructor of base class\" << endl;\n }\n};\nclass MyDerivedClass : public MyBaseClass {\n public:\n MyDerivedClass() {\n cout << \"Constructor of derived class\" << endl;\n }\n};\nint main() {\n MyDerivedClass derived;\n}"
},
{
"code": null,
"e": 1959,
"s": 1904,
"text": "Constructor of base class\nConstructor of derived class"
},
{
"code": null,
"e": 2012,
"s": 1959,
"text": "Now let us see constructor which can take parameter."
},
{
"code": null,
"e": 2023,
"s": 2012,
"text": " Live Demo"
},
{
"code": null,
"e": 2449,
"s": 2023,
"text": "#include <iostream>\nusing namespace std;\nclass MyBaseClass {\n public:\n MyBaseClass(int x) {\n cout << \"Constructor of base class: \" << x << endl;\n }\n};\nclass MyDerivedClass : public MyBaseClass { //base constructor as initializer list\n public:\n MyDerivedClass(int y) : MyBaseClass(50) {\n cout << \"Constructor of derived class: \" << y << endl;\n }\n};\nint main() {\n MyDerivedClass derived(100);\n}"
},
{
"code": null,
"e": 2513,
"s": 2449,
"text": "Constructor of base class: 50\nConstructor of derived class: 100"
}
] |
list::begin() and list::end() in C++ STL - GeeksforGeeks | 07 Dec, 2021
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.
begin() function is used to return an iterator pointing to the first element of the list container. It is different from the front() function because the front function returns a reference to the first element of the container but begin() function returns a bidirectional iterator to the first element of the container.Syntax :
listname.begin()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the first element.
Examples:
Input : mylist{1, 2, 3, 4, 5};
mylist.begin();
Output : returns an iterator to the element 1
Input : mylist{8, 7};
mylist.begin();
Output : returns an iterator to the element 8
Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed.
CPP
// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <list>using namespace std; int main(){ // declaration of list container list<int> mylist{ 1, 2, 3, 4, 5 }; // using begin() to print list for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; return 0;}
Output:
1 2 3 4 5
Time Complexity: O(1)
end() function is used to return an iterator pointing to the last element of the list container. It is different from the back() function because the back() function returns a reference to the last element of the container but end() function returns a bidirectional iterator to the past last element of the container.Syntax :
listname.end()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the past last element.
Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed.
CPP
// CPP program to illustrate// Implementation of end() function#include <iostream>#include <list>using namespace std; int main(){ // declaration of list container list<int> mylist{ 1, 2, 3, 4, 5 }; // using end() to print list for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; return 0;}
Output:
1 2 3 4 5
Time Complexity: O(1)
adityapal754
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Constructors in C++
C++ Classes and Objects
Socket Programming in C/C++
Bitwise Operators in C/C++
Operator Overloading in C++
Copy Constructor in C++
Virtual Function in C++
Templates in C++ with Examples
rand() and srand() in C/C++ | [
{
"code": null,
"e": 24102,
"s": 24074,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 24353,
"s": 24102,
"text": "Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists."
},
{
"code": null,
"e": 24682,
"s": 24353,
"text": "begin() function is used to return an iterator pointing to the first element of the list container. It is different from the front() function because the front function returns a reference to the first element of the container but begin() function returns a bidirectional iterator to the first element of the container.Syntax : "
},
{
"code": null,
"e": 24827,
"s": 24682,
"text": "listname.begin()\nParameters :\nNo parameters are passed.\nReturns :\nThis function returns a bidirectional\niterator pointing to the first element.\n"
},
{
"code": null,
"e": 24839,
"s": 24827,
"text": "Examples: "
},
{
"code": null,
"e": 25038,
"s": 24839,
"text": "Input : mylist{1, 2, 3, 4, 5};\n mylist.begin();\nOutput : returns an iterator to the element 1\n\nInput : mylist{8, 7};\n mylist.begin();\nOutput : returns an iterator to the element 8\n"
},
{
"code": null,
"e": 25145,
"s": 25038,
"text": "Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. "
},
{
"code": null,
"e": 25149,
"s": 25145,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <list>using namespace std; int main(){ // declaration of list container list<int> mylist{ 1, 2, 3, 4, 5 }; // using begin() to print list for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; return 0;}",
"e": 25521,
"s": 25149,
"text": null
},
{
"code": null,
"e": 25530,
"s": 25521,
"text": "Output: "
},
{
"code": null,
"e": 25541,
"s": 25530,
"text": "1 2 3 4 5\n"
},
{
"code": null,
"e": 25564,
"s": 25541,
"text": "Time Complexity: O(1) "
},
{
"code": null,
"e": 25891,
"s": 25564,
"text": "end() function is used to return an iterator pointing to the last element of the list container. It is different from the back() function because the back() function returns a reference to the last element of the container but end() function returns a bidirectional iterator to the past last element of the container.Syntax : "
},
{
"code": null,
"e": 26038,
"s": 25891,
"text": "listname.end()\nParameters :\nNo parameters are passed.\nReturns :\nThis function returns a bidirectional\niterator pointing to the past last element.\n"
},
{
"code": null,
"e": 26145,
"s": 26038,
"text": "Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. "
},
{
"code": null,
"e": 26149,
"s": 26145,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of end() function#include <iostream>#include <list>using namespace std; int main(){ // declaration of list container list<int> mylist{ 1, 2, 3, 4, 5 }; // using end() to print list for (auto it = mylist.begin(); it != mylist.end(); ++it) cout << ' ' << *it; return 0;}",
"e": 26520,
"s": 26149,
"text": null
},
{
"code": null,
"e": 26529,
"s": 26520,
"text": "Output: "
},
{
"code": null,
"e": 26540,
"s": 26529,
"text": "1 2 3 4 5\n"
},
{
"code": null,
"e": 26563,
"s": 26540,
"text": "Time Complexity: O(1) "
},
{
"code": null,
"e": 26576,
"s": 26563,
"text": "adityapal754"
},
{
"code": null,
"e": 26585,
"s": 26576,
"text": "cpp-list"
},
{
"code": null,
"e": 26589,
"s": 26585,
"text": "STL"
},
{
"code": null,
"e": 26593,
"s": 26589,
"text": "C++"
},
{
"code": null,
"e": 26597,
"s": 26593,
"text": "STL"
},
{
"code": null,
"e": 26601,
"s": 26597,
"text": "CPP"
},
{
"code": null,
"e": 26699,
"s": 26601,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26708,
"s": 26699,
"text": "Comments"
},
{
"code": null,
"e": 26721,
"s": 26708,
"text": "Old Comments"
},
{
"code": null,
"e": 26740,
"s": 26721,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26760,
"s": 26740,
"text": "Constructors in C++"
},
{
"code": null,
"e": 26784,
"s": 26760,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26812,
"s": 26784,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26839,
"s": 26812,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 26867,
"s": 26839,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26891,
"s": 26867,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 26915,
"s": 26891,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 26946,
"s": 26915,
"text": "Templates in C++ with Examples"
}
] |
Map numbers to characters in JavaScript | Suppose we have the number 12145. We are required to write a function that maps the digits of
the number to English alphabets according to the following norms. The alphabets are to be mapped according to the 1 based index, like 'a' for 1 and 'b' for 2 'c' for 3 and so on.
There can be several ways for mapping a number. Let's take the above number 121415 for
example,
It can be mapped as −
12145->1,2,1,4,5->a,b,a,d,e
It also can be −
12145->12,1,4,5->l,a,d,e
It can also be −
12145->12,14,5->l,n,e
and so on, but 12145 can't be 1,2,1,45 because there’s is no mapping for 45 in the alphabets.
So, our function should return an array of all the permutations of the alphabet mappings.
The code for this will be −
const num = 12145;
const mapToAlphabets = num => {
const numStr = '' + num;
let res = [];
const shoveElements = (left, right) => {
if (!left.length) {
res.push(right.map(el => {
return (+el + 9).toString(36);
}).join(''));
return;
};
if(+left[0] > 0){
shoveElements(left.slice(1), right.concat(left[0]));
};
if(left.length >= 2 && +(left.slice(0, 2)) <= 26){
shoveElements(left.slice(2), right.concat(left.slice(0, 2)));
};
};
shoveElements(numStr, []);
return res;
}
console.log(mapToAlphabets(num));
The output in the console −
[ 'abade', 'abne', 'aude', 'lade', 'lne' ] | [
{
"code": null,
"e": 1335,
"s": 1062,
"text": "Suppose we have the number 12145. We are required to write a function that maps the digits of\nthe number to English alphabets according to the following norms. The alphabets are to be mapped according to the 1 based index, like 'a' for 1 and 'b' for 2 'c' for 3 and so on."
},
{
"code": null,
"e": 1431,
"s": 1335,
"text": "There can be several ways for mapping a number. Let's take the above number 121415 for\nexample,"
},
{
"code": null,
"e": 1453,
"s": 1431,
"text": "It can be mapped as −"
},
{
"code": null,
"e": 1481,
"s": 1453,
"text": "12145->1,2,1,4,5->a,b,a,d,e"
},
{
"code": null,
"e": 1498,
"s": 1481,
"text": "It also can be −"
},
{
"code": null,
"e": 1523,
"s": 1498,
"text": "12145->12,1,4,5->l,a,d,e"
},
{
"code": null,
"e": 1540,
"s": 1523,
"text": "It can also be −"
},
{
"code": null,
"e": 1562,
"s": 1540,
"text": "12145->12,14,5->l,n,e"
},
{
"code": null,
"e": 1746,
"s": 1562,
"text": "and so on, but 12145 can't be 1,2,1,45 because there’s is no mapping for 45 in the alphabets.\nSo, our function should return an array of all the permutations of the alphabet mappings."
},
{
"code": null,
"e": 1774,
"s": 1746,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2387,
"s": 1774,
"text": "const num = 12145;\nconst mapToAlphabets = num => {\n const numStr = '' + num;\n let res = [];\n const shoveElements = (left, right) => {\n if (!left.length) {\n res.push(right.map(el => {\n return (+el + 9).toString(36);\n }).join(''));\n return;\n };\n if(+left[0] > 0){\n shoveElements(left.slice(1), right.concat(left[0]));\n };\n if(left.length >= 2 && +(left.slice(0, 2)) <= 26){\n shoveElements(left.slice(2), right.concat(left.slice(0, 2)));\n };\n };\n shoveElements(numStr, []);\n return res;\n}\nconsole.log(mapToAlphabets(num));"
},
{
"code": null,
"e": 2415,
"s": 2387,
"text": "The output in the console −"
},
{
"code": null,
"e": 2458,
"s": 2415,
"text": "[ 'abade', 'abne', 'aude', 'lade', 'lne' ]"
}
] |
Implementation of Contiguous Memory Management Techniques - GeeksforGeeks | 13 Apr, 2020
Memory Management Techniques are basic techniques that are used in managing the memory in operating system. Memory Management Techniques are basically classified into two categories:
(i) Contiguous
(ii) Non-contiguous
Contiguous Memory Management Techniques:In this technique, memory is allotted in a continuous way to the processes. It has two types:
Fixed Partition Scheme:In the fixed partition scheme, memory is divided into fixed number of partitions. Fixed means number of partitions are fixed in the memory. In the fixed partition, in every partition only one process will be accommodated. Degree of multi-programming is restricted by number of partitions in the memory. Maximum size of the process is restricted by maximum size of the partition. Every partition is associated with the limit registers.
Limit Registers: It has two limit:
Lower Limit: Starting address of the partition.
Upper Limit: Ending address of the partition.
Internal Fragmentation is found in fixed partition scheme.To overcome the problem of internal fragmentation, instead of fixed partition scheme, variable partition scheme is used.
Variable Partition Scheme:In the variable partition scheme, initially memory will be single continuous free block. Whenever the request by the process arrives, accordingly partition will be made in the memory. If the smaller processes keep on coming then the larger partitions will be made into smaller partitions.
External Fragmentation is found in variable partition scheme.To overcome the problem of external fragmentation, compaction technique is used or non-contiguous memory management techniques are used.
Compaction:Moving all the processes toward the top or towards the bottom to make free available memory in a single continuous place is called as compaction. Compaction is undesirable to implement because it interrupts all the running processes in the memory.
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Normal Forms in DBMS
LRU Cache Implementation
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Inter Process Communication (IPC)
Banker's Algorithm in Operating System
Program for FCFS CPU Scheduling | Set 1
Program for Round Robin scheduling | Set 1
LRU Cache Implementation
Introduction of Deadlock in Operating System | [
{
"code": null,
"e": 23904,
"s": 23876,
"text": "\n13 Apr, 2020"
},
{
"code": null,
"e": 24087,
"s": 23904,
"text": "Memory Management Techniques are basic techniques that are used in managing the memory in operating system. Memory Management Techniques are basically classified into two categories:"
},
{
"code": null,
"e": 24123,
"s": 24087,
"text": "(i) Contiguous\n(ii) Non-contiguous "
},
{
"code": null,
"e": 24257,
"s": 24123,
"text": "Contiguous Memory Management Techniques:In this technique, memory is allotted in a continuous way to the processes. It has two types:"
},
{
"code": null,
"e": 24715,
"s": 24257,
"text": "Fixed Partition Scheme:In the fixed partition scheme, memory is divided into fixed number of partitions. Fixed means number of partitions are fixed in the memory. In the fixed partition, in every partition only one process will be accommodated. Degree of multi-programming is restricted by number of partitions in the memory. Maximum size of the process is restricted by maximum size of the partition. Every partition is associated with the limit registers."
},
{
"code": null,
"e": 24750,
"s": 24715,
"text": "Limit Registers: It has two limit:"
},
{
"code": null,
"e": 24798,
"s": 24750,
"text": "Lower Limit: Starting address of the partition."
},
{
"code": null,
"e": 24844,
"s": 24798,
"text": "Upper Limit: Ending address of the partition."
},
{
"code": null,
"e": 25023,
"s": 24844,
"text": "Internal Fragmentation is found in fixed partition scheme.To overcome the problem of internal fragmentation, instead of fixed partition scheme, variable partition scheme is used."
},
{
"code": null,
"e": 25338,
"s": 25023,
"text": "Variable Partition Scheme:In the variable partition scheme, initially memory will be single continuous free block. Whenever the request by the process arrives, accordingly partition will be made in the memory. If the smaller processes keep on coming then the larger partitions will be made into smaller partitions."
},
{
"code": null,
"e": 25536,
"s": 25338,
"text": "External Fragmentation is found in variable partition scheme.To overcome the problem of external fragmentation, compaction technique is used or non-contiguous memory management techniques are used."
},
{
"code": null,
"e": 25795,
"s": 25536,
"text": "Compaction:Moving all the processes toward the top or towards the bottom to make free available memory in a single continuous place is called as compaction. Compaction is undesirable to implement because it interrupts all the running processes in the memory."
},
{
"code": null,
"e": 25803,
"s": 25795,
"text": "GATE CS"
},
{
"code": null,
"e": 25821,
"s": 25803,
"text": "Operating Systems"
},
{
"code": null,
"e": 25839,
"s": 25821,
"text": "Operating Systems"
},
{
"code": null,
"e": 25937,
"s": 25839,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25946,
"s": 25937,
"text": "Comments"
},
{
"code": null,
"e": 25959,
"s": 25946,
"text": "Old Comments"
},
{
"code": null,
"e": 25980,
"s": 25959,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 26005,
"s": 25980,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 26037,
"s": 26005,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 26076,
"s": 26037,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 26110,
"s": 26076,
"text": "Inter Process Communication (IPC)"
},
{
"code": null,
"e": 26149,
"s": 26110,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 26189,
"s": 26149,
"text": "Program for FCFS CPU Scheduling | Set 1"
},
{
"code": null,
"e": 26232,
"s": 26189,
"text": "Program for Round Robin scheduling | Set 1"
},
{
"code": null,
"e": 26257,
"s": 26232,
"text": "LRU Cache Implementation"
}
] |
Python – Adjacent elements in List | When it is required to display adjacent elements in list, a method is defined that uses enumerate and a simple iteration to determine the result.
Below is a demonstration of the same −
def find_adjacent_elements(my_list):
my_result = []
for index, ele in enumerate(my_list):
if index == 0:
my_result.append((None, my_list[index + 1]))
elif index == len(my_list) - 1:
my_result.append((my_list[index - 1], None))
else:
my_result.append((my_list[index - 1], my_list[index + 1]))
return my_result
my_list = [13, 37, 58, 12, 41, 25, 48, 19, 23]
print("The list is:")
print(my_list)
print("The result is :")
print(find_adjacent_elements(my_list))
The list is:
[13, 37, 58, 12, 41, 25, 48, 19, 23]
The result is :
[(None, 37), (13, 58), (37, 12), (58, 41), (12, 25), (41, 48), (25, 19), (48, 23), (19, None)]
A method named ‘find_adjacent_elements’ is defined that takes a list as a parameter, and does enumerates over the list.
A method named ‘find_adjacent_elements’ is defined that takes a list as a parameter, and does enumerates over the list.
An empty list is created.
An empty list is created.
The elements are iterated over using ‘enumerate’ and depending on the value of the index, the output is determined.
The elements are iterated over using ‘enumerate’ and depending on the value of the index, the output is determined.
If index value is 0, the element in first index is appended to the empty list.
If index value is 0, the element in first index is appended to the empty list.
If index is equal to length of list minus 1, the element in previous index is appended to empty list.
If index is equal to length of list minus 1, the element in previous index is appended to empty list.
Otherwise, both the previous and next elements are appended to the empty list.
Otherwise, both the previous and next elements are appended to the empty list.
Outside the method, a list is defined and displayed on the console.
Outside the method, a list is defined and displayed on the console.
The method is called by passing the required parameter.
The method is called by passing the required parameter.
The output is displayed on the console.
The output is displayed on the console. | [
{
"code": null,
"e": 1208,
"s": 1062,
"text": "When it is required to display adjacent elements in list, a method is defined that uses enumerate and a simple iteration to determine the result."
},
{
"code": null,
"e": 1247,
"s": 1208,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1761,
"s": 1247,
"text": "def find_adjacent_elements(my_list):\n my_result = []\n for index, ele in enumerate(my_list):\n if index == 0:\n my_result.append((None, my_list[index + 1]))\n elif index == len(my_list) - 1:\n my_result.append((my_list[index - 1], None))\n else:\n my_result.append((my_list[index - 1], my_list[index + 1]))\n return my_result\n\nmy_list = [13, 37, 58, 12, 41, 25, 48, 19, 23]\n\nprint(\"The list is:\")\nprint(my_list)\n\nprint(\"The result is :\")\nprint(find_adjacent_elements(my_list))"
},
{
"code": null,
"e": 1922,
"s": 1761,
"text": "The list is:\n[13, 37, 58, 12, 41, 25, 48, 19, 23]\nThe result is :\n[(None, 37), (13, 58), (37, 12), (58, 41), (12, 25), (41, 48), (25, 19), (48, 23), (19, None)]"
},
{
"code": null,
"e": 2042,
"s": 1922,
"text": "A method named ‘find_adjacent_elements’ is defined that takes a list as a parameter, and does enumerates over the list."
},
{
"code": null,
"e": 2162,
"s": 2042,
"text": "A method named ‘find_adjacent_elements’ is defined that takes a list as a parameter, and does enumerates over the list."
},
{
"code": null,
"e": 2188,
"s": 2162,
"text": "An empty list is created."
},
{
"code": null,
"e": 2214,
"s": 2188,
"text": "An empty list is created."
},
{
"code": null,
"e": 2330,
"s": 2214,
"text": "The elements are iterated over using ‘enumerate’ and depending on the value of the index, the output is determined."
},
{
"code": null,
"e": 2446,
"s": 2330,
"text": "The elements are iterated over using ‘enumerate’ and depending on the value of the index, the output is determined."
},
{
"code": null,
"e": 2525,
"s": 2446,
"text": "If index value is 0, the element in first index is appended to the empty list."
},
{
"code": null,
"e": 2604,
"s": 2525,
"text": "If index value is 0, the element in first index is appended to the empty list."
},
{
"code": null,
"e": 2706,
"s": 2604,
"text": "If index is equal to length of list minus 1, the element in previous index is appended to empty list."
},
{
"code": null,
"e": 2808,
"s": 2706,
"text": "If index is equal to length of list minus 1, the element in previous index is appended to empty list."
},
{
"code": null,
"e": 2887,
"s": 2808,
"text": "Otherwise, both the previous and next elements are appended to the empty list."
},
{
"code": null,
"e": 2966,
"s": 2887,
"text": "Otherwise, both the previous and next elements are appended to the empty list."
},
{
"code": null,
"e": 3034,
"s": 2966,
"text": "Outside the method, a list is defined and displayed on the console."
},
{
"code": null,
"e": 3102,
"s": 3034,
"text": "Outside the method, a list is defined and displayed on the console."
},
{
"code": null,
"e": 3158,
"s": 3102,
"text": "The method is called by passing the required parameter."
},
{
"code": null,
"e": 3214,
"s": 3158,
"text": "The method is called by passing the required parameter."
},
{
"code": null,
"e": 3254,
"s": 3214,
"text": "The output is displayed on the console."
},
{
"code": null,
"e": 3294,
"s": 3254,
"text": "The output is displayed on the console."
}
] |
Find the percentage of a student on basis of marks and add percent sign (%) to the result in SQL | Let us first create a table −
mysql> create table DemoTable
(
Marks int
);
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(65);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(67);
Query OK, 1 row affected (0.33 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Marks |
+-------+
| 88 |
| 65 |
| 98 |
| 45 |
| 67 |
+-------+
5 rows in set (0.00 sec)
Following is the query to calculate percentage of the student in the basis of marks in 5 subjects. The result would be in percentage; therefore, we will also add percent sign (%) to the calculation −
mysql> select concat(round(SUM(Marks)*100/500),'%') from DemoTable;
This will produce the following output −
+---------------------------------------+
| concat(round(SUM(Marks)*100/500),'%') |
+---------------------------------------+
| 73% |
+---------------------------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1177,
"s": 1092,
"text": "mysql> create table DemoTable\n(\n Marks int\n);\nQuery OK, 0 rows affected (0.62 sec)"
},
{
"code": null,
"e": 1233,
"s": 1177,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1618,
"s": 1233,
"text": "mysql> insert into DemoTable values(88);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values(65);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values(98);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values(45);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(67);\nQuery OK, 1 row affected (0.33 sec)"
},
{
"code": null,
"e": 1678,
"s": 1618,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1709,
"s": 1678,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1750,
"s": 1709,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1865,
"s": 1750,
"text": "+-------+\n| Marks |\n+-------+\n| 88 |\n| 65 |\n| 98 |\n| 45 |\n| 67 |\n+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2065,
"s": 1865,
"text": "Following is the query to calculate percentage of the student in the basis of marks in 5 subjects. The result would be in percentage; therefore, we will also add percent sign (%) to the calculation −"
},
{
"code": null,
"e": 2133,
"s": 2065,
"text": "mysql> select concat(round(SUM(Marks)*100/500),'%') from DemoTable;"
},
{
"code": null,
"e": 2174,
"s": 2133,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2408,
"s": 2174,
"text": "+---------------------------------------+\n| concat(round(SUM(Marks)*100/500),'%') |\n+---------------------------------------+\n| 73% |\n+---------------------------------------+\n1 row in set (0.00 sec)"
}
] |
How to count unique values in a Pandas Groupby object? - GeeksforGeeks | 15 Mar, 2021
Prerequisites: Pandas
Groupby as the name suggests groups attributes on the basis of similarity in some value. We can count the unique values in pandas Groupby object using groupby(), agg(), and reset_index() method. This article depicts how the count of unique values of some attribute in a data frame can be retrieved using pandas.
groupby() – groupby() function is used to split the data into groups based on some criteria. pandas objects can be split on any of their axes.
Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)
Parameters :
by : mapping, function, str, or iterable
axis : int, default 0
level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels
as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output
sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group.
group_keys : When calling apply, add group keys to index to identify pieces
squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent type
Returns : GroupBy object
agg() – agg() is used to pass a function or list of functions to be applied on a series or even each element of series separately. In the case of the list of functions, multiple results are returned by agg() method.
Syntax: DataFrame.aggregate(func, axis=0, *args, **kwargs)
Parameters:
func : callable, string, dictionary, or list of string/callables. Function to use for aggregating the data. If a function, must either work when passed a DataFrame or when passed to DataFrame.apply. For a DataFrame, can pass a dict, if the keys are DataFrame column names.
axis : (default 0) {0 or ‘index’, 1 or ‘columns’} 0 or ‘index’: apply function to each column. 1 or ‘columns’: apply function to each row.
Returns: Aggregated DataFrame
reset-index() – Pandas reset_index() is a method to reset index of a Data Frame. reset_index() method sets a list of integers ranging from 0 to length of data as index.
Syntax: DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=”)
Parameters:
level: int, string or a list to select and remove passed column from index.
drop: Boolean value, Adds the replaced index column to the data if False.
inplace: Boolean value, make changes in the original data frame itself if True.
col_level: Select in which column level to insert the labels.
col_fill: Object, to determine how the other levels are named.
Return type: DataFrame
Approach:
Import libraries
Make data
Group Data
Use aggregate function
Reset Index
Print Data
Example 1:
Python
# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({'Col_1': ['a', 'b', 'c', 'b', 'a', 'd'], 'Col_2': [1, 2, 3, 3, 2, 1]}) # print original dataframeprint("original dataframe:")display(df) # call groupby method.df = df.groupby("Col_1") # call agg methoddf = df.agg({"Col_2": "nunique"}) # call reset_index methoddf = df.reset_index() # print dataframeprint("final dataframe:")display(df)
Output:
Example 2:
Python
# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({'Col_1': ['a', 'b', 'c', 'b', 'a', 'd'], 'Col_2': [1, 2, 3, 3, 2, 1]}) # print original dataframeprint("original dataframe:")display(df) # call groupby method.df = df.groupby("Col_2") # call agg methoddf = df.agg({"Col_1": "nunique"}) # call reset_index methoddf = df.reset_index() # print dataframeprint("final data frame:")display(df)
Output:
Picked
Python Pandas-exercise
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | 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": 24292,
"s": 24264,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 24314,
"s": 24292,
"text": "Prerequisites: Pandas"
},
{
"code": null,
"e": 24627,
"s": 24314,
"text": "Groupby as the name suggests groups attributes on the basis of similarity in some value. We can count the unique values in pandas Groupby object using groupby(), agg(), and reset_index() method. This article depicts how the count of unique values of some attribute in a data frame can be retrieved using pandas. "
},
{
"code": null,
"e": 24770,
"s": 24627,
"text": "groupby() – groupby() function is used to split the data into groups based on some criteria. pandas objects can be split on any of their axes."
},
{
"code": null,
"e": 24893,
"s": 24770,
"text": "Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)"
},
{
"code": null,
"e": 24906,
"s": 24893,
"text": "Parameters :"
},
{
"code": null,
"e": 24947,
"s": 24906,
"text": "by : mapping, function, str, or iterable"
},
{
"code": null,
"e": 24969,
"s": 24947,
"text": "axis : int, default 0"
},
{
"code": null,
"e": 25059,
"s": 24969,
"text": "level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels"
},
{
"code": null,
"e": 25231,
"s": 25059,
"text": "as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output"
},
{
"code": null,
"e": 25428,
"s": 25231,
"text": "sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group."
},
{
"code": null,
"e": 25504,
"s": 25428,
"text": "group_keys : When calling apply, add group keys to index to identify pieces"
},
{
"code": null,
"e": 25607,
"s": 25504,
"text": "squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent type"
},
{
"code": null,
"e": 25632,
"s": 25607,
"text": "Returns : GroupBy object"
},
{
"code": null,
"e": 25848,
"s": 25632,
"text": "agg() – agg() is used to pass a function or list of functions to be applied on a series or even each element of series separately. In the case of the list of functions, multiple results are returned by agg() method."
},
{
"code": null,
"e": 25907,
"s": 25848,
"text": "Syntax: DataFrame.aggregate(func, axis=0, *args, **kwargs)"
},
{
"code": null,
"e": 25919,
"s": 25907,
"text": "Parameters:"
},
{
"code": null,
"e": 26192,
"s": 25919,
"text": "func : callable, string, dictionary, or list of string/callables. Function to use for aggregating the data. If a function, must either work when passed a DataFrame or when passed to DataFrame.apply. For a DataFrame, can pass a dict, if the keys are DataFrame column names."
},
{
"code": null,
"e": 26331,
"s": 26192,
"text": "axis : (default 0) {0 or ‘index’, 1 or ‘columns’} 0 or ‘index’: apply function to each column. 1 or ‘columns’: apply function to each row."
},
{
"code": null,
"e": 26361,
"s": 26331,
"text": "Returns: Aggregated DataFrame"
},
{
"code": null,
"e": 26530,
"s": 26361,
"text": "reset-index() – Pandas reset_index() is a method to reset index of a Data Frame. reset_index() method sets a list of integers ranging from 0 to length of data as index."
},
{
"code": null,
"e": 26624,
"s": 26530,
"text": "Syntax: DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=”)"
},
{
"code": null,
"e": 26636,
"s": 26624,
"text": "Parameters:"
},
{
"code": null,
"e": 26712,
"s": 26636,
"text": "level: int, string or a list to select and remove passed column from index."
},
{
"code": null,
"e": 26786,
"s": 26712,
"text": "drop: Boolean value, Adds the replaced index column to the data if False."
},
{
"code": null,
"e": 26866,
"s": 26786,
"text": "inplace: Boolean value, make changes in the original data frame itself if True."
},
{
"code": null,
"e": 26928,
"s": 26866,
"text": "col_level: Select in which column level to insert the labels."
},
{
"code": null,
"e": 26991,
"s": 26928,
"text": "col_fill: Object, to determine how the other levels are named."
},
{
"code": null,
"e": 27014,
"s": 26991,
"text": "Return type: DataFrame"
},
{
"code": null,
"e": 27024,
"s": 27014,
"text": "Approach:"
},
{
"code": null,
"e": 27041,
"s": 27024,
"text": "Import libraries"
},
{
"code": null,
"e": 27051,
"s": 27041,
"text": "Make data"
},
{
"code": null,
"e": 27062,
"s": 27051,
"text": "Group Data"
},
{
"code": null,
"e": 27085,
"s": 27062,
"text": "Use aggregate function"
},
{
"code": null,
"e": 27097,
"s": 27085,
"text": "Reset Index"
},
{
"code": null,
"e": 27108,
"s": 27097,
"text": "Print Data"
},
{
"code": null,
"e": 27119,
"s": 27108,
"text": "Example 1:"
},
{
"code": null,
"e": 27126,
"s": 27119,
"text": "Python"
},
{
"code": "# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({'Col_1': ['a', 'b', 'c', 'b', 'a', 'd'], 'Col_2': [1, 2, 3, 3, 2, 1]}) # print original dataframeprint(\"original dataframe:\")display(df) # call groupby method.df = df.groupby(\"Col_1\") # call agg methoddf = df.agg({\"Col_2\": \"nunique\"}) # call reset_index methoddf = df.reset_index() # print dataframeprint(\"final dataframe:\")display(df)",
"e": 27560,
"s": 27126,
"text": null
},
{
"code": null,
"e": 27568,
"s": 27560,
"text": "Output:"
},
{
"code": null,
"e": 27579,
"s": 27568,
"text": "Example 2:"
},
{
"code": null,
"e": 27586,
"s": 27579,
"text": "Python"
},
{
"code": "# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({'Col_1': ['a', 'b', 'c', 'b', 'a', 'd'], 'Col_2': [1, 2, 3, 3, 2, 1]}) # print original dataframeprint(\"original dataframe:\")display(df) # call groupby method.df = df.groupby(\"Col_2\") # call agg methoddf = df.agg({\"Col_1\": \"nunique\"}) # call reset_index methoddf = df.reset_index() # print dataframeprint(\"final data frame:\")display(df)",
"e": 28021,
"s": 27586,
"text": null
},
{
"code": null,
"e": 28029,
"s": 28021,
"text": "Output:"
},
{
"code": null,
"e": 28036,
"s": 28029,
"text": "Picked"
},
{
"code": null,
"e": 28059,
"s": 28036,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 28081,
"s": 28059,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 28095,
"s": 28081,
"text": "Python-pandas"
},
{
"code": null,
"e": 28102,
"s": 28095,
"text": "Python"
},
{
"code": null,
"e": 28200,
"s": 28102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28232,
"s": 28200,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28288,
"s": 28232,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28330,
"s": 28288,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28372,
"s": 28330,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28394,
"s": 28372,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28425,
"s": 28394,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28464,
"s": 28425,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28519,
"s": 28464,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28548,
"s": 28519,
"text": "Create a directory in Python"
}
] |
Python 3 - Tkinter Toplevel | Toplevel widgets work as windows that are directly managed by the window manager. They do not necessarily have a parent widget on top of them.
Your application can use any number of top-level windows.
Here is the simple syntax to create this widget −
w = Toplevel ( option, ... )
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
bg
The background color of the window.
bd
Border width in pixels; default is 0.
cursor
The cursor that appears when the mouse is in this window.
class_
Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection = 0 if you don't want that behavior.
font
The default font for text inserted into the widget.
fg
The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default.
height
Window height.
relief
Normally, a top-level window will have no 3-d borders around it. To get a shaded border, set the bd option larger that its default value of zero, and set the relief option to one of the constants.
width
The desired width of the window.
Toplevel objects have these methods −
deiconify()
Displays the window, after using either the iconify or the withdraw methods.
frame()
Returns a system-specific window identifier.
group(window)
Adds the window to the window group administered by the given window.
iconify()
Turns the window into an icon, without destroying it.
protocol(name, function)
Registers a function as a callback which will be called for the given protocol.
iconify()
Turns the window into an icon, without destroying it.
state()
Returns the current state of the window. Possible values are normal, iconic, withdrawn and icon.
transient([master])
Turns the window into a temporary(transient) window for the given master or to the window's parent, when no argument is given.
withdraw()
Removes the window from the screen, without destroying it.
maxsize(width, height)
Defines the maximum size for this window.
minsize(width, height)
Defines the minimum size for this window.
positionfrom(who)
Defines the position controller.
resizable(width, height)
Defines the resize flags, which control whether the window can be resized.
sizefrom(who)
Defines the size controller.
title(string)
Defines the window title.
Try following example yourself −
# !/usr/bin/python3
from tkinter import *
root = Tk()
root.title("hello")
top = Toplevel()
top.title("Python")
top.mainloop()
When the above code is executed, it produces the following result −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2483,
"s": 2340,
"text": "Toplevel widgets work as windows that are directly managed by the window manager. They do not necessarily have a parent widget on top of them."
},
{
"code": null,
"e": 2541,
"s": 2483,
"text": "Your application can use any number of top-level windows."
},
{
"code": null,
"e": 2591,
"s": 2541,
"text": "Here is the simple syntax to create this widget −"
},
{
"code": null,
"e": 2621,
"s": 2591,
"text": "w = Toplevel ( option, ... )\n"
},
{
"code": null,
"e": 2761,
"s": 2621,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 2764,
"s": 2761,
"text": "bg"
},
{
"code": null,
"e": 2800,
"s": 2764,
"text": "The background color of the window."
},
{
"code": null,
"e": 2803,
"s": 2800,
"text": "bd"
},
{
"code": null,
"e": 2841,
"s": 2803,
"text": "Border width in pixels; default is 0."
},
{
"code": null,
"e": 2848,
"s": 2841,
"text": "cursor"
},
{
"code": null,
"e": 2906,
"s": 2848,
"text": "The cursor that appears when the mouse is in this window."
},
{
"code": null,
"e": 2913,
"s": 2906,
"text": "class_"
},
{
"code": null,
"e": 3070,
"s": 2913,
"text": "Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection = 0 if you don't want that behavior."
},
{
"code": null,
"e": 3075,
"s": 3070,
"text": "font"
},
{
"code": null,
"e": 3127,
"s": 3075,
"text": "The default font for text inserted into the widget."
},
{
"code": null,
"e": 3130,
"s": 3127,
"text": "fg"
},
{
"code": null,
"e": 3265,
"s": 3130,
"text": "The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default."
},
{
"code": null,
"e": 3272,
"s": 3265,
"text": "height"
},
{
"code": null,
"e": 3287,
"s": 3272,
"text": "Window height."
},
{
"code": null,
"e": 3294,
"s": 3287,
"text": "relief"
},
{
"code": null,
"e": 3491,
"s": 3294,
"text": "Normally, a top-level window will have no 3-d borders around it. To get a shaded border, set the bd option larger that its default value of zero, and set the relief option to one of the constants."
},
{
"code": null,
"e": 3497,
"s": 3491,
"text": "width"
},
{
"code": null,
"e": 3530,
"s": 3497,
"text": "The desired width of the window."
},
{
"code": null,
"e": 3568,
"s": 3530,
"text": "Toplevel objects have these methods −"
},
{
"code": null,
"e": 3580,
"s": 3568,
"text": "deiconify()"
},
{
"code": null,
"e": 3657,
"s": 3580,
"text": "Displays the window, after using either the iconify or the withdraw methods."
},
{
"code": null,
"e": 3665,
"s": 3657,
"text": "frame()"
},
{
"code": null,
"e": 3710,
"s": 3665,
"text": "Returns a system-specific window identifier."
},
{
"code": null,
"e": 3724,
"s": 3710,
"text": "group(window)"
},
{
"code": null,
"e": 3794,
"s": 3724,
"text": "Adds the window to the window group administered by the given window."
},
{
"code": null,
"e": 3804,
"s": 3794,
"text": "iconify()"
},
{
"code": null,
"e": 3858,
"s": 3804,
"text": "Turns the window into an icon, without destroying it."
},
{
"code": null,
"e": 3883,
"s": 3858,
"text": "protocol(name, function)"
},
{
"code": null,
"e": 3963,
"s": 3883,
"text": "Registers a function as a callback which will be called for the given protocol."
},
{
"code": null,
"e": 3973,
"s": 3963,
"text": "iconify()"
},
{
"code": null,
"e": 4027,
"s": 3973,
"text": "Turns the window into an icon, without destroying it."
},
{
"code": null,
"e": 4035,
"s": 4027,
"text": "state()"
},
{
"code": null,
"e": 4132,
"s": 4035,
"text": "Returns the current state of the window. Possible values are normal, iconic, withdrawn and icon."
},
{
"code": null,
"e": 4152,
"s": 4132,
"text": "transient([master])"
},
{
"code": null,
"e": 4279,
"s": 4152,
"text": "Turns the window into a temporary(transient) window for the given master or to the window's parent, when no argument is given."
},
{
"code": null,
"e": 4290,
"s": 4279,
"text": "withdraw()"
},
{
"code": null,
"e": 4349,
"s": 4290,
"text": "Removes the window from the screen, without destroying it."
},
{
"code": null,
"e": 4372,
"s": 4349,
"text": "maxsize(width, height)"
},
{
"code": null,
"e": 4414,
"s": 4372,
"text": "Defines the maximum size for this window."
},
{
"code": null,
"e": 4437,
"s": 4414,
"text": "minsize(width, height)"
},
{
"code": null,
"e": 4479,
"s": 4437,
"text": "Defines the minimum size for this window."
},
{
"code": null,
"e": 4497,
"s": 4479,
"text": "positionfrom(who)"
},
{
"code": null,
"e": 4530,
"s": 4497,
"text": "Defines the position controller."
},
{
"code": null,
"e": 4555,
"s": 4530,
"text": "resizable(width, height)"
},
{
"code": null,
"e": 4630,
"s": 4555,
"text": "Defines the resize flags, which control whether the window can be resized."
},
{
"code": null,
"e": 4644,
"s": 4630,
"text": "sizefrom(who)"
},
{
"code": null,
"e": 4673,
"s": 4644,
"text": "Defines the size controller."
},
{
"code": null,
"e": 4687,
"s": 4673,
"text": "title(string)"
},
{
"code": null,
"e": 4713,
"s": 4687,
"text": "Defines the window title."
},
{
"code": null,
"e": 4746,
"s": 4713,
"text": "Try following example yourself −"
},
{
"code": null,
"e": 4873,
"s": 4746,
"text": "# !/usr/bin/python3\nfrom tkinter import *\n\nroot = Tk()\nroot.title(\"hello\")\ntop = Toplevel()\ntop.title(\"Python\")\ntop.mainloop()"
},
{
"code": null,
"e": 4942,
"s": 4873,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4979,
"s": 4942,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4995,
"s": 4979,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5028,
"s": 4995,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5047,
"s": 5028,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5082,
"s": 5047,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5104,
"s": 5082,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5138,
"s": 5104,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5166,
"s": 5138,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5201,
"s": 5166,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5215,
"s": 5201,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5248,
"s": 5215,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5265,
"s": 5248,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5272,
"s": 5265,
"text": " Print"
},
{
"code": null,
"e": 5283,
"s": 5272,
"text": " Add Notes"
}
] |
Find maximum and minimum element in binary tree without using recursion or stack or queue - GeeksforGeeks | 04 Aug, 2021
Given a binary tree. The task is to find out the maximum and minimum element in a binary tree without using recursion or stack or queue i.e, space complexity should be O(1).
Examples:
Input :
12
/ \
13 10
/ \
14 15
/ \ / \
21 24 22 23
Output : Max element : 24
Min element : 10
Input :
12
/ \
19 82
/ / \
41 15 95
\ / / \
2 21 7 16
Output : Max element : 95
Min element : 2
Prerequisite : Inorder Tree Traversal without recursion and without stack
Approach : 1. Initialize current as root 2. Take to variable max and min 3. While current is not NULL
If the current does not have left child Update variable max and min with current’s data if requiredGo to the right, i.e., current = current->right
Update variable max and min with current’s data if required
Go to the right, i.e., current = current->right
Else Make current as the right child of the rightmost node in current’s left subtreeGo to this left child, i.e., current = current->left
Make current as the right child of the rightmost node in current’s left subtree
Go to this left child, i.e., current = current->left
Below is the implementation of the above approach :
C++
Java
Python3
C#
Javascript
// C++ program find maximum and minimum element#include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Function to print a maximum and minimum element// in a tree without recursion without stackvoid printMinMax(Node* root){ if (root == NULL) { cout << "Tree is empty"; return; } Node* current = root; Node* pre; // Max variable for storing maximum value int max_value = INT_MIN; // Min variable for storing minimum value int min_value = INT_MAX; while (current != NULL) { // If left child does nor exists if (current->left == NULL) { max_value = max(max_value, current->key); min_value = min(min_value, current->key); current = current->right; } else { // Find the inorder predecessor of current pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; // Make current as the right child // of its inorder predecessor if (pre->right == NULL) { pre->right = current; current = current->left; } // Revert the changes made in the 'if' part to // restore the original tree i.e., fix the // right child of predecessor else { pre->right = NULL; max_value = max(max_value, current->key); min_value = min(min_value, current->key); current = current->right; } // End of if condition pre->right == NULL } // End of if condition current->left == NULL } // End of while // Finally print max and min value cout << "Max Value is : " << max_value << endl; cout << "Min Value is : " << min_value << endl;} // Driver Codeint main(){ /* 15 / \ 19 11 / \ 25 5 / \ / \ 17 3 23 24 Let us create Binary Tree as shown above */ Node* root = newNode(15); root->left = newNode(19); root->right = newNode(11); root->right->left = newNode(25); root->right->right = newNode(5); root->right->left->left = newNode(17); root->right->left->right = newNode(3); root->right->right->left = newNode(23); root->right->right->right = newNode(24); // Function call for printing a max // and min element in a tree printMinMax(root); return 0;}
// Java program find maximum and minimum elementclass GFG{ // A Tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to print a maximum and minimum element// in a tree without recursion without stackstatic void printMinMax(Node root){ if (root == null) { System.out.print("Tree is empty"); return; } Node current = root; Node pre; // Max variable for storing maximum value int max_value = Integer.MIN_VALUE; // Min variable for storing minimum value int min_value = Integer.MAX_VALUE; while (current != null) { // If left child does nor exists if (current.left == null) { max_value = Math.max(max_value, current.key); min_value = Math.min(min_value, current.key); current = current.right; } else { // Find the inorder predecessor of current pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; // Make current as the right child // of its inorder predecessor if (pre.right == null) { pre.right = current; current = current.left; } // Revert the changes made in the 'if' part to // restore the original tree i.e., fix the // right child of predecessor else { pre.right = null; max_value = Math.max(max_value, current.key); min_value = Math.min(min_value, current.key); current = current.right; } // End of if condition pre.right == null } // End of if condition current.left == null } // End of while // Finally print max and min value System.out.print("Max Value is : " + max_value + "\n"); System.out.print("Min Value is : " + min_value + "\n");} // Driver Codepublic static void main(String[] args){ /* 15 / \ 19 11 / \ 25 5 / \ / \ 17 3 23 24 Let us create Binary Tree as shown above */ Node root = newNode(15); root.left = newNode(19); root.right = newNode(11); root.right.left = newNode(25); root.right.right = newNode(5); root.right.left.left = newNode(17); root.right.left.right = newNode(3); root.right.right.left = newNode(23); root.right.right.right = newNode(24); // Function call for printing a max // and min element in a tree printMinMax(root);}} // This code is contributed by Rajput-Ji
# Python program find maximum and minimum elementfrom sys import maxsize INT_MAX = maxsizeINT_MIN = -maxsize # A Tree nodeclass Node: def __init__(self, key): self.key = key self.left = None self.right = None # Function to print a maximum and minimum element# in a tree without recursion without stackdef printMinMax(root: Node): if root is None: print("Tree is empty") return current = root pre = Node(0) # Max variable for storing maximum value max_value = INT_MIN # Min variable for storing minimum value min_value = INT_MAX while current is not None: # If left child does nor exists if current.left is None: max_value = max(max_value, current.key) min_value = min(min_value, current.key) current = current.right else: # Find the inorder predecessor of current pre = current.left while pre.right is not None and pre.right != current: pre = pre.right # Make current as the right child # of its inorder predecessor if pre.right is None: pre.right = current current = current.left # Revert the changes made in the 'if' part to # restore the original tree i.e., fix the # right child of predecessor else: pre.right = None max_value = max(max_value, current.key) min_value = min(min_value, current.key) current = current.right # End of if condition pre->right == NULL # End of if condition current->left == NULL # End of while # Finally print max and min value print("Max value is :", max_value) print("Min value is :", min_value) # Driver Codeif __name__ == "__main__": # /* 15 # / \ # 19 11 # / \ # 25 5 # / \ / \ # 17 3 23 24 # Let us create Binary Tree as shown # above */ root = Node(15) root.left = Node(19) root.right = Node(11) root.right.left = Node(25) root.right.right = Node(5) root.right.left.left = Node(17) root.right.left.right = Node(3) root.right.right.left = Node(23) root.right.right.right = Node(24) # Function call for printing a max # and min element in a tree printMinMax(root) # This code is contributed by# sanjeev2552
// C# program find maximum and minimum elementusing System;class GFG{ // A Tree nodeclass Node{ public int key; public Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to print a maximum and minimum element// in a tree without recursion without stackstatic void printMinMax(Node root){ if (root == null) { Console.Write("Tree is empty"); return; } Node current = root; Node pre; // Max variable for storing maximum value int max_value = int.MinValue; // Min variable for storing minimum value int min_value = int.MaxValue; while (current != null) { // If left child does nor exists if (current.left == null) { max_value = Math.Max(max_value, current.key); min_value = Math.Min(min_value, current.key); current = current.right; } else { // Find the inorder predecessor of current pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; // Make current as the right child // of its inorder predecessor if (pre.right == null) { pre.right = current; current = current.left; } // Revert the changes made in the 'if' part to // restore the original tree i.e., fix the // right child of predecessor else { pre.right = null; max_value = Math.Max(max_value, current.key); min_value = Math.Min(min_value, current.key); current = current.right; } // End of if condition pre.right == null } // End of if condition current.left == null } // End of while // Finally print max and min value Console.Write("Max Value is : " + max_value + "\n"); Console.Write("Min Value is : " + min_value + "\n");} // Driver Codepublic static void Main(String[] args){ /* 15 / \ 19 11 / \ 25 5 / \ / \ 17 3 23 24 Let us create Binary Tree as shown above */ Node root = newNode(15); root.left = newNode(19); root.right = newNode(11); root.right.left = newNode(25); root.right.right = newNode(5); root.right.left.left = newNode(17); root.right.left.right = newNode(3); root.right.right.left = newNode(23); root.right.right.right = newNode(24); // Function call for printing a max // and min element in a tree printMinMax(root);}} // This code is contributed by PrinciRaj1992
<script> // Javascript program find maximum// and minimum element // A Tree nodeclass Node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; // Utility function to create a new nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to print a maximum and minimum// element in a tree without recursion// without stackfunction printMinMax(root){ if (root == null) { document.write("Tree is empty"); return; } var current = root; var pre; // Max variable for storing maximum value var max_value = -1000000000; // Min variable for storing minimum value var min_value = 1000000000; while (current != null) { // If left child does nor exists if (current.left == null) { max_value = Math.max(max_value, current.key); min_value = Math.min(min_value, current.key); current = current.right; } else { // Find the inorder predecessor of current pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; // Make current as the right child // of its inorder predecessor if (pre.right == null) { pre.right = current; current = current.left; } // Revert the changes made in the 'if' // part to restore the original tree // i.e., fix the right child of predecessor else { pre.right = null; max_value = Math.max(max_value, current.key); min_value = Math.min(min_value, current.key); current = current.right; } // End of if condition pre.right == null } // End of if condition current.left == null } // End of while // Finally print max and min value document.write("Max Value is : " + max_value + "<br>"); document.write("Min Value is : " + min_value + "<br>");} // Driver Code/* 15/ \19 11 / \25 5/ \ / \17 3 23 24Let us create Binary Tree as shownabove */var root = newNode(15);root.left = newNode(19);root.right = newNode(11);root.right.left = newNode(25);root.right.right = newNode(5);root.right.left.left = newNode(17);root.right.left.right = newNode(3);root.right.right.left = newNode(23);root.right.right.right = newNode(24); // Function call for printing a max// and min element in a treeprintMinMax(root); // This code is contributed by noob2000 </script>
Output :
Max Value is : 25
Min Value is : 3
Time Complexity: O(N)Space complexity: O(1)
Rajput-Ji
princiraj1992
sanjeev2552
noob2000
pankajsharmagfg
Inorder Traversal
Algorithms
Tree
Tree
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Rail Fence Cipher - Encryption and Decryption
Quadratic Probing in Hashing
Program for SSTF disk scheduling algorithm
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion | [
{
"code": null,
"e": 24700,
"s": 24672,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 24875,
"s": 24700,
"text": "Given a binary tree. The task is to find out the maximum and minimum element in a binary tree without using recursion or stack or queue i.e, space complexity should be O(1). "
},
{
"code": null,
"e": 24886,
"s": 24875,
"text": "Examples: "
},
{
"code": null,
"e": 25474,
"s": 24886,
"text": "Input : \n 12\n / \\\n 13 10\n / \\\n 14 15\n / \\ / \\\n 21 24 22 23\n\nOutput : Max element : 24\n Min element : 10\n\nInput : \n 12\n / \\\n 19 82\n / / \\\n 41 15 95\n \\ / / \\\n 2 21 7 16\n\nOutput : Max element : 95\n Min element : 2"
},
{
"code": null,
"e": 25548,
"s": 25474,
"text": "Prerequisite : Inorder Tree Traversal without recursion and without stack"
},
{
"code": null,
"e": 25651,
"s": 25548,
"text": "Approach : 1. Initialize current as root 2. Take to variable max and min 3. While current is not NULL "
},
{
"code": null,
"e": 25798,
"s": 25651,
"text": "If the current does not have left child Update variable max and min with current’s data if requiredGo to the right, i.e., current = current->right"
},
{
"code": null,
"e": 25858,
"s": 25798,
"text": "Update variable max and min with current’s data if required"
},
{
"code": null,
"e": 25906,
"s": 25858,
"text": "Go to the right, i.e., current = current->right"
},
{
"code": null,
"e": 26043,
"s": 25906,
"text": "Else Make current as the right child of the rightmost node in current’s left subtreeGo to this left child, i.e., current = current->left"
},
{
"code": null,
"e": 26123,
"s": 26043,
"text": "Make current as the right child of the rightmost node in current’s left subtree"
},
{
"code": null,
"e": 26176,
"s": 26123,
"text": "Go to this left child, i.e., current = current->left"
},
{
"code": null,
"e": 26230,
"s": 26176,
"text": "Below is the implementation of the above approach : "
},
{
"code": null,
"e": 26234,
"s": 26230,
"text": "C++"
},
{
"code": null,
"e": 26239,
"s": 26234,
"text": "Java"
},
{
"code": null,
"e": 26247,
"s": 26239,
"text": "Python3"
},
{
"code": null,
"e": 26250,
"s": 26247,
"text": "C#"
},
{
"code": null,
"e": 26261,
"s": 26250,
"text": "Javascript"
},
{
"code": "// C++ program find maximum and minimum element#include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Function to print a maximum and minimum element// in a tree without recursion without stackvoid printMinMax(Node* root){ if (root == NULL) { cout << \"Tree is empty\"; return; } Node* current = root; Node* pre; // Max variable for storing maximum value int max_value = INT_MIN; // Min variable for storing minimum value int min_value = INT_MAX; while (current != NULL) { // If left child does nor exists if (current->left == NULL) { max_value = max(max_value, current->key); min_value = min(min_value, current->key); current = current->right; } else { // Find the inorder predecessor of current pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; // Make current as the right child // of its inorder predecessor if (pre->right == NULL) { pre->right = current; current = current->left; } // Revert the changes made in the 'if' part to // restore the original tree i.e., fix the // right child of predecessor else { pre->right = NULL; max_value = max(max_value, current->key); min_value = min(min_value, current->key); current = current->right; } // End of if condition pre->right == NULL } // End of if condition current->left == NULL } // End of while // Finally print max and min value cout << \"Max Value is : \" << max_value << endl; cout << \"Min Value is : \" << min_value << endl;} // Driver Codeint main(){ /* 15 / \\ 19 11 / \\ 25 5 / \\ / \\ 17 3 23 24 Let us create Binary Tree as shown above */ Node* root = newNode(15); root->left = newNode(19); root->right = newNode(11); root->right->left = newNode(25); root->right->right = newNode(5); root->right->left->left = newNode(17); root->right->left->right = newNode(3); root->right->right->left = newNode(23); root->right->right->right = newNode(24); // Function call for printing a max // and min element in a tree printMinMax(root); return 0;}",
"e": 29094,
"s": 26261,
"text": null
},
{
"code": "// Java program find maximum and minimum elementclass GFG{ // A Tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to print a maximum and minimum element// in a tree without recursion without stackstatic void printMinMax(Node root){ if (root == null) { System.out.print(\"Tree is empty\"); return; } Node current = root; Node pre; // Max variable for storing maximum value int max_value = Integer.MIN_VALUE; // Min variable for storing minimum value int min_value = Integer.MAX_VALUE; while (current != null) { // If left child does nor exists if (current.left == null) { max_value = Math.max(max_value, current.key); min_value = Math.min(min_value, current.key); current = current.right; } else { // Find the inorder predecessor of current pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; // Make current as the right child // of its inorder predecessor if (pre.right == null) { pre.right = current; current = current.left; } // Revert the changes made in the 'if' part to // restore the original tree i.e., fix the // right child of predecessor else { pre.right = null; max_value = Math.max(max_value, current.key); min_value = Math.min(min_value, current.key); current = current.right; } // End of if condition pre.right == null } // End of if condition current.left == null } // End of while // Finally print max and min value System.out.print(\"Max Value is : \" + max_value + \"\\n\"); System.out.print(\"Min Value is : \" + min_value + \"\\n\");} // Driver Codepublic static void main(String[] args){ /* 15 / \\ 19 11 / \\ 25 5 / \\ / \\ 17 3 23 24 Let us create Binary Tree as shown above */ Node root = newNode(15); root.left = newNode(19); root.right = newNode(11); root.right.left = newNode(25); root.right.right = newNode(5); root.right.left.left = newNode(17); root.right.left.right = newNode(3); root.right.right.left = newNode(23); root.right.right.right = newNode(24); // Function call for printing a max // and min element in a tree printMinMax(root);}} // This code is contributed by Rajput-Ji",
"e": 31965,
"s": 29094,
"text": null
},
{
"code": "# Python program find maximum and minimum elementfrom sys import maxsize INT_MAX = maxsizeINT_MIN = -maxsize # A Tree nodeclass Node: def __init__(self, key): self.key = key self.left = None self.right = None # Function to print a maximum and minimum element# in a tree without recursion without stackdef printMinMax(root: Node): if root is None: print(\"Tree is empty\") return current = root pre = Node(0) # Max variable for storing maximum value max_value = INT_MIN # Min variable for storing minimum value min_value = INT_MAX while current is not None: # If left child does nor exists if current.left is None: max_value = max(max_value, current.key) min_value = min(min_value, current.key) current = current.right else: # Find the inorder predecessor of current pre = current.left while pre.right is not None and pre.right != current: pre = pre.right # Make current as the right child # of its inorder predecessor if pre.right is None: pre.right = current current = current.left # Revert the changes made in the 'if' part to # restore the original tree i.e., fix the # right child of predecessor else: pre.right = None max_value = max(max_value, current.key) min_value = min(min_value, current.key) current = current.right # End of if condition pre->right == NULL # End of if condition current->left == NULL # End of while # Finally print max and min value print(\"Max value is :\", max_value) print(\"Min value is :\", min_value) # Driver Codeif __name__ == \"__main__\": # /* 15 # / \\ # 19 11 # / \\ # 25 5 # / \\ / \\ # 17 3 23 24 # Let us create Binary Tree as shown # above */ root = Node(15) root.left = Node(19) root.right = Node(11) root.right.left = Node(25) root.right.right = Node(5) root.right.left.left = Node(17) root.right.left.right = Node(3) root.right.right.left = Node(23) root.right.right.right = Node(24) # Function call for printing a max # and min element in a tree printMinMax(root) # This code is contributed by# sanjeev2552",
"e": 34356,
"s": 31965,
"text": null
},
{
"code": "// C# program find maximum and minimum elementusing System;class GFG{ // A Tree nodeclass Node{ public int key; public Node left, right;}; // Utility function to create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to print a maximum and minimum element// in a tree without recursion without stackstatic void printMinMax(Node root){ if (root == null) { Console.Write(\"Tree is empty\"); return; } Node current = root; Node pre; // Max variable for storing maximum value int max_value = int.MinValue; // Min variable for storing minimum value int min_value = int.MaxValue; while (current != null) { // If left child does nor exists if (current.left == null) { max_value = Math.Max(max_value, current.key); min_value = Math.Min(min_value, current.key); current = current.right; } else { // Find the inorder predecessor of current pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; // Make current as the right child // of its inorder predecessor if (pre.right == null) { pre.right = current; current = current.left; } // Revert the changes made in the 'if' part to // restore the original tree i.e., fix the // right child of predecessor else { pre.right = null; max_value = Math.Max(max_value, current.key); min_value = Math.Min(min_value, current.key); current = current.right; } // End of if condition pre.right == null } // End of if condition current.left == null } // End of while // Finally print max and min value Console.Write(\"Max Value is : \" + max_value + \"\\n\"); Console.Write(\"Min Value is : \" + min_value + \"\\n\");} // Driver Codepublic static void Main(String[] args){ /* 15 / \\ 19 11 / \\ 25 5 / \\ / \\ 17 3 23 24 Let us create Binary Tree as shown above */ Node root = newNode(15); root.left = newNode(19); root.right = newNode(11); root.right.left = newNode(25); root.right.right = newNode(5); root.right.left.left = newNode(17); root.right.left.right = newNode(3); root.right.right.left = newNode(23); root.right.right.right = newNode(24); // Function call for printing a max // and min element in a tree printMinMax(root);}} // This code is contributed by PrinciRaj1992",
"e": 37366,
"s": 34356,
"text": null
},
{
"code": "<script> // Javascript program find maximum// and minimum element // A Tree nodeclass Node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; // Utility function to create a new nodefunction newNode(key){ var temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to print a maximum and minimum// element in a tree without recursion// without stackfunction printMinMax(root){ if (root == null) { document.write(\"Tree is empty\"); return; } var current = root; var pre; // Max variable for storing maximum value var max_value = -1000000000; // Min variable for storing minimum value var min_value = 1000000000; while (current != null) { // If left child does nor exists if (current.left == null) { max_value = Math.max(max_value, current.key); min_value = Math.min(min_value, current.key); current = current.right; } else { // Find the inorder predecessor of current pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; // Make current as the right child // of its inorder predecessor if (pre.right == null) { pre.right = current; current = current.left; } // Revert the changes made in the 'if' // part to restore the original tree // i.e., fix the right child of predecessor else { pre.right = null; max_value = Math.max(max_value, current.key); min_value = Math.min(min_value, current.key); current = current.right; } // End of if condition pre.right == null } // End of if condition current.left == null } // End of while // Finally print max and min value document.write(\"Max Value is : \" + max_value + \"<br>\"); document.write(\"Min Value is : \" + min_value + \"<br>\");} // Driver Code/* 15/ \\19 11 / \\25 5/ \\ / \\17 3 23 24Let us create Binary Tree as shownabove */var root = newNode(15);root.left = newNode(19);root.right = newNode(11);root.right.left = newNode(25);root.right.right = newNode(5);root.right.left.left = newNode(17);root.right.left.right = newNode(3);root.right.right.left = newNode(23);root.right.right.right = newNode(24); // Function call for printing a max// and min element in a treeprintMinMax(root); // This code is contributed by noob2000 </script>",
"e": 40295,
"s": 37366,
"text": null
},
{
"code": null,
"e": 40305,
"s": 40295,
"text": "Output : "
},
{
"code": null,
"e": 40340,
"s": 40305,
"text": "Max Value is : 25\nMin Value is : 3"
},
{
"code": null,
"e": 40385,
"s": 40340,
"text": "Time Complexity: O(N)Space complexity: O(1) "
},
{
"code": null,
"e": 40395,
"s": 40385,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 40409,
"s": 40395,
"text": "princiraj1992"
},
{
"code": null,
"e": 40421,
"s": 40409,
"text": "sanjeev2552"
},
{
"code": null,
"e": 40430,
"s": 40421,
"text": "noob2000"
},
{
"code": null,
"e": 40446,
"s": 40430,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 40464,
"s": 40446,
"text": "Inorder Traversal"
},
{
"code": null,
"e": 40475,
"s": 40464,
"text": "Algorithms"
},
{
"code": null,
"e": 40480,
"s": 40475,
"text": "Tree"
},
{
"code": null,
"e": 40485,
"s": 40480,
"text": "Tree"
},
{
"code": null,
"e": 40496,
"s": 40485,
"text": "Algorithms"
},
{
"code": null,
"e": 40594,
"s": 40496,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40619,
"s": 40594,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 40662,
"s": 40619,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 40708,
"s": 40662,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 40737,
"s": 40708,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 40780,
"s": 40737,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 40830,
"s": 40780,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 40865,
"s": 40830,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 40899,
"s": 40865,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 40928,
"s": 40899,
"text": "AVL Tree | Set 1 (Insertion)"
}
] |
How to fix the incorrect datetime value while inserting in a MySQL table? | To avoid the incorrect datetime value error, you can use the STR_TO_DATE() method.
As we know the datetime format is YYYY-MM-DD and if you won’t insert in the same format, the error would get generated.
Let us see what actually lead to this error. For this, let us create a new table. The query to create a table is as follows
mysql> create table CorrectDatetimeDemo
- > (
- > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
- > ArrivalTime datetime
- > );
Query OK, 0 rows affected (0.63 sec)
The occurs when we try to include a date with an incorrect datetime format
mysql> insert into CorrectDatetimeDemo(ArrivalTime) values('18/02/2019 11:15:45');
ERROR 1292 (22007): Incorrect datetime value: '18/02/2019 11:15:45' for column 'ArrivalTime' at row 1
To avoid the above error, you can use STR_TO_DATE().
The syntax is as follows
INSERT INTO yourTableName(yourDateTimeColumnName) VALUES (STR_TO_DATE('yourDateTimeValue','%d/%m/%Y %H:%i:%s'));
Now, let us insert the datetime again with the correct format as shown in the above syntax.
The query is as follows
mysql> insert into CorrectDatetimeDemo(ArrivalTime) values(STR_TO_DATE('18/02/2019 11:15:45','%d/%m/%Y %H:%i:%s'));
Query OK, 1 row affected (0.21 sec)
mysql> insert into CorrectDatetimeDemo(ArrivalTime) values(STR_TO_DATE('15/01/2017 10:10:15','%d/%m/%Y %H:%i:%s'));
Query OK, 1 row affected (0.16 sec)
mysql> insert into CorrectDatetimeDemo(ArrivalTime) values(STR_TO_DATE('12/04/2016 15:30:35','%d/%m/%Y %H:%i:%s'));
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from CorrectDatetimeDemo;
The following is the output
+----+---------------------+
| Id | ArrivalTime |
+----+---------------------+
| 1 | 2019-02-18 11:15:45 |
| 2 | 2017-01-15 10:10:15 |
| 3 | 2016-04-12 15:30:35 |
+----+---------------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1270,
"s": 1187,
"text": "To avoid the incorrect datetime value error, you can use the STR_TO_DATE() method."
},
{
"code": null,
"e": 1390,
"s": 1270,
"text": "As we know the datetime format is YYYY-MM-DD and if you won’t insert in the same format, the error would get generated."
},
{
"code": null,
"e": 1514,
"s": 1390,
"text": "Let us see what actually lead to this error. For this, let us create a new table. The query to create a table is as follows"
},
{
"code": null,
"e": 1689,
"s": 1514,
"text": "mysql> create table CorrectDatetimeDemo\n - > (\n - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > ArrivalTime datetime\n - > );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1764,
"s": 1689,
"text": "The occurs when we try to include a date with an incorrect datetime format"
},
{
"code": null,
"e": 1949,
"s": 1764,
"text": "mysql> insert into CorrectDatetimeDemo(ArrivalTime) values('18/02/2019 11:15:45');\nERROR 1292 (22007): Incorrect datetime value: '18/02/2019 11:15:45' for column 'ArrivalTime' at row 1"
},
{
"code": null,
"e": 2002,
"s": 1949,
"text": "To avoid the above error, you can use STR_TO_DATE()."
},
{
"code": null,
"e": 2027,
"s": 2002,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 2140,
"s": 2027,
"text": "INSERT INTO yourTableName(yourDateTimeColumnName) VALUES (STR_TO_DATE('yourDateTimeValue','%d/%m/%Y %H:%i:%s'));"
},
{
"code": null,
"e": 2232,
"s": 2140,
"text": "Now, let us insert the datetime again with the correct format as shown in the above syntax."
},
{
"code": null,
"e": 2256,
"s": 2232,
"text": "The query is as follows"
},
{
"code": null,
"e": 2714,
"s": 2256,
"text": "mysql> insert into CorrectDatetimeDemo(ArrivalTime) values(STR_TO_DATE('18/02/2019 11:15:45','%d/%m/%Y %H:%i:%s'));\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into CorrectDatetimeDemo(ArrivalTime) values(STR_TO_DATE('15/01/2017 10:10:15','%d/%m/%Y %H:%i:%s'));\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into CorrectDatetimeDemo(ArrivalTime) values(STR_TO_DATE('12/04/2016 15:30:35','%d/%m/%Y %H:%i:%s'));\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 2773,
"s": 2714,
"text": "Display all records from the table using select statement."
},
{
"code": null,
"e": 2797,
"s": 2773,
"text": "The query is as follows"
},
{
"code": null,
"e": 2838,
"s": 2797,
"text": "mysql> select *from CorrectDatetimeDemo;"
},
{
"code": null,
"e": 2866,
"s": 2838,
"text": "The following is the output"
},
{
"code": null,
"e": 3094,
"s": 2866,
"text": "+----+---------------------+\n| Id | ArrivalTime |\n+----+---------------------+\n| 1 | 2019-02-18 11:15:45 |\n| 2 | 2017-01-15 10:10:15 |\n| 3 | 2016-04-12 15:30:35 |\n+----+---------------------+\n3 rows in set (0.00 sec)"
}
] |
Flutter – Customizable Ratings bar | 15 Feb, 2021
Rating Bar as the name suggests is used to rate content inside the application. More or less all applications use them either to gate user feedback on their application or to get a rating for content hosted by the application. Applications like IMDB use them to rate movies and Television series where apps like and Uber use them to get feedback on their services from the customer.
In this article we will build a simple app with the following features:
A horizontal Rating bar
A switch to make all rating bars above go right to left
A switch to make the rating bars vertical
Three different modes to change the Icon of the first rating bar
To build the above application follow the below steps:
Add the dependency to the pubspec.yaml file
Import the dependency to the main.dart file
Use the StatefulWidget to give structure to the application
Add the vertical rating bar
Add switch to change the alignment of the rating bars from right to left (RTL)
Add a switch to change the alignment of the rating bar from horizontal to vertical
Add 3 different modes that change the UI Icons.
To add the dependency to the pubspec.yaml file the following image can be followed:
To import the flutter_rating_bar dependency to the main.dart file, use the following:
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
A StatefulWidget can be used to give the app an appbar and a body to hold content as shown below:
Dart
class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { var _ratingController = TextEditingController(); double _rating; int _ratingBarMode = 1; bool _isRTLMode = false; bool _isVertical = false; IconData _selectedIcon; @override void initState() { _ratingController.text = "3.0"; super.initState(); } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, appBarTheme: AppBarTheme( textTheme: TextTheme( title: Theme.of(context).textTheme.title.copyWith( color: Colors.white, ), ), ), ),
A simple rating bar can be called upon from the flutter_rating_bar package by calling the RatingBar widget as shown below:
Dart
RatingBar( initialRating: 3, minRating: 1, direction: Axis.horizontal, allowHalfRating: true, itemCount: 5, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, _) => Icon( Icons.star, color: Colors.amber, ), onRatingUpdate: (rating) { print(rating); },);
At this stage, we will add a switch that can change the alignment of the rating bar from left to right, to right to left. It can be done by using the MainAxisAlignment as MainAxisAlignment.center and calling the _isRTL mode as shown below:
Dart
mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Switch to RTL Mode', style: TextStyle( fontWeight: FontWeight.w300, ), ), Switch( value: _isRTLMode, onChanged: (value) { setState(() { _isRTLMode = value; }); },
At this stage, we will add a switch that can change the alignment of the rating bar from left to right, to right to left. It can be done by using the MainAxisAlignment as MainAxisAlignment.center and calling the _isVertical mode as shown below:
Dart
mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Switch to Vertical Bar', style: TextStyle( fontWeight: FontWeight.w300, ), ), Switch( value: _isVertical, onChanged: (value) { setState(() { _isVertical = value; }); }, activeColor: Colors.amber, ), ], ),
In this application, we will be adding 3 Mode and on the selection of each mode the rating bar Icon will change. We will be using the switch() function to assign the cases to modes and assign icons to the same as shown below:
Dart
Widget _ratingBar(int mode) { switch (mode) { case 1: return RatingBar( initialRating: 2, minRating: 1, direction: _isVertical ? Axis.vertical : Axis.horizontal, allowHalfRating: true, unratedColor: Colors.amber.withAlpha(50), itemCount: 5, itemSize: 50.0, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, _) => Icon( _selectedIcon ?? Icons.star, color: Colors.amber, ), onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); case 2: return RatingBar( initialRating: 3, direction: _isVertical ? Axis.vertical : Axis.horizontal, allowHalfRating: true, itemCount: 5, ratingWidget: RatingWidget( full: _image('assets/heart.png'), half: _image('assets/heart_half.png'), empty: _image('assets/heart_border.png'), ), itemPadding: EdgeInsets.symmetric(horizontal: 4.0), onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); case 3: return RatingBar( initialRating: 3, direction: _isVertical ? Axis.vertical : Axis.horizontal, itemCount: 5, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, index) { switch (index) { case 0: return Icon( Icons.sentiment_very_dissatisfied, color: Colors.red, ); case 1: return Icon( Icons.sentiment_dissatisfied, color: Colors.redAccent, ); case 2: return Icon( Icons.sentiment_neutral, color: Colors.amber, ); case 3: return Icon( Icons.sentiment_satisfied, color: Colors.lightGreen, ); case 4: return Icon( Icons.sentiment_very_satisfied, color: Colors.green, ); default: return Container(); } }, onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); default: return Container(); } }
Complete Source Code:
Dart
import 'package:flutter/material.dart';import 'package:flutter_rating_bar/flutter_rating_bar.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { var _ratingController = TextEditingController(); double _rating; int _ratingBarMode = 1; bool _isRTLMode = false; bool _isVertical = false; IconData _selectedIcon; @override void initState() { _ratingController.text = "3.0"; super.initState(); } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, appBarTheme: AppBarTheme( textTheme: TextTheme( title: Theme.of(context).textTheme.title.copyWith( color: Colors.white, ), ), ), ), home: Builder( builder: (context) => Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Directionality( textDirection: _isRTLMode ? TextDirection.rtl : TextDirection.ltr, child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox( height: 40.0, ), _heading('Rating Bar'), _ratingBar(_ratingBarMode), SizedBox( height: 20.0, ), _rating != null ? Text( "Rating: $_rating", style: TextStyle(fontWeight: FontWeight.bold), ) : Container(), Row( children: [ _radio(1), _radio(2), _radio(3), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Switch to Vertical Bar', style: TextStyle( fontWeight: FontWeight.w300, ), ), Switch( value: _isVertical, onChanged: (value) { setState(() { _isVertical = value; }); }, activeColor: Colors.amber, ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Switch to RTL Mode', style: TextStyle( fontWeight: FontWeight.w300, ), ), Switch( value: _isRTLMode, onChanged: (value) { setState(() { _isRTLMode = value; }); }, activeColor: Colors.amber, ), ], ), ], ), ), ), ), ), ); } Widget _radio(int value) { return Expanded( child: RadioListTile( value: value, groupValue: _ratingBarMode, dense: true, title: Text( 'Mode $value', style: TextStyle( fontWeight: FontWeight.w300, fontSize: 12.0, ), ), onChanged: (value) { setState(() { _ratingBarMode = value; }); }, ), ); } Widget _ratingBar(int mode) { switch (mode) { case 1: return RatingBar( initialRating: 2, minRating: 1, direction: _isVertical ? Axis.vertical : Axis.horizontal, allowHalfRating: true, unratedColor: Colors.amber.withAlpha(50), itemCount: 5, itemSize: 50.0, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, _) => Icon( _selectedIcon ?? Icons.star, color: Colors.amber, ), onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); case 2: return RatingBar( initialRating: 3, direction: _isVertical ? Axis.vertical : Axis.horizontal, allowHalfRating: true, itemCount: 5, ratingWidget: RatingWidget( full: _image('assets/heart.png'), half: _image('assets/heart_half.png'), empty: _image('assets/heart_border.png'), ), itemPadding: EdgeInsets.symmetric(horizontal: 4.0), onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); case 3: return RatingBar( initialRating: 3, direction: _isVertical ? Axis.vertical : Axis.horizontal, itemCount: 5, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, index) { switch (index) { case 0: return Icon( Icons.sentiment_very_dissatisfied, color: Colors.red, ); case 1: return Icon( Icons.sentiment_dissatisfied, color: Colors.redAccent, ); case 2: return Icon( Icons.sentiment_neutral, color: Colors.amber, ); case 3: return Icon( Icons.sentiment_satisfied, color: Colors.lightGreen, ); case 4: return Icon( Icons.sentiment_very_satisfied, color: Colors.green, ); default: return Container(); } }, onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); default: return Container(); } } Widget _image(String asset) { return Image.asset( asset, height: 30.0, width: 30.0, color: Colors.amber, ); } Widget _heading(String text) => Column( children: [ Text( text, style: TextStyle( fontWeight: FontWeight.w300, fontSize: 24.0, ), ), SizedBox( height: 20.0, ), ], );}
Output:
android
Flutter
Flutter UI-components
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ListView Class in Flutter
Flutter - Search Bar
Flutter - Dialogs
Flutter - FutureBuilder Widget
Flutter - Flexible Widget
Flutter Tutorial
Flutter - Search Bar
Flutter - Dialogs
Flutter - FutureBuilder Widget
Flutter - Flexible Widget | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 411,
"s": 28,
"text": "Rating Bar as the name suggests is used to rate content inside the application. More or less all applications use them either to gate user feedback on their application or to get a rating for content hosted by the application. Applications like IMDB use them to rate movies and Television series where apps like and Uber use them to get feedback on their services from the customer."
},
{
"code": null,
"e": 483,
"s": 411,
"text": "In this article we will build a simple app with the following features:"
},
{
"code": null,
"e": 507,
"s": 483,
"text": "A horizontal Rating bar"
},
{
"code": null,
"e": 563,
"s": 507,
"text": "A switch to make all rating bars above go right to left"
},
{
"code": null,
"e": 605,
"s": 563,
"text": "A switch to make the rating bars vertical"
},
{
"code": null,
"e": 670,
"s": 605,
"text": "Three different modes to change the Icon of the first rating bar"
},
{
"code": null,
"e": 725,
"s": 670,
"text": "To build the above application follow the below steps:"
},
{
"code": null,
"e": 769,
"s": 725,
"text": "Add the dependency to the pubspec.yaml file"
},
{
"code": null,
"e": 813,
"s": 769,
"text": "Import the dependency to the main.dart file"
},
{
"code": null,
"e": 873,
"s": 813,
"text": "Use the StatefulWidget to give structure to the application"
},
{
"code": null,
"e": 901,
"s": 873,
"text": "Add the vertical rating bar"
},
{
"code": null,
"e": 980,
"s": 901,
"text": "Add switch to change the alignment of the rating bars from right to left (RTL)"
},
{
"code": null,
"e": 1063,
"s": 980,
"text": "Add a switch to change the alignment of the rating bar from horizontal to vertical"
},
{
"code": null,
"e": 1111,
"s": 1063,
"text": "Add 3 different modes that change the UI Icons."
},
{
"code": null,
"e": 1195,
"s": 1111,
"text": "To add the dependency to the pubspec.yaml file the following image can be followed:"
},
{
"code": null,
"e": 1281,
"s": 1195,
"text": "To import the flutter_rating_bar dependency to the main.dart file, use the following:"
},
{
"code": null,
"e": 1343,
"s": 1281,
"text": "import 'package:flutter_rating_bar/flutter_rating_bar.dart';\n"
},
{
"code": null,
"e": 1441,
"s": 1343,
"text": "A StatefulWidget can be used to give the app an appbar and a body to hold content as shown below:"
},
{
"code": null,
"e": 1446,
"s": 1441,
"text": "Dart"
},
{
"code": "class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { var _ratingController = TextEditingController(); double _rating; int _ratingBarMode = 1; bool _isRTLMode = false; bool _isVertical = false; IconData _selectedIcon; @override void initState() { _ratingController.text = \"3.0\"; super.initState(); } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, appBarTheme: AppBarTheme( textTheme: TextTheme( title: Theme.of(context).textTheme.title.copyWith( color: Colors.white, ), ), ), ),",
"e": 2222,
"s": 1446,
"text": null
},
{
"code": null,
"e": 2345,
"s": 2222,
"text": "A simple rating bar can be called upon from the flutter_rating_bar package by calling the RatingBar widget as shown below:"
},
{
"code": null,
"e": 2350,
"s": 2345,
"text": "Dart"
},
{
"code": "RatingBar( initialRating: 3, minRating: 1, direction: Axis.horizontal, allowHalfRating: true, itemCount: 5, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, _) => Icon( Icons.star, color: Colors.amber, ), onRatingUpdate: (rating) { print(rating); },);",
"e": 2660,
"s": 2350,
"text": null
},
{
"code": null,
"e": 2900,
"s": 2660,
"text": "At this stage, we will add a switch that can change the alignment of the rating bar from left to right, to right to left. It can be done by using the MainAxisAlignment as MainAxisAlignment.center and calling the _isRTL mode as shown below:"
},
{
"code": null,
"e": 2905,
"s": 2900,
"text": "Dart"
},
{
"code": "mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Switch to RTL Mode', style: TextStyle( fontWeight: FontWeight.w300, ), ), Switch( value: _isRTLMode, onChanged: (value) { setState(() { _isRTLMode = value; }); },",
"e": 3448,
"s": 2905,
"text": null
},
{
"code": null,
"e": 3693,
"s": 3448,
"text": "At this stage, we will add a switch that can change the alignment of the rating bar from left to right, to right to left. It can be done by using the MainAxisAlignment as MainAxisAlignment.center and calling the _isVertical mode as shown below:"
},
{
"code": null,
"e": 3698,
"s": 3693,
"text": "Dart"
},
{
"code": "mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Switch to Vertical Bar', style: TextStyle( fontWeight: FontWeight.w300, ), ), Switch( value: _isVertical, onChanged: (value) { setState(() { _isVertical = value; }); }, activeColor: Colors.amber, ), ], ),",
"e": 4359,
"s": 3698,
"text": null
},
{
"code": null,
"e": 4585,
"s": 4359,
"text": "In this application, we will be adding 3 Mode and on the selection of each mode the rating bar Icon will change. We will be using the switch() function to assign the cases to modes and assign icons to the same as shown below:"
},
{
"code": null,
"e": 4590,
"s": 4585,
"text": "Dart"
},
{
"code": "Widget _ratingBar(int mode) { switch (mode) { case 1: return RatingBar( initialRating: 2, minRating: 1, direction: _isVertical ? Axis.vertical : Axis.horizontal, allowHalfRating: true, unratedColor: Colors.amber.withAlpha(50), itemCount: 5, itemSize: 50.0, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, _) => Icon( _selectedIcon ?? Icons.star, color: Colors.amber, ), onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); case 2: return RatingBar( initialRating: 3, direction: _isVertical ? Axis.vertical : Axis.horizontal, allowHalfRating: true, itemCount: 5, ratingWidget: RatingWidget( full: _image('assets/heart.png'), half: _image('assets/heart_half.png'), empty: _image('assets/heart_border.png'), ), itemPadding: EdgeInsets.symmetric(horizontal: 4.0), onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); case 3: return RatingBar( initialRating: 3, direction: _isVertical ? Axis.vertical : Axis.horizontal, itemCount: 5, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, index) { switch (index) { case 0: return Icon( Icons.sentiment_very_dissatisfied, color: Colors.red, ); case 1: return Icon( Icons.sentiment_dissatisfied, color: Colors.redAccent, ); case 2: return Icon( Icons.sentiment_neutral, color: Colors.amber, ); case 3: return Icon( Icons.sentiment_satisfied, color: Colors.lightGreen, ); case 4: return Icon( Icons.sentiment_very_satisfied, color: Colors.green, ); default: return Container(); } }, onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); default: return Container(); } }",
"e": 7042,
"s": 4590,
"text": null
},
{
"code": null,
"e": 7064,
"s": 7042,
"text": "Complete Source Code:"
},
{
"code": null,
"e": 7069,
"s": 7064,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:flutter_rating_bar/flutter_rating_bar.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { var _ratingController = TextEditingController(); double _rating; int _ratingBarMode = 1; bool _isRTLMode = false; bool _isVertical = false; IconData _selectedIcon; @override void initState() { _ratingController.text = \"3.0\"; super.initState(); } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, appBarTheme: AppBarTheme( textTheme: TextTheme( title: Theme.of(context).textTheme.title.copyWith( color: Colors.white, ), ), ), ), home: Builder( builder: (context) => Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Directionality( textDirection: _isRTLMode ? TextDirection.rtl : TextDirection.ltr, child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox( height: 40.0, ), _heading('Rating Bar'), _ratingBar(_ratingBarMode), SizedBox( height: 20.0, ), _rating != null ? Text( \"Rating: $_rating\", style: TextStyle(fontWeight: FontWeight.bold), ) : Container(), Row( children: [ _radio(1), _radio(2), _radio(3), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Switch to Vertical Bar', style: TextStyle( fontWeight: FontWeight.w300, ), ), Switch( value: _isVertical, onChanged: (value) { setState(() { _isVertical = value; }); }, activeColor: Colors.amber, ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Switch to RTL Mode', style: TextStyle( fontWeight: FontWeight.w300, ), ), Switch( value: _isRTLMode, onChanged: (value) { setState(() { _isRTLMode = value; }); }, activeColor: Colors.amber, ), ], ), ], ), ), ), ), ), ); } Widget _radio(int value) { return Expanded( child: RadioListTile( value: value, groupValue: _ratingBarMode, dense: true, title: Text( 'Mode $value', style: TextStyle( fontWeight: FontWeight.w300, fontSize: 12.0, ), ), onChanged: (value) { setState(() { _ratingBarMode = value; }); }, ), ); } Widget _ratingBar(int mode) { switch (mode) { case 1: return RatingBar( initialRating: 2, minRating: 1, direction: _isVertical ? Axis.vertical : Axis.horizontal, allowHalfRating: true, unratedColor: Colors.amber.withAlpha(50), itemCount: 5, itemSize: 50.0, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, _) => Icon( _selectedIcon ?? Icons.star, color: Colors.amber, ), onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); case 2: return RatingBar( initialRating: 3, direction: _isVertical ? Axis.vertical : Axis.horizontal, allowHalfRating: true, itemCount: 5, ratingWidget: RatingWidget( full: _image('assets/heart.png'), half: _image('assets/heart_half.png'), empty: _image('assets/heart_border.png'), ), itemPadding: EdgeInsets.symmetric(horizontal: 4.0), onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); case 3: return RatingBar( initialRating: 3, direction: _isVertical ? Axis.vertical : Axis.horizontal, itemCount: 5, itemPadding: EdgeInsets.symmetric(horizontal: 4.0), itemBuilder: (context, index) { switch (index) { case 0: return Icon( Icons.sentiment_very_dissatisfied, color: Colors.red, ); case 1: return Icon( Icons.sentiment_dissatisfied, color: Colors.redAccent, ); case 2: return Icon( Icons.sentiment_neutral, color: Colors.amber, ); case 3: return Icon( Icons.sentiment_satisfied, color: Colors.lightGreen, ); case 4: return Icon( Icons.sentiment_very_satisfied, color: Colors.green, ); default: return Container(); } }, onRatingUpdate: (rating) { setState(() { _rating = rating; }); }, ); default: return Container(); } } Widget _image(String asset) { return Image.asset( asset, height: 30.0, width: 30.0, color: Colors.amber, ); } Widget _heading(String text) => Column( children: [ Text( text, style: TextStyle( fontWeight: FontWeight.w300, fontSize: 24.0, ), ), SizedBox( height: 20.0, ), ], );}",
"e": 14023,
"s": 7069,
"text": null
},
{
"code": null,
"e": 14031,
"s": 14023,
"text": "Output:"
},
{
"code": null,
"e": 14039,
"s": 14031,
"text": "android"
},
{
"code": null,
"e": 14047,
"s": 14039,
"text": "Flutter"
},
{
"code": null,
"e": 14069,
"s": 14047,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 14074,
"s": 14069,
"text": "Dart"
},
{
"code": null,
"e": 14082,
"s": 14074,
"text": "Flutter"
},
{
"code": null,
"e": 14180,
"s": 14082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14206,
"s": 14180,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 14227,
"s": 14206,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 14245,
"s": 14227,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 14276,
"s": 14245,
"text": "Flutter - FutureBuilder Widget"
},
{
"code": null,
"e": 14302,
"s": 14276,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 14319,
"s": 14302,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 14340,
"s": 14319,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 14358,
"s": 14340,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 14389,
"s": 14358,
"text": "Flutter - FutureBuilder Widget"
}
] |
Difference between 1NF and 2NF in DBMS | 21 Aug, 2021
1. First Normal Form (1NF) : For any relation to be in the first normal form (1NF), the relation should not contain any composite or multi-valued attribute. So a relation will be in first normal form if it contains atomic values. The relation should contain only single valued attributes. Thus a relation that is in the first normal form must follow the following rules:
There should be no repeating groups or elements in the relation, i.e., it should contain only single valued attributes.
There should be a unique name to be specified for each attribute within the table.
It should not contain any composite attributes.
Example: Consider the following relation:
This relation is in 1NF as it does not contain any multi-valued or composite attributes.
2. Second Normal Form (2NF) : The basic concept of second normal form is full functional dependency. It is thus applicable to the relations which contain composite keys(where the primary key consists of more than one attributes).So any relation which contains a single attribute primary key is always in 2NF (second normal form). Thus the relation which contains a composite primary key in order to be in 2NF should not contain any partial dependency. Partial dependency occurs when any non prime attribute is dependent on any of the proper subsets of the candidate key .Thus every non prime attribute should be dependent on whole of the every candidate key in the relation. Thus a relation is in 2NF if:
It is in 1NF(first normal form).
It does not contain any partial dependency.
Example: Consider the functional dependencies for the relation R(X, Y, E, F).
{XY->EF, E->F}
We thus find the closure of (XY) which is {X, Y, E, F} Since its closure contains all the attributes in the relation thus XY is the candidate key.For each functional dependency, i.e., XY->EF: It does not contain any partial dependency as the non prime attributes depend on the whole of candidate key. E->F: It does not contain any partial dependency as here the non prime attributes depend on each other only.
Difference between 1NF and 2NF :
surinderdawra388
Picked
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Trigger | Student Database
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 400,
"s": 28,
"text": "1. First Normal Form (1NF) : For any relation to be in the first normal form (1NF), the relation should not contain any composite or multi-valued attribute. So a relation will be in first normal form if it contains atomic values. The relation should contain only single valued attributes. Thus a relation that is in the first normal form must follow the following rules: "
},
{
"code": null,
"e": 520,
"s": 400,
"text": "There should be no repeating groups or elements in the relation, i.e., it should contain only single valued attributes."
},
{
"code": null,
"e": 603,
"s": 520,
"text": "There should be a unique name to be specified for each attribute within the table."
},
{
"code": null,
"e": 651,
"s": 603,
"text": "It should not contain any composite attributes."
},
{
"code": null,
"e": 695,
"s": 651,
"text": "Example: Consider the following relation: "
},
{
"code": null,
"e": 785,
"s": 695,
"text": "This relation is in 1NF as it does not contain any multi-valued or composite attributes. "
},
{
"code": null,
"e": 1492,
"s": 785,
"text": "2. Second Normal Form (2NF) : The basic concept of second normal form is full functional dependency. It is thus applicable to the relations which contain composite keys(where the primary key consists of more than one attributes).So any relation which contains a single attribute primary key is always in 2NF (second normal form). Thus the relation which contains a composite primary key in order to be in 2NF should not contain any partial dependency. Partial dependency occurs when any non prime attribute is dependent on any of the proper subsets of the candidate key .Thus every non prime attribute should be dependent on whole of the every candidate key in the relation. Thus a relation is in 2NF if: "
},
{
"code": null,
"e": 1525,
"s": 1492,
"text": "It is in 1NF(first normal form)."
},
{
"code": null,
"e": 1569,
"s": 1525,
"text": "It does not contain any partial dependency."
},
{
"code": null,
"e": 1649,
"s": 1569,
"text": "Example: Consider the functional dependencies for the relation R(X, Y, E, F). "
},
{
"code": null,
"e": 1665,
"s": 1649,
"text": "{XY->EF, E->F} "
},
{
"code": null,
"e": 2076,
"s": 1665,
"text": "We thus find the closure of (XY) which is {X, Y, E, F} Since its closure contains all the attributes in the relation thus XY is the candidate key.For each functional dependency, i.e., XY->EF: It does not contain any partial dependency as the non prime attributes depend on the whole of candidate key. E->F: It does not contain any partial dependency as here the non prime attributes depend on each other only. "
},
{
"code": null,
"e": 2111,
"s": 2076,
"text": "Difference between 1NF and 2NF : "
},
{
"code": null,
"e": 2128,
"s": 2111,
"text": "surinderdawra388"
},
{
"code": null,
"e": 2135,
"s": 2128,
"text": "Picked"
},
{
"code": null,
"e": 2140,
"s": 2135,
"text": "DBMS"
},
{
"code": null,
"e": 2159,
"s": 2140,
"text": "Difference Between"
},
{
"code": null,
"e": 2167,
"s": 2159,
"text": "GATE CS"
},
{
"code": null,
"e": 2172,
"s": 2167,
"text": "DBMS"
},
{
"code": null,
"e": 2270,
"s": 2172,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2281,
"s": 2270,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2334,
"s": 2281,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2392,
"s": 2334,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 2415,
"s": 2392,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 2446,
"s": 2415,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 2486,
"s": 2446,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 2517,
"s": 2486,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 2578,
"s": 2517,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2646,
"s": 2578,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
related_name – Django Built-in Field Validation | 01 Nov, 2020
The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don’t specify a related_name, Django automatically creates one using the name of your model with the suffix _set.
Syntax:
field_name = models.Field(related_name="name")
Explanation:
Illustration of related_name=”name” using an Example. Consider a project named suorganizer(start up organizer) having an app named organizer.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django ?
How to Create an App in Django ?
Enter the following code into models.py file of organizer app.
Python
from django.db import models # Create your models here. class Tag(models.Model): name = models.CharField(max_length = 31) def __str__(self): return self.name.title() class Post(models.Model): title = models.CharField(max_length = 63) tags = models.ManyToManyField(Tag, related_name ='blog_posts') def __str__(self): return self.title
After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command.
Python manage.py shell
Now let us try to create instance of Tag and Post using None.
# importing required model
from organizer.models import Tag, Post
# creating instance of Tag model
r = Tag.objects.create(name ="django")
r.save()
# creating instance of Post model
s = Post.objects.create(title ="About django")
s.save()
# accessing objects
t = Tag.objects.get(name ="django")
p = Post.objects.get(title ="About django")
# method1--adding tag to post using post object
p.tags.add(t)
# method2--adding tag to post using tag object
# which is possible with related_name
t.blog_posts.add(p)
Let us check in admin interface if the instance of model is created.
1. Tag object:
2.Post object
In Django we only ever specify symmetric relations in a single place. The related_name parameter is what defines the other side of a relation. Concretely, given a Post instance p, the tags associated with this post are accessible via p.tags. However, given a Tag instance t, we had not explicitly defined a variable to access Post objects. Thanks to the related_name option, we may now access the list of blog posts related to the tag t via the blog posts attribute, as in t.blog_posts. The related _name parameter is actually an option. If we do not set it, Django automatically creates the other side of the relation for us. In the case of the Tag model, Django would have created a post_set attribute, allowing access via t.post_set in our example. The formula Django uses is the name of the model followed by the string_set. The related name parameter thus simply overrides Django’s default rather than providing new behavior.
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Nov, 2020"
},
{
"code": null,
"e": 259,
"s": 28,
"text": "The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don’t specify a related_name, Django automatically creates one using the name of your model with the suffix _set."
},
{
"code": null,
"e": 267,
"s": 259,
"text": "Syntax:"
},
{
"code": null,
"e": 315,
"s": 267,
"text": "field_name = models.Field(related_name=\"name\")\n"
},
{
"code": null,
"e": 328,
"s": 315,
"text": "Explanation:"
},
{
"code": null,
"e": 471,
"s": 328,
"text": "Illustration of related_name=”name” using an Example. Consider a project named suorganizer(start up organizer) having an app named organizer."
},
{
"code": null,
"e": 658,
"s": 471,
"text": "Refer to the following articles to check how to create a project and an app in Django.\n\n How to Create a Basic Project using MVT in Django ?\n How to Create an App in Django ?\n\n"
},
{
"code": null,
"e": 721,
"s": 658,
"text": "Enter the following code into models.py file of organizer app."
},
{
"code": null,
"e": 728,
"s": 721,
"text": "Python"
},
{
"code": "from django.db import models # Create your models here. class Tag(models.Model): name = models.CharField(max_length = 31) def __str__(self): return self.name.title() class Post(models.Model): title = models.CharField(max_length = 63) tags = models.ManyToManyField(Tag, related_name ='blog_posts') def __str__(self): return self.title ",
"e": 1120,
"s": 728,
"text": null
},
{
"code": null,
"e": 1307,
"s": 1120,
"text": "After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command."
},
{
"code": null,
"e": 1332,
"s": 1307,
"text": "Python manage.py shell\n\n"
},
{
"code": null,
"e": 1394,
"s": 1332,
"text": "Now let us try to create instance of Tag and Post using None."
},
{
"code": null,
"e": 1904,
"s": 1394,
"text": "# importing required model\nfrom organizer.models import Tag, Post\n\n# creating instance of Tag model\nr = Tag.objects.create(name =\"django\")\nr.save()\n\n# creating instance of Post model\ns = Post.objects.create(title =\"About django\")\ns.save()\n\n# accessing objects\nt = Tag.objects.get(name =\"django\")\np = Post.objects.get(title =\"About django\")\n\n# method1--adding tag to post using post object\np.tags.add(t)\n\n# method2--adding tag to post using tag object\n# which is possible with related_name\nt.blog_posts.add(p)\n"
},
{
"code": null,
"e": 1973,
"s": 1904,
"text": "Let us check in admin interface if the instance of model is created."
},
{
"code": null,
"e": 1988,
"s": 1973,
"text": "1. Tag object:"
},
{
"code": null,
"e": 2002,
"s": 1988,
"text": "2.Post object"
},
{
"code": null,
"e": 2937,
"s": 2002,
"text": "In Django we only ever specify symmetric relations in a single place. The related_name parameter is what defines the other side of a relation. Concretely, given a Post instance p, the tags associated with this post are accessible via p.tags. However, given a Tag instance t, we had not explicitly defined a variable to access Post objects. Thanks to the related_name option, we may now access the list of blog posts related to the tag t via the blog posts attribute, as in t.blog_posts. The related _name parameter is actually an option. If we do not set it, Django automatically creates the other side of the relation for us. In the case of the Tag model, Django would have created a post_set attribute, allowing access via t.post_set in our example. The formula Django uses is the name of the model followed by the string_set. The related name parameter thus simply overrides Django’s default rather than providing new behavior. "
},
{
"code": null,
"e": 2951,
"s": 2937,
"text": "Python Django"
},
{
"code": null,
"e": 2958,
"s": 2951,
"text": "Python"
}
] |
Ruby | Array concat() operation | 08 Jan, 2020
Array#concat() : concat() is a Array class method which returns the array after appending the two arrays together.
Syntax: Array.concat()
Parameter: Arrays to be combined
Return: Append the two arrays
Code #1 : Example for concat() method
# Ruby code for concat() method# adding elements at the end # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [5, 4, nil, 1, 88, 9] # declaring arrayc = [18, 22, nil, 40, 50, 6] # COMBINING TWO ARRAYSputs "combining a and b : #{a.concat(b)}\n\n" puts "combining c and b : #{b.concat(c)}\n\n" puts "combining a and c : #{c.concat(a)}\n\n"
Output :
combining a and b : [18, 22, 33, nil, 5, 6, 5, 4, nil, 1, 88, 9]
combining c and b : [5, 4, nil, 1, 88, 9, 18, 22, nil, 40, 50, 6]
combining a and c : [18, 22, nil, 40, 50, 6, 18, 22, 33, nil, 5, 6, 5, 4, nil, 1, 88, 9]
Code #2 : Example for concat() method
# Ruby code for concat() method# adding elements at the end # declaring arraya = ["abc", "xyz", "dog"] # declaring arrayb = ["cow", "cat", "dog"] # declaring arrayc = ["cat", "1", "dog"] # COMBINING TWO ARRAYSputs "combining a and b : #{a.concat(b)}\n\n" puts "combining c and b : #{b.concat(c)}\n\n" puts "combining a and c : #{c.concat(a)}\n\n"
Output :
combining a and b : ["abc", "xyz", "dog", "cow", "cat", "dog"]
combining c and b : ["cow", "cat", "dog", "cat", "1", "dog"]
combining a and c : ["cat", "1", "dog", "abc", "xyz", "dog", "cow", "cat", "dog"]
Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jan, 2020"
},
{
"code": null,
"e": 143,
"s": 28,
"text": "Array#concat() : concat() is a Array class method which returns the array after appending the two arrays together."
},
{
"code": null,
"e": 235,
"s": 143,
"text": "Syntax: Array.concat()\n\nParameter: Arrays to be combined\n\nReturn: Append the two arrays\n"
},
{
"code": null,
"e": 273,
"s": 235,
"text": "Code #1 : Example for concat() method"
},
{
"code": "# Ruby code for concat() method# adding elements at the end # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [5, 4, nil, 1, 88, 9] # declaring arrayc = [18, 22, nil, 40, 50, 6] # COMBINING TWO ARRAYSputs \"combining a and b : #{a.concat(b)}\\n\\n\" puts \"combining c and b : #{b.concat(c)}\\n\\n\" puts \"combining a and c : #{c.concat(a)}\\n\\n\"",
"e": 633,
"s": 273,
"text": null
},
{
"code": null,
"e": 642,
"s": 633,
"text": "Output :"
},
{
"code": null,
"e": 866,
"s": 642,
"text": "combining a and b : [18, 22, 33, nil, 5, 6, 5, 4, nil, 1, 88, 9]\n\ncombining c and b : [5, 4, nil, 1, 88, 9, 18, 22, nil, 40, 50, 6]\n\ncombining a and c : [18, 22, nil, 40, 50, 6, 18, 22, 33, nil, 5, 6, 5, 4, nil, 1, 88, 9]\n\n"
},
{
"code": null,
"e": 904,
"s": 866,
"text": "Code #2 : Example for concat() method"
},
{
"code": "# Ruby code for concat() method# adding elements at the end # declaring arraya = [\"abc\", \"xyz\", \"dog\"] # declaring arrayb = [\"cow\", \"cat\", \"dog\"] # declaring arrayc = [\"cat\", \"1\", \"dog\"] # COMBINING TWO ARRAYSputs \"combining a and b : #{a.concat(b)}\\n\\n\" puts \"combining c and b : #{b.concat(c)}\\n\\n\" puts \"combining a and c : #{c.concat(a)}\\n\\n\"",
"e": 1257,
"s": 904,
"text": null
},
{
"code": null,
"e": 1266,
"s": 1257,
"text": "Output :"
},
{
"code": null,
"e": 1475,
"s": 1266,
"text": "combining a and b : [\"abc\", \"xyz\", \"dog\", \"cow\", \"cat\", \"dog\"]\n\ncombining c and b : [\"cow\", \"cat\", \"dog\", \"cat\", \"1\", \"dog\"]\n\ncombining a and c : [\"cat\", \"1\", \"dog\", \"abc\", \"xyz\", \"dog\", \"cow\", \"cat\", \"dog\"]\n"
},
{
"code": null,
"e": 1492,
"s": 1475,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 1509,
"s": 1492,
"text": "Ruby Collections"
},
{
"code": null,
"e": 1522,
"s": 1509,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1527,
"s": 1522,
"text": "Ruby"
}
] |
Swift – Difference Between Function and Method | 06 Dec, 2021
Some folks use function and method interchangeably and they think function and method are the same in swift. But, function and method both are different things and both have their advantages. In the code, Both function and method can be used again but methods are one of these: classes, structs, and enums part, whereas functions do not belong to any classes, structs, and enums. In short, a method is a function that is associated with a type, that is, a class, a struct, or an enum. We can also think in this: Every method is also a function, but not every function is also a method. Swift uses the “func” keyword for both methods and functions. This is a bit complicated but we will see the clear difference between function and method in this post.
Functions: Functions are chunks of code that do a specific task. There is always a name associated with a function and to call the function we use this name to do some work. Or we can say that a function is a piece of code that is called by name and does a specific task. We can pass data to function as an argument and the function can also return data that is the return value of the function. A particular type should not be associated with the functions. Files that are outside of a particular type can also get this function if it is a global function. We pass all data to function is explicitly passed.
Syntax:
func function_name(parameters) -> returnType{
// Body of the function
}
Example:
Swift
// Swift program to illustrate function // Functionfunc gfg() { print("Hello GeeksforGeeks")} // Calling functiongfg()
Output:
Hello GeeksforGeeks
Methods: Method is the function that is associated with a particular type. The instance method can be defined by structures, enumerations, and classes. It encapsulates particular work and functionality for running with an instance of a given particular type. We call the method from the name which is associated with its object. we can determine the work required to gradually improve essential components or the whole system code using the swift method. It is also used to examine the big and complicated legacy system. Below are the two types of methods:
Instance methods
Type Methods
Swift supports Instance methods and Type Methods. Instance methods can only be invoked by an instance of the type. If we try to access the instance method with different objects, then the compiler will give an error. A type method is prefixed with the static or class keyword in swift. A type method is also the type itself.
However, the behavior of local names and external names in swift is not the same for methods and functions. In a method, the first parameter name is given by swift by default. And by default, gives the second and following next parameters are used for both local and external parameter names.
Syntax:
func method_name(parameters){
// Body of the method
}
Example:
In the below code, we create two methods. Here, learn() is the example of the instance method and write() is the example of the type method. In the type method, we use the static or class keyword as a prefix. Here we use the static prefix for the write() method. And, you can see we call it using struct name. We call the instance method using the instance of struct Geek().
Swift
// Swift program to illustrate method // Geeks structurestruct Geek{ let speed: Int // Instance method func learn() { print("learning at \(speed) MPH") } // Type method static func write() { print("write in a swift") } } // Driver code // Create Carlet x = Geek(speed: 20) // Instance Methodx.learn() // Type MethodGeek.write()
Output:
learning at 20 MPH
write in a swift
Function
Method
Picked
Difference Between
Swift
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
Difference between Compile-time and Run-time Polymorphism in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
Swift - Convert String to Int Swift
Swift - Difference Between Sets and Arrays
Swift - Hello World Program
Swift - Properties and its Different Types
Swift - Iterate Arrays and Dictionaries | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 806,
"s": 53,
"text": "Some folks use function and method interchangeably and they think function and method are the same in swift. But, function and method both are different things and both have their advantages. In the code, Both function and method can be used again but methods are one of these: classes, structs, and enums part, whereas functions do not belong to any classes, structs, and enums. In short, a method is a function that is associated with a type, that is, a class, a struct, or an enum. We can also think in this: Every method is also a function, but not every function is also a method. Swift uses the “func” keyword for both methods and functions. This is a bit complicated but we will see the clear difference between function and method in this post."
},
{
"code": null,
"e": 1416,
"s": 806,
"text": "Functions: Functions are chunks of code that do a specific task. There is always a name associated with a function and to call the function we use this name to do some work. Or we can say that a function is a piece of code that is called by name and does a specific task. We can pass data to function as an argument and the function can also return data that is the return value of the function. A particular type should not be associated with the functions. Files that are outside of a particular type can also get this function if it is a global function. We pass all data to function is explicitly passed. "
},
{
"code": null,
"e": 1424,
"s": 1416,
"text": "Syntax:"
},
{
"code": null,
"e": 1500,
"s": 1424,
"text": "func function_name(parameters) -> returnType{\n // Body of the function\n}"
},
{
"code": null,
"e": 1509,
"s": 1500,
"text": "Example:"
},
{
"code": null,
"e": 1515,
"s": 1509,
"text": "Swift"
},
{
"code": "// Swift program to illustrate function // Functionfunc gfg() { print(\"Hello GeeksforGeeks\")} // Calling functiongfg()",
"e": 1641,
"s": 1515,
"text": null
},
{
"code": null,
"e": 1649,
"s": 1641,
"text": "Output:"
},
{
"code": null,
"e": 1669,
"s": 1649,
"text": "Hello GeeksforGeeks"
},
{
"code": null,
"e": 2227,
"s": 1669,
"text": "Methods: Method is the function that is associated with a particular type. The instance method can be defined by structures, enumerations, and classes. It encapsulates particular work and functionality for running with an instance of a given particular type. We call the method from the name which is associated with its object. we can determine the work required to gradually improve essential components or the whole system code using the swift method. It is also used to examine the big and complicated legacy system. Below are the two types of methods: "
},
{
"code": null,
"e": 2244,
"s": 2227,
"text": "Instance methods"
},
{
"code": null,
"e": 2257,
"s": 2244,
"text": "Type Methods"
},
{
"code": null,
"e": 2582,
"s": 2257,
"text": "Swift supports Instance methods and Type Methods. Instance methods can only be invoked by an instance of the type. If we try to access the instance method with different objects, then the compiler will give an error. A type method is prefixed with the static or class keyword in swift. A type method is also the type itself."
},
{
"code": null,
"e": 2876,
"s": 2582,
"text": "However, the behavior of local names and external names in swift is not the same for methods and functions. In a method, the first parameter name is given by swift by default. And by default, gives the second and following next parameters are used for both local and external parameter names. "
},
{
"code": null,
"e": 2884,
"s": 2876,
"text": "Syntax:"
},
{
"code": null,
"e": 2942,
"s": 2884,
"text": "func method_name(parameters){\n // Body of the method\n}"
},
{
"code": null,
"e": 2951,
"s": 2942,
"text": "Example:"
},
{
"code": null,
"e": 3327,
"s": 2951,
"text": "In the below code, we create two methods. Here, learn() is the example of the instance method and write() is the example of the type method. In the type method, we use the static or class keyword as a prefix. Here we use the static prefix for the write() method. And, you can see we call it using struct name. We call the instance method using the instance of struct Geek(). "
},
{
"code": null,
"e": 3333,
"s": 3327,
"text": "Swift"
},
{
"code": "// Swift program to illustrate method // Geeks structurestruct Geek{ let speed: Int // Instance method func learn() { print(\"learning at \\(speed) MPH\") } // Type method static func write() { print(\"write in a swift\") } } // Driver code // Create Carlet x = Geek(speed: 20) // Instance Methodx.learn() // Type MethodGeek.write()",
"e": 3717,
"s": 3333,
"text": null
},
{
"code": null,
"e": 3725,
"s": 3717,
"text": "Output:"
},
{
"code": null,
"e": 3761,
"s": 3725,
"text": "learning at 20 MPH\nwrite in a swift"
},
{
"code": null,
"e": 3770,
"s": 3761,
"text": "Function"
},
{
"code": null,
"e": 3777,
"s": 3770,
"text": "Method"
},
{
"code": null,
"e": 3784,
"s": 3777,
"text": "Picked"
},
{
"code": null,
"e": 3803,
"s": 3784,
"text": "Difference Between"
},
{
"code": null,
"e": 3809,
"s": 3803,
"text": "Swift"
},
{
"code": null,
"e": 3907,
"s": 3809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3968,
"s": 3907,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4036,
"s": 3968,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 4102,
"s": 4036,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 4151,
"s": 4102,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 4206,
"s": 4151,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 4242,
"s": 4206,
"text": "Swift - Convert String to Int Swift"
},
{
"code": null,
"e": 4285,
"s": 4242,
"text": "Swift - Difference Between Sets and Arrays"
},
{
"code": null,
"e": 4313,
"s": 4285,
"text": "Swift - Hello World Program"
},
{
"code": null,
"e": 4356,
"s": 4313,
"text": "Swift - Properties and its Different Types"
}
] |
Delete the array elements in JavaScript | delete vs splice | 18 May, 2019
For deletion of elements in an array, two approaches can be used. They have their own merits regarding the way they perform the deletion.
Using delete array[index]:
This method deletes the element at the index specified, but does not modify the array. This means that at the place of the deleted index, the element is left undefined or null. This may cause problems when iterating through the array as the deleted index does not hold any value. The length of the array in this case remains the same.
Syntax:
delete array[index]
Example:
<!DOCTYPE html><html><head> <title> Deleting array elements in JavaScript – delete vs splice </title></head><body> <h1 style="color: green">GeeksforGeeks</h1> <b>Deleting array elements in JavaScript – delete vs splice</b> <p>Click on the button below to delete an element.</p> <p>Original array is: 1, 2, 3, 4, 5, 6</p> <p>New array is: <span class="output"></span></p> <button onclick="deleteElement()">Click to delete</button> <script> function deleteElement() { array = [1, 2, 3, 4, 5, 6]; index = 2; delete array[index]; console.log(array); document.querySelector('.output').textContent = array; } </script></body></html>
Output:
Display:
Console:
Using the splice method:
The array.splice() method is used to add or remove items from an array. This method takes in 3 parameters, the index where the element’s id is to be inserted or removed, the number of items to be deleted and the new items which are to be inserted.
This method actually deletes the element at index and shifts the remaining elements leaving no empty index. This is useful as the array left after deletion can be iterated normally and displayed properly. The length of the array decreases using this method.
Syntax:
array.splice(index, items_to_remove, item1 ... itemX)
Example:
<!DOCTYPE html><html><head> <title> Deleting array elements in JavaScript – delete vs splice </title></head><body> <h1 style="color: green">GeeksforGeeks</h1> <b>Deleting array elements in JavaScript – delete vs splice</b> <p>Click on the button below to delete an element.</p> <p>Original array is: 1, 2, 3, 4, 5, 6</p> <p>New array is: <span class="output"></span></p> <button onclick="deleteElement()">Click to delete</button> <script> function deleteElement() { array = [1, 2, 3, 4, 5, 6]; index = 2; array.splice(index, 1); console.log(array); document.querySelector('.output').textContent = array; } </script></body></html>
Output:
Before clicking the button:
After clicking the button:
javascript-array
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 May, 2019"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "For deletion of elements in an array, two approaches can be used. They have their own merits regarding the way they perform the deletion."
},
{
"code": null,
"e": 193,
"s": 166,
"text": "Using delete array[index]:"
},
{
"code": null,
"e": 528,
"s": 193,
"text": "This method deletes the element at the index specified, but does not modify the array. This means that at the place of the deleted index, the element is left undefined or null. This may cause problems when iterating through the array as the deleted index does not hold any value. The length of the array in this case remains the same."
},
{
"code": null,
"e": 536,
"s": 528,
"text": "Syntax:"
},
{
"code": null,
"e": 556,
"s": 536,
"text": "delete array[index]"
},
{
"code": null,
"e": 565,
"s": 556,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head> <title> Deleting array elements in JavaScript – delete vs splice </title></head><body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>Deleting array elements in JavaScript – delete vs splice</b> <p>Click on the button below to delete an element.</p> <p>Original array is: 1, 2, 3, 4, 5, 6</p> <p>New array is: <span class=\"output\"></span></p> <button onclick=\"deleteElement()\">Click to delete</button> <script> function deleteElement() { array = [1, 2, 3, 4, 5, 6]; index = 2; delete array[index]; console.log(array); document.querySelector('.output').textContent = array; } </script></body></html>",
"e": 1310,
"s": 565,
"text": null
},
{
"code": null,
"e": 1318,
"s": 1310,
"text": "Output:"
},
{
"code": null,
"e": 1327,
"s": 1318,
"text": "Display:"
},
{
"code": null,
"e": 1336,
"s": 1327,
"text": "Console:"
},
{
"code": null,
"e": 1361,
"s": 1336,
"text": "Using the splice method:"
},
{
"code": null,
"e": 1609,
"s": 1361,
"text": "The array.splice() method is used to add or remove items from an array. This method takes in 3 parameters, the index where the element’s id is to be inserted or removed, the number of items to be deleted and the new items which are to be inserted."
},
{
"code": null,
"e": 1867,
"s": 1609,
"text": "This method actually deletes the element at index and shifts the remaining elements leaving no empty index. This is useful as the array left after deletion can be iterated normally and displayed properly. The length of the array decreases using this method."
},
{
"code": null,
"e": 1875,
"s": 1867,
"text": "Syntax:"
},
{
"code": null,
"e": 1929,
"s": 1875,
"text": "array.splice(index, items_to_remove, item1 ... itemX)"
},
{
"code": null,
"e": 1938,
"s": 1929,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head> <title> Deleting array elements in JavaScript – delete vs splice </title></head><body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>Deleting array elements in JavaScript – delete vs splice</b> <p>Click on the button below to delete an element.</p> <p>Original array is: 1, 2, 3, 4, 5, 6</p> <p>New array is: <span class=\"output\"></span></p> <button onclick=\"deleteElement()\">Click to delete</button> <script> function deleteElement() { array = [1, 2, 3, 4, 5, 6]; index = 2; array.splice(index, 1); console.log(array); document.querySelector('.output').textContent = array; } </script></body></html>",
"e": 2686,
"s": 1938,
"text": null
},
{
"code": null,
"e": 2694,
"s": 2686,
"text": "Output:"
},
{
"code": null,
"e": 2722,
"s": 2694,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 2749,
"s": 2722,
"text": "After clicking the button:"
},
{
"code": null,
"e": 2766,
"s": 2749,
"text": "javascript-array"
},
{
"code": null,
"e": 2773,
"s": 2766,
"text": "Picked"
},
{
"code": null,
"e": 2784,
"s": 2773,
"text": "JavaScript"
},
{
"code": null,
"e": 2801,
"s": 2784,
"text": "Web Technologies"
},
{
"code": null,
"e": 2899,
"s": 2801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2960,
"s": 2899,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3032,
"s": 2960,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3072,
"s": 3032,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3113,
"s": 3072,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3165,
"s": 3113,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3198,
"s": 3165,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3260,
"s": 3198,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3321,
"s": 3260,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3371,
"s": 3321,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Pandas Dataframe.to_numpy() – Convert dataframe to Numpy array | 27 Feb, 2020
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of Dataframe.to_numpy() method.
Syntax: Dataframe.to_numpy(dtype = None, copy = False)
Parameters:dtype: Data type which we are passing like str.copy: [bool, default False] Ensures that the returned value is a not a view on another array.
Returns:numpy.ndarray
To get the link to csv file, click on nba.csv
Example 1: Changing the DataFrame into numpy array by using a method DataFrame.to_numpy(). Always remember that when dealing with lot of data you should clean the data first to get the high accuracy. Although in this code we use the first five values of Weight column by using .head() method.
# importing pandasimport pandas as pd # reading the csv data = pd.read_csv("nba.csv") data.dropna(inplace = True) # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head()) # using to_numpy() functionprint(gfg.to_numpy())
Output:
[[180.]
[235.]
[185.]
[235.]
[238.]]
Example 2: In this code we are just giving the parameters in the same code. So we provide the dtype here.
# importing pandasimport pandas as pd # read csv file data = pd.read_csv("nba.csv") data.dropna(inplace = True) # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head()) # providing dtypeprint(gfg.to_numpy(dtype ='float32'))
Output:
[[180.]
[235.]
[185.]
[235.]
[238.]]
Example 3: Validating the type of the array after conversion.
# importing pandas import pandas as pd # reading csv data = pd.read_csv("nba.csv") data.dropna(inplace = True) # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head()) # using to_numpy()print(type(gfg.to_numpy()))
Output:
<class 'numpy.ndarray'>
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 265,
"s": 28,
"text": "Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of Dataframe.to_numpy() method."
},
{
"code": null,
"e": 320,
"s": 265,
"text": "Syntax: Dataframe.to_numpy(dtype = None, copy = False)"
},
{
"code": null,
"e": 472,
"s": 320,
"text": "Parameters:dtype: Data type which we are passing like str.copy: [bool, default False] Ensures that the returned value is a not a view on another array."
},
{
"code": null,
"e": 494,
"s": 472,
"text": "Returns:numpy.ndarray"
},
{
"code": null,
"e": 540,
"s": 494,
"text": "To get the link to csv file, click on nba.csv"
},
{
"code": null,
"e": 833,
"s": 540,
"text": "Example 1: Changing the DataFrame into numpy array by using a method DataFrame.to_numpy(). Always remember that when dealing with lot of data you should clean the data first to get the high accuracy. Although in this code we use the first five values of Weight column by using .head() method."
},
{
"code": "# importing pandasimport pandas as pd # reading the csv data = pd.read_csv(\"nba.csv\") data.dropna(inplace = True) # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head()) # using to_numpy() functionprint(gfg.to_numpy())",
"e": 1091,
"s": 833,
"text": null
},
{
"code": null,
"e": 1099,
"s": 1091,
"text": "Output:"
},
{
"code": null,
"e": 1140,
"s": 1099,
"text": "[[180.]\n [235.]\n [185.]\n [235.]\n [238.]]"
},
{
"code": null,
"e": 1246,
"s": 1140,
"text": "Example 2: In this code we are just giving the parameters in the same code. So we provide the dtype here."
},
{
"code": "# importing pandasimport pandas as pd # read csv file data = pd.read_csv(\"nba.csv\") data.dropna(inplace = True) # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head()) # providing dtypeprint(gfg.to_numpy(dtype ='float32'))",
"e": 1508,
"s": 1246,
"text": null
},
{
"code": null,
"e": 1516,
"s": 1508,
"text": "Output:"
},
{
"code": null,
"e": 1557,
"s": 1516,
"text": "[[180.]\n [235.]\n [185.]\n [235.]\n [238.]]"
},
{
"code": null,
"e": 1619,
"s": 1557,
"text": "Example 3: Validating the type of the array after conversion."
},
{
"code": "# importing pandas import pandas as pd # reading csv data = pd.read_csv(\"nba.csv\") data.dropna(inplace = True) # creating DataFrame form weight columngfg = pd.DataFrame(data['Weight'].head()) # using to_numpy()print(type(gfg.to_numpy()))",
"e": 1871,
"s": 1619,
"text": null
},
{
"code": null,
"e": 1879,
"s": 1871,
"text": "Output:"
},
{
"code": null,
"e": 1903,
"s": 1879,
"text": "<class 'numpy.ndarray'>"
},
{
"code": null,
"e": 1927,
"s": 1903,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1941,
"s": 1927,
"text": "Python-pandas"
},
{
"code": null,
"e": 1948,
"s": 1941,
"text": "Python"
},
{
"code": null,
"e": 2046,
"s": 1948,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2064,
"s": 2046,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2106,
"s": 2064,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2128,
"s": 2106,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2163,
"s": 2128,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2189,
"s": 2163,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2221,
"s": 2189,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2250,
"s": 2221,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2277,
"s": 2250,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2307,
"s": 2277,
"text": "Iterate over a list in Python"
}
] |
How to develop a Progressive Web App using ReactJS ? | 22 Sep, 2021
Progressive React Applications respond very fast to user actions. They load fast and are engaging just like a mobile app. They can access Mobile device features, leverage the Operating System and have a very high reach. It enables Installability, Backgroung Syncing, Caching and Offline Support and other features like Push Notifications. With React, we can very easily enhance web apps progressively to look and feel like native mobile applications.
Now let’s see step-by-step implementation on how to develop a Progressive Web Application using React.
Step 1: With ReactJS, it is even easier to create a Progressive Web App or even convert an existing React project into one. In the terminal of your text editor, enter the following command. CRA creates a boilerplate for Progressive Web App that you can easily modify according to your needs.
npx create-react-app react-pwa –template cra-template-pwa
cd react-pwa
This command creates a new React Application named react-pwa and navigates to the directory of your app. You can further modify your manifest.json file and other files like the logo to customize the app and make it your own.
Step 2: Let’s implement the functionalities of a PWA and add more features to our App. In the terminal of your text editor enter the following command to install some third-party and npm packages.
npm install –save web-push react-router-dom bootstrap react-bootstrap
Project Structure: Add worker.js and feed.js in your public folder and a components folder inside your src folder, so that it looks like this.
Project Structure
Step 3: Register a Service Worker – A Service Worker is a special kind of script file that works between the browser and the network. It helps us to perform unique functionalities and registers itself whenever a page is loaded. To register a new service worker in your React App, in the worker.js file in your public folder (public/worker.js), add the following code.
Javascript
var STATIC_CACHE_NAME = "gfg-pwa";var DYNAMIC_CACHE_NAME = "dynamic-gfg-pwa"; // Add Routes and pages using React Browser Routervar urlsToCache = ["/", "/search", "/aboutus", "/profile"]; // Install a service workerself.addEventListener("install", (event) => { // Perform install steps event.waitUntil( caches.open(STATIC_CACHE_NAME).then(function (cache) { console.log("Opened cache"); return cache.addAll(urlsToCache); }) );}); // Cache and return requestsself.addEventListener("fetch", (event) => { event.respondWith( caches.match(event.request).then((cacheRes) => { // If the file is not present in STATIC_CACHE, // it will be searched in DYNAMIC_CACHE return ( cacheRes || fetch(event.request).then((fetchRes) => { return caches.open(DYNAMIC_CACHE_NAME).then((cache) => { cache.put(event.request.url, fetchRes.clone()); return fetchRes; }); }) ); }) );}); // Update a service workerself.addEventListener("activate", (event) => { var cacheWhitelist = ["gfg-pwa"]; event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames.map((cacheName) => { if (cacheWhitelist.indexOf(cacheName) === -1) { return caches.delete(cacheName); } }) ); }) );});
Step 4: Some old browsers may not support service workers. However, most modern browsers like Google Chrome have in-built support for service workers. In case of the absence of support, the app will run like a normal web application. To make sure that we don’t run into an error or the app doesn’t crash, we need to check whether the support status of service workers in the browser of the client. To do so, update your index.html file in the public folder (public/index.html) with the following code.
Javascript
<script> if ("serviceWorker" in navigator) { window.addEventListener("load", function () { navigator.serviceWorker .register("/worker.js") .then( function (registration) { console.log( "Worker registration successful", registration.scope); }, function (err) { console.log("Worker registration failed", err); } ) .catch(function (err) { console.log(err); }); }); } else { console.log("Service Worker is not" + " supported by browser."); }</script>
Step 5: Now, that we have the code for the basic functionalities of a service worker. We need to register it. To do so, change one line in index.js in the src folder (src/index.js) from
service-worker.unregister()
to
serviceWorker.register()
Our service worker i.e. worker.js will now successfully register itself.
Step to run the application: Now, enter the following command in the terminal of your text editor.
npm start
Output: This will open your React App in the localhost://3000 in the browser. And, in ṯhe Dev Tools, under Application Tab, you can see that your service worker is registered with a “Worker registration successful” message in your console.
Service Worker Registered
Explanation: We now have the basic service worker functioning just the way we want it to. To implement other native device-like features, let us implement to send a notification in case the user goes offline while using the app. Also, to see your new features, there is no need to run the app again, just clicking on reload button will do the trick.
Step 6: Sending a Push Notification when Offline – Push Notifications are a native mobile feature. And the browser will automatically ask for user permission in default settings. Web-push is a third-party package that will aid us with VAPID keys to push a notification. Now, we need to have a VAPID API Key to start implementing Push notifications in our App. Note that every VAPID API KEY is unique for every service worker.
To generate the API Keys, type the following in the terminal:
./node_modules/.bin/web-push generate-vapid-keys
Now, in the terminal of your text editor, web-push provides two of your own vapid keys. We are going to use the public vapid key to generate push notifications.
Modify the script in index.html. This will encode your base64 string VAPID API KEY and connect it with the service worker so that it is able to send notifications.
Javascript
<script> if ("serviceWorker" in navigator) { function urlBase64ToUint8Array(base64String) { const padding = "=".repeat((4 - (base64String.length % 4)) % 4); const base64 = (base64String + padding) .replace(/\-/g, "+") .replace(/_/g, "/"); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } function determineAppServerKey() { var vapidPublicKey = "YOUR_PUBLIC_KEY"; return urlBase64ToUint8Array(vapidPublicKey); } window.addEventListener("load", function () { navigator.serviceWorker .register("/worker.js") .then( function (registration) { console.log( "Worker registration successful", registration.scope ); return registration.pushManager .getSubscription() .then(function (subscription) { registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: determineAppServerKey(), }); }); }, function (err) { console.log("Worker registration failed", err); } ) .catch(function (err) { console.log(err); }); }); } else { console.log("Service Worker is not supported by browser."); }</script>
Step 7: Let’s use this new functionality to send push notifications whenever we go offline. In worker.js modify the fetch event and add the following code. Inside the show notification function, you can add more properties and modify them according to your wishes.
Javascript
self.addEventListener("fetch", (event) => { event.respondWith( caches.match(event.request).then((cacheRes) => { return ( cacheRes || fetch(event.request).then((fetchRes) => { return caches.open(DYNAMIC_CACHE_NAME) .then((cache) => { cache.put(event.request.url, fetchRes.clone()); return fetchRes; }); }) ); }) ); if (!navigator.onLine) { if (event.request.url === "http://localhost:3000/static/js/main.chunk.js") { event.waitUntil( self.registration.showNotification("Internet", { body: "internet not working", icon: "logo.png", }) ); } }});
The self.registration.showNotification function shows the desired notification and even asks for permission before showing one.
Step 8: To check that Syncing and Caching work when offline, you can change the status above your Service Worker in Dev Tools to ‘offline’ or do the same above the app. Now, whenever you go offline, you will see a push notification indicating that you went offline.
Push Notification: Internet Not Working
Note that you are still able to see the pages though some functionalities might be lost. This is because these default pages and URLs once visited get stored in the cache. So, make sure to unregister and register it again under the Application Tab every time you make changes in your files during development.
Step 9: Adding Native Features like Camera and Geolocation – PWA enables using native features like accessing the webcam and figuring out location with the help of service workers. Let’s start with creating the UI for this first where we can use these functionalities, create a Profile.js file in ‘src/Profile.js’ which we can navigate to via /profile using React Routes.
Javascript
import React from "react";import { InputGroup, Button, Container } from "react-bootstrap"; const Profile = () => { return ( <> <Container className={style.styling}> <br></br> <InputGroup className="mb-3"> <InputGroup.Text>Latitude</InputGroup.Text> <InputGroup.Text id="latitude">00</InputGroup.Text> </InputGroup> <br></br> <InputGroup className="mb-3"> <InputGroup.Text>Longitude</InputGroup.Text> <InputGroup.Text id="longitude">00</InputGroup.Text> </InputGroup> <br></br> <InputGroup className="mb-3"> <InputGroup.Text>Location</InputGroup.Text> </InputGroup> <Button variant="outline-secondary" id="locationBtn"> Get Location </Button> <br></br> <br></br> <Button variant="outline-secondary" id="photoBtn"> Take a Picture Now! </Button> <video id="player" autoPlay width="320px" height="240px"></video> <canvas id="canvas" width="320px" height="240px" style={{ display: "none" }} ></canvas> <Button variant="outline-secondary" id="capture"> Capture </Button> <br></br> <div id="pick-image"> <h6>Pick an Image instead</h6> <input type="file" accept="image/*" id="image-picker"></input> </div> <br></br> <br></br> </Container> </> );}; export default Profile;
Step 10: Now let’s add a feed.js file in public/feed.js to implement the functionality of location and camera.
Javascript
window.onload = function () { var photo = document.getElementById("photoBtn"); var locationBtn = document.getElementById("locationBtn"); locationBtn.addEventListener("click", handler); var capture = document.getElementById("capture"); photo.addEventListener("click", initializeMedia); capture.addEventListener("click", takepic);}; function initializeLocation() { if (!("geolocation" in navigator)) { locationBtn.style.display = "none"; }} function handler(event) { if (!("geolocation" in navigator)) { return; } navigator.geolocation.getCurrentPosition( function (position) { console.log(position); var lat = position.coords.latitude; var lon = position.coords.longitude; console.log(lat); console.log(lon); latitude.innerHTML = lat; longitude.innerHTML = lon; });} function initializeMedia() { if (!("mediaDevices" in navigator)) { navigator.mediaDevices = {}; } if (!("getUserMedia" in navigator.mediaDevices)) { navigator.mediaDevices.getUserMedia = function (constraints) { var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (!getUserMedia) { return Promise.reject(new Error( "getUserMedia is not implemented!")); } return new Promise(function (resolve, reject) { getUserMedia.call(navigator, constraints, resolve, reject); }); }; } navigator.mediaDevices .getUserMedia({ video: true }) .then(function (stream) { player.srcObject = stream; player.style.display = "block"; }) .catch(function (err) { console.log(err); imagePicker.style.display = "block"; });} function takepic(event) { canvas.style.display = "block"; player.style.display = "none"; capture.style.display = "none"; var context = canvas.getContext("2d"); context.drawImage( player, 0, 0, canvas.width, player.videoHeight / (player.videoWidth / canvas.width) ); player.srcObject.getVideoTracks().forEach(function (track) { track.stop(); });}
Step 11: Create a new file called feed.js in the (/src/public) folder. In feed.js, we use geolocation and mediaDevices to implement functionalities of location and camera respectively. You can also use the Google Geocoder API to convert these latitudes and longitudes into the name of a place.
Output: You can now navigate to localhost:3000/profile to take your picture and get the location.
Native Features Enabled
Explanation: Clicking on the Get Location button will trigger the navigator.geolocation.getCurrentPosition inside the handler function thereby populating the latitude and longitude fields with appropriate values. To get the exact name of the city, try using the Geocoder API as mentioned above. Similarly, clicking on the Take a Picture, Now Button will trigger the navigator.mediaDevices.getUserMedia inside the initializeMedia function thereby opening the front camera and taking a picture. Both these functions will first add for permissions and then execute themselves.
Blogathon-2021
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
Shared ViewModel in Android
How to fetch data from an API in ReactJS ?
Axios in React: A Guide for Beginners
How to redirect to another page in ReactJS ?
ReactJS Functional Components | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 505,
"s": 54,
"text": "Progressive React Applications respond very fast to user actions. They load fast and are engaging just like a mobile app. They can access Mobile device features, leverage the Operating System and have a very high reach. It enables Installability, Backgroung Syncing, Caching and Offline Support and other features like Push Notifications. With React, we can very easily enhance web apps progressively to look and feel like native mobile applications."
},
{
"code": null,
"e": 608,
"s": 505,
"text": "Now let’s see step-by-step implementation on how to develop a Progressive Web Application using React."
},
{
"code": null,
"e": 900,
"s": 608,
"text": "Step 1: With ReactJS, it is even easier to create a Progressive Web App or even convert an existing React project into one. In the terminal of your text editor, enter the following command. CRA creates a boilerplate for Progressive Web App that you can easily modify according to your needs."
},
{
"code": null,
"e": 958,
"s": 900,
"text": "npx create-react-app react-pwa –template cra-template-pwa"
},
{
"code": null,
"e": 971,
"s": 958,
"text": "cd react-pwa"
},
{
"code": null,
"e": 1196,
"s": 971,
"text": "This command creates a new React Application named react-pwa and navigates to the directory of your app. You can further modify your manifest.json file and other files like the logo to customize the app and make it your own."
},
{
"code": null,
"e": 1393,
"s": 1196,
"text": "Step 2: Let’s implement the functionalities of a PWA and add more features to our App. In the terminal of your text editor enter the following command to install some third-party and npm packages."
},
{
"code": null,
"e": 1463,
"s": 1393,
"text": "npm install –save web-push react-router-dom bootstrap react-bootstrap"
},
{
"code": null,
"e": 1606,
"s": 1463,
"text": "Project Structure: Add worker.js and feed.js in your public folder and a components folder inside your src folder, so that it looks like this."
},
{
"code": null,
"e": 1624,
"s": 1606,
"text": "Project Structure"
},
{
"code": null,
"e": 1992,
"s": 1624,
"text": "Step 3: Register a Service Worker – A Service Worker is a special kind of script file that works between the browser and the network. It helps us to perform unique functionalities and registers itself whenever a page is loaded. To register a new service worker in your React App, in the worker.js file in your public folder (public/worker.js), add the following code."
},
{
"code": null,
"e": 2003,
"s": 1992,
"text": "Javascript"
},
{
"code": "var STATIC_CACHE_NAME = \"gfg-pwa\";var DYNAMIC_CACHE_NAME = \"dynamic-gfg-pwa\"; // Add Routes and pages using React Browser Routervar urlsToCache = [\"/\", \"/search\", \"/aboutus\", \"/profile\"]; // Install a service workerself.addEventListener(\"install\", (event) => { // Perform install steps event.waitUntil( caches.open(STATIC_CACHE_NAME).then(function (cache) { console.log(\"Opened cache\"); return cache.addAll(urlsToCache); }) );}); // Cache and return requestsself.addEventListener(\"fetch\", (event) => { event.respondWith( caches.match(event.request).then((cacheRes) => { // If the file is not present in STATIC_CACHE, // it will be searched in DYNAMIC_CACHE return ( cacheRes || fetch(event.request).then((fetchRes) => { return caches.open(DYNAMIC_CACHE_NAME).then((cache) => { cache.put(event.request.url, fetchRes.clone()); return fetchRes; }); }) ); }) );}); // Update a service workerself.addEventListener(\"activate\", (event) => { var cacheWhitelist = [\"gfg-pwa\"]; event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames.map((cacheName) => { if (cacheWhitelist.indexOf(cacheName) === -1) { return caches.delete(cacheName); } }) ); }) );});",
"e": 3353,
"s": 2003,
"text": null
},
{
"code": null,
"e": 3855,
"s": 3353,
"text": "Step 4: Some old browsers may not support service workers. However, most modern browsers like Google Chrome have in-built support for service workers. In case of the absence of support, the app will run like a normal web application. To make sure that we don’t run into an error or the app doesn’t crash, we need to check whether the support status of service workers in the browser of the client. To do so, update your index.html file in the public folder (public/index.html) with the following code."
},
{
"code": null,
"e": 3868,
"s": 3857,
"text": "Javascript"
},
{
"code": "<script> if (\"serviceWorker\" in navigator) { window.addEventListener(\"load\", function () { navigator.serviceWorker .register(\"/worker.js\") .then( function (registration) { console.log( \"Worker registration successful\", registration.scope); }, function (err) { console.log(\"Worker registration failed\", err); } ) .catch(function (err) { console.log(err); }); }); } else { console.log(\"Service Worker is not\" + \" supported by browser.\"); }</script>",
"e": 4467,
"s": 3868,
"text": null
},
{
"code": null,
"e": 4653,
"s": 4467,
"text": "Step 5: Now, that we have the code for the basic functionalities of a service worker. We need to register it. To do so, change one line in index.js in the src folder (src/index.js) from"
},
{
"code": null,
"e": 4681,
"s": 4653,
"text": "service-worker.unregister()"
},
{
"code": null,
"e": 4684,
"s": 4681,
"text": "to"
},
{
"code": null,
"e": 4709,
"s": 4684,
"text": "serviceWorker.register()"
},
{
"code": null,
"e": 4782,
"s": 4709,
"text": "Our service worker i.e. worker.js will now successfully register itself."
},
{
"code": null,
"e": 4881,
"s": 4782,
"text": "Step to run the application: Now, enter the following command in the terminal of your text editor."
},
{
"code": null,
"e": 4891,
"s": 4881,
"text": "npm start"
},
{
"code": null,
"e": 5132,
"s": 4891,
"text": "Output: This will open your React App in the localhost://3000 in the browser. And, in ṯhe Dev Tools, under Application Tab, you can see that your service worker is registered with a “Worker registration successful” message in your console."
},
{
"code": null,
"e": 5158,
"s": 5132,
"text": "Service Worker Registered"
},
{
"code": null,
"e": 5508,
"s": 5158,
"text": "Explanation: We now have the basic service worker functioning just the way we want it to. To implement other native device-like features, let us implement to send a notification in case the user goes offline while using the app. Also, to see your new features, there is no need to run the app again, just clicking on reload button will do the trick."
},
{
"code": null,
"e": 5934,
"s": 5508,
"text": "Step 6: Sending a Push Notification when Offline – Push Notifications are a native mobile feature. And the browser will automatically ask for user permission in default settings. Web-push is a third-party package that will aid us with VAPID keys to push a notification. Now, we need to have a VAPID API Key to start implementing Push notifications in our App. Note that every VAPID API KEY is unique for every service worker."
},
{
"code": null,
"e": 5996,
"s": 5934,
"text": "To generate the API Keys, type the following in the terminal:"
},
{
"code": null,
"e": 6045,
"s": 5996,
"text": "./node_modules/.bin/web-push generate-vapid-keys"
},
{
"code": null,
"e": 6206,
"s": 6045,
"text": "Now, in the terminal of your text editor, web-push provides two of your own vapid keys. We are going to use the public vapid key to generate push notifications."
},
{
"code": null,
"e": 6370,
"s": 6206,
"text": "Modify the script in index.html. This will encode your base64 string VAPID API KEY and connect it with the service worker so that it is able to send notifications."
},
{
"code": null,
"e": 6381,
"s": 6370,
"text": "Javascript"
},
{
"code": "<script> if (\"serviceWorker\" in navigator) { function urlBase64ToUint8Array(base64String) { const padding = \"=\".repeat((4 - (base64String.length % 4)) % 4); const base64 = (base64String + padding) .replace(/\\-/g, \"+\") .replace(/_/g, \"/\"); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } function determineAppServerKey() { var vapidPublicKey = \"YOUR_PUBLIC_KEY\"; return urlBase64ToUint8Array(vapidPublicKey); } window.addEventListener(\"load\", function () { navigator.serviceWorker .register(\"/worker.js\") .then( function (registration) { console.log( \"Worker registration successful\", registration.scope ); return registration.pushManager .getSubscription() .then(function (subscription) { registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: determineAppServerKey(), }); }); }, function (err) { console.log(\"Worker registration failed\", err); } ) .catch(function (err) { console.log(err); }); }); } else { console.log(\"Service Worker is not supported by browser.\"); }</script>",
"e": 7908,
"s": 6381,
"text": null
},
{
"code": null,
"e": 8173,
"s": 7908,
"text": "Step 7: Let’s use this new functionality to send push notifications whenever we go offline. In worker.js modify the fetch event and add the following code. Inside the show notification function, you can add more properties and modify them according to your wishes."
},
{
"code": null,
"e": 8184,
"s": 8173,
"text": "Javascript"
},
{
"code": "self.addEventListener(\"fetch\", (event) => { event.respondWith( caches.match(event.request).then((cacheRes) => { return ( cacheRes || fetch(event.request).then((fetchRes) => { return caches.open(DYNAMIC_CACHE_NAME) .then((cache) => { cache.put(event.request.url, fetchRes.clone()); return fetchRes; }); }) ); }) ); if (!navigator.onLine) { if (event.request.url === \"http://localhost:3000/static/js/main.chunk.js\") { event.waitUntil( self.registration.showNotification(\"Internet\", { body: \"internet not working\", icon: \"logo.png\", }) ); } }});",
"e": 8873,
"s": 8184,
"text": null
},
{
"code": null,
"e": 9001,
"s": 8873,
"text": "The self.registration.showNotification function shows the desired notification and even asks for permission before showing one."
},
{
"code": null,
"e": 9268,
"s": 9001,
"text": "Step 8: To check that Syncing and Caching work when offline, you can change the status above your Service Worker in Dev Tools to ‘offline’ or do the same above the app. Now, whenever you go offline, you will see a push notification indicating that you went offline. "
},
{
"code": null,
"e": 9308,
"s": 9268,
"text": "Push Notification: Internet Not Working"
},
{
"code": null,
"e": 9618,
"s": 9308,
"text": "Note that you are still able to see the pages though some functionalities might be lost. This is because these default pages and URLs once visited get stored in the cache. So, make sure to unregister and register it again under the Application Tab every time you make changes in your files during development."
},
{
"code": null,
"e": 9990,
"s": 9618,
"text": "Step 9: Adding Native Features like Camera and Geolocation – PWA enables using native features like accessing the webcam and figuring out location with the help of service workers. Let’s start with creating the UI for this first where we can use these functionalities, create a Profile.js file in ‘src/Profile.js’ which we can navigate to via /profile using React Routes."
},
{
"code": null,
"e": 10001,
"s": 9990,
"text": "Javascript"
},
{
"code": "import React from \"react\";import { InputGroup, Button, Container } from \"react-bootstrap\"; const Profile = () => { return ( <> <Container className={style.styling}> <br></br> <InputGroup className=\"mb-3\"> <InputGroup.Text>Latitude</InputGroup.Text> <InputGroup.Text id=\"latitude\">00</InputGroup.Text> </InputGroup> <br></br> <InputGroup className=\"mb-3\"> <InputGroup.Text>Longitude</InputGroup.Text> <InputGroup.Text id=\"longitude\">00</InputGroup.Text> </InputGroup> <br></br> <InputGroup className=\"mb-3\"> <InputGroup.Text>Location</InputGroup.Text> </InputGroup> <Button variant=\"outline-secondary\" id=\"locationBtn\"> Get Location </Button> <br></br> <br></br> <Button variant=\"outline-secondary\" id=\"photoBtn\"> Take a Picture Now! </Button> <video id=\"player\" autoPlay width=\"320px\" height=\"240px\"></video> <canvas id=\"canvas\" width=\"320px\" height=\"240px\" style={{ display: \"none\" }} ></canvas> <Button variant=\"outline-secondary\" id=\"capture\"> Capture </Button> <br></br> <div id=\"pick-image\"> <h6>Pick an Image instead</h6> <input type=\"file\" accept=\"image/*\" id=\"image-picker\"></input> </div> <br></br> <br></br> </Container> </> );}; export default Profile;",
"e": 11517,
"s": 10001,
"text": null
},
{
"code": null,
"e": 11628,
"s": 11517,
"text": "Step 10: Now let’s add a feed.js file in public/feed.js to implement the functionality of location and camera."
},
{
"code": null,
"e": 11639,
"s": 11628,
"text": "Javascript"
},
{
"code": "window.onload = function () { var photo = document.getElementById(\"photoBtn\"); var locationBtn = document.getElementById(\"locationBtn\"); locationBtn.addEventListener(\"click\", handler); var capture = document.getElementById(\"capture\"); photo.addEventListener(\"click\", initializeMedia); capture.addEventListener(\"click\", takepic);}; function initializeLocation() { if (!(\"geolocation\" in navigator)) { locationBtn.style.display = \"none\"; }} function handler(event) { if (!(\"geolocation\" in navigator)) { return; } navigator.geolocation.getCurrentPosition( function (position) { console.log(position); var lat = position.coords.latitude; var lon = position.coords.longitude; console.log(lat); console.log(lon); latitude.innerHTML = lat; longitude.innerHTML = lon; });} function initializeMedia() { if (!(\"mediaDevices\" in navigator)) { navigator.mediaDevices = {}; } if (!(\"getUserMedia\" in navigator.mediaDevices)) { navigator.mediaDevices.getUserMedia = function (constraints) { var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (!getUserMedia) { return Promise.reject(new Error( \"getUserMedia is not implemented!\")); } return new Promise(function (resolve, reject) { getUserMedia.call(navigator, constraints, resolve, reject); }); }; } navigator.mediaDevices .getUserMedia({ video: true }) .then(function (stream) { player.srcObject = stream; player.style.display = \"block\"; }) .catch(function (err) { console.log(err); imagePicker.style.display = \"block\"; });} function takepic(event) { canvas.style.display = \"block\"; player.style.display = \"none\"; capture.style.display = \"none\"; var context = canvas.getContext(\"2d\"); context.drawImage( player, 0, 0, canvas.width, player.videoHeight / (player.videoWidth / canvas.width) ); player.srcObject.getVideoTracks().forEach(function (track) { track.stop(); });}",
"e": 13690,
"s": 11639,
"text": null
},
{
"code": null,
"e": 13984,
"s": 13690,
"text": "Step 11: Create a new file called feed.js in the (/src/public) folder. In feed.js, we use geolocation and mediaDevices to implement functionalities of location and camera respectively. You can also use the Google Geocoder API to convert these latitudes and longitudes into the name of a place."
},
{
"code": null,
"e": 14082,
"s": 13984,
"text": "Output: You can now navigate to localhost:3000/profile to take your picture and get the location."
},
{
"code": null,
"e": 14106,
"s": 14082,
"text": "Native Features Enabled"
},
{
"code": null,
"e": 14680,
"s": 14106,
"text": "Explanation: Clicking on the Get Location button will trigger the navigator.geolocation.getCurrentPosition inside the handler function thereby populating the latitude and longitude fields with appropriate values. To get the exact name of the city, try using the Geocoder API as mentioned above. Similarly, clicking on the Take a Picture, Now Button will trigger the navigator.mediaDevices.getUserMedia inside the initializeMedia function thereby opening the front camera and taking a picture. Both these functions will first add for permissions and then execute themselves."
},
{
"code": null,
"e": 14695,
"s": 14680,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 14711,
"s": 14695,
"text": "React-Questions"
},
{
"code": null,
"e": 14721,
"s": 14711,
"text": "Blogathon"
},
{
"code": null,
"e": 14729,
"s": 14721,
"text": "ReactJS"
},
{
"code": null,
"e": 14746,
"s": 14729,
"text": "Web Technologies"
},
{
"code": null,
"e": 14844,
"s": 14746,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14885,
"s": 14844,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 14923,
"s": 14885,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 14967,
"s": 14923,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 15027,
"s": 14967,
"text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python"
},
{
"code": null,
"e": 15055,
"s": 15027,
"text": "Shared ViewModel in Android"
},
{
"code": null,
"e": 15098,
"s": 15055,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 15136,
"s": 15098,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 15181,
"s": 15136,
"text": "How to redirect to another page in ReactJS ?"
}
] |
Android - Internal Storage | Android provides many kinds of storage for applications to store their data. These storage places are shared preferences, internal and external storage, SQLite storage, and storage via network connection.
In this chapter we are going to look at the internal storage. Internal storage is the storage of the private data on the device memory.
By default these files are private and are accessed by only your application and get deleted , when user delete your application.
In order to use internal storage to write some data in the file, call the openFileOutput() method with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is given below −
FileOutputStream fOut = openFileOutput("file name here",MODE_WORLD_READABLE);
The method openFileOutput() returns an instance of FileOutputStream. So you receive it in the object of FileInputStream. After that you can call write method to write data on the file. Its syntax is given below −
String str = "data";
fOut.write(str.getBytes());
fOut.close();
In order to read from the file you just created , call the openFileInput() method with the name of the file. It returns an instance of FileInputStream. Its syntax is given below −
FileInputStream fin = openFileInput(file);
After that, you can call read method to read one character at a time from the file and then you can print it. Its syntax is given below −
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
//string temp contains all the data of the file.
fin.close();
Apart from the the methods of write and close, there are other methods provided by the FileOutputStream class for better writing files. These methods are listed below −
FileOutputStream(File file, boolean append)
This method constructs a new FileOutputStream that writes to file.
getChannel()
This method returns a write-only FileChannel that shares its position with this stream
getFD()
This method returns the underlying file descriptor
write(byte[] buffer, int byteOffset, int byteCount)
This method Writes count bytes from the byte array buffer starting at position offset to this stream
Apart from the the methods of read and close, there are other methods provided by the FileInputStream class for better reading files. These methods are listed below −
available()
This method returns an estimated number of bytes that can be read or skipped without blocking for more input
getChannel()
This method returns a read-only FileChannel that shares its position with this stream
getFD()
This method returns the underlying file descriptor
read(byte[] buffer, int byteOffset, int byteCount)
This method reads at most length bytes from this stream and stores them in the byte array b starting at offset
Here is an example demonstrating the use of internal storage to store and read files. It creates a basic storage application that allows you to read and write from internal storage.
To experiment with this example, you can run this on an actual device or in an emulator.
Following is the content of the modified main activity file src/MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class MainActivity extends Activity {
Button b1,b2;
TextView tv;
EditText ed1;
String data;
private String file = "mydata";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
ed1=(EditText)findViewById(R.id.editText);
tv=(TextView)findViewById(R.id.textView2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
data=ed1.getText().toString();
try {
FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(file);
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(),"file read",Toast.LENGTH_SHORT).show();
}
catch(Exception e){
}
}
});
}
}
Following is the modified content of the xml res/layout/activity_main.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" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="Internal storage" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Text"
android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:layout_marginTop="42dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="load"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
android:id="@+id/textView2"
android:layout_below="@+id/editText"
android:layout_toLeftOf="@+id/button2"
android:layout_toStartOf="@+id/button2"
android:textColor="#ff5bff1f"
android:textSize="25dp" />
</RelativeLayout>
Following is the content of the res/values/string.xml.
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<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 our Storage application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −
Now what you need to do is to enter any text in the field. For example , i have entered some text. Press the save button. The following notification would appear in you AVD −
Now when you press the load button, the application will read the file , and display the data. In case of our, following data would be returned −
Note you can actually view this file by switching to DDMS tab. In DDMS , select file explorer and navigate this path.
tools>android>android device Monitor
This has also been shown in the image below. | [
{
"code": null,
"e": 3946,
"s": 3741,
"text": "Android provides many kinds of storage for applications to store their data. These storage places are shared preferences, internal and external storage, SQLite storage, and storage via network connection."
},
{
"code": null,
"e": 4082,
"s": 3946,
"text": "In this chapter we are going to look at the internal storage. Internal storage is the storage of the private data on the device memory."
},
{
"code": null,
"e": 4212,
"s": 4082,
"text": "By default these files are private and are accessed by only your application and get deleted , when user delete your application."
},
{
"code": null,
"e": 4420,
"s": 4212,
"text": "In order to use internal storage to write some data in the file, call the openFileOutput() method with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is given below −"
},
{
"code": null,
"e": 4498,
"s": 4420,
"text": "FileOutputStream fOut = openFileOutput(\"file name here\",MODE_WORLD_READABLE);"
},
{
"code": null,
"e": 4711,
"s": 4498,
"text": "The method openFileOutput() returns an instance of FileOutputStream. So you receive it in the object of FileInputStream. After that you can call write method to write data on the file. Its syntax is given below −"
},
{
"code": null,
"e": 4774,
"s": 4711,
"text": "String str = \"data\";\nfOut.write(str.getBytes());\nfOut.close();"
},
{
"code": null,
"e": 4954,
"s": 4774,
"text": "In order to read from the file you just created , call the openFileInput() method with the name of the file. It returns an instance of FileInputStream. Its syntax is given below −"
},
{
"code": null,
"e": 4997,
"s": 4954,
"text": "FileInputStream fin = openFileInput(file);"
},
{
"code": null,
"e": 5135,
"s": 4997,
"text": "After that, you can call read method to read one character at a time from the file and then you can print it. Its syntax is given below −"
},
{
"code": null,
"e": 5301,
"s": 5135,
"text": "int c;\nString temp=\"\";\nwhile( (c = fin.read()) != -1){\n temp = temp + Character.toString((char)c);\n}\n\n//string temp contains all the data of the file.\nfin.close();"
},
{
"code": null,
"e": 5470,
"s": 5301,
"text": "Apart from the the methods of write and close, there are other methods provided by the FileOutputStream class for better writing files. These methods are listed below −"
},
{
"code": null,
"e": 5514,
"s": 5470,
"text": "FileOutputStream(File file, boolean append)"
},
{
"code": null,
"e": 5581,
"s": 5514,
"text": "This method constructs a new FileOutputStream that writes to file."
},
{
"code": null,
"e": 5594,
"s": 5581,
"text": "getChannel()"
},
{
"code": null,
"e": 5681,
"s": 5594,
"text": "This method returns a write-only FileChannel that shares its position with this stream"
},
{
"code": null,
"e": 5689,
"s": 5681,
"text": "getFD()"
},
{
"code": null,
"e": 5740,
"s": 5689,
"text": "This method returns the underlying file descriptor"
},
{
"code": null,
"e": 5792,
"s": 5740,
"text": "write(byte[] buffer, int byteOffset, int byteCount)"
},
{
"code": null,
"e": 5893,
"s": 5792,
"text": "This method Writes count bytes from the byte array buffer starting at position offset to this stream"
},
{
"code": null,
"e": 6060,
"s": 5893,
"text": "Apart from the the methods of read and close, there are other methods provided by the FileInputStream class for better reading files. These methods are listed below −"
},
{
"code": null,
"e": 6072,
"s": 6060,
"text": "available()"
},
{
"code": null,
"e": 6181,
"s": 6072,
"text": "This method returns an estimated number of bytes that can be read or skipped without blocking for more input"
},
{
"code": null,
"e": 6194,
"s": 6181,
"text": "getChannel()"
},
{
"code": null,
"e": 6280,
"s": 6194,
"text": "This method returns a read-only FileChannel that shares its position with this stream"
},
{
"code": null,
"e": 6288,
"s": 6280,
"text": "getFD()"
},
{
"code": null,
"e": 6339,
"s": 6288,
"text": "This method returns the underlying file descriptor"
},
{
"code": null,
"e": 6390,
"s": 6339,
"text": "read(byte[] buffer, int byteOffset, int byteCount)"
},
{
"code": null,
"e": 6501,
"s": 6390,
"text": "This method reads at most length bytes from this stream and stores them in the byte array b starting at offset"
},
{
"code": null,
"e": 6684,
"s": 6501,
"text": "Here is an example demonstrating the use of internal storage to store and read files. It creates a basic storage application that allows you to read and write from internal storage."
},
{
"code": null,
"e": 6773,
"s": 6684,
"text": "To experiment with this example, you can run this on an actual device or in an emulator."
},
{
"code": null,
"e": 6856,
"s": 6773,
"text": "Following is the content of the modified main activity file src/MainActivity.java."
},
{
"code": null,
"e": 8856,
"s": 6856,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\n\npublic class MainActivity extends Activity {\n Button b1,b2;\n TextView tv;\n EditText ed1;\n\n String data;\n private String file = \"mydata\";\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n b1=(Button)findViewById(R.id.button);\n b2=(Button)findViewById(R.id.button2);\n\n ed1=(EditText)findViewById(R.id.editText);\n tv=(TextView)findViewById(R.id.textView2);\n b1.setOnClickListener(new View.OnClickListener() {\n \n @Override\n public void onClick(View v) {\n data=ed1.getText().toString();\n try {\n FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);\n fOut.write(data.getBytes());\n fOut.close();\n Toast.makeText(getBaseContext(),\"file saved\",Toast.LENGTH_SHORT).show();\n }\n catch (Exception e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n });\n\n b2.setOnClickListener(new View.OnClickListener() {\n \n @Override\n public void onClick(View v) {\n try {\n FileInputStream fin = openFileInput(file);\n int c;\n String temp=\"\";\n while( (c = fin.read()) != -1){\n temp = temp + Character.toString((char)c);\n }\n tv.setText(temp);\n Toast.makeText(getBaseContext(),\"file read\",Toast.LENGTH_SHORT).show();\n }\n catch(Exception e){\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 8931,
"s": 8856,
"text": "Following is the modified content of the xml res/layout/activity_main.xml."
},
{
"code": null,
"e": 11873,
"s": 8931,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" tools:context=\".MainActivity\">\n \n <TextView android:text=\"Internal storage\" android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Save\"\n android:id=\"@+id/button\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignLeft=\"@+id/textView\"\n android:layout_alignStart=\"@+id/textView\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:hint=\"Enter Text\"\n android:focusable=\"true\"\n android:textColorHighlight=\"#ff7eff15\"\n android:textColorHint=\"#ffff25e6\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignRight=\"@+id/textView\"\n android:layout_alignEnd=\"@+id/textView\"\n android:layout_marginTop=\"42dp\"\n android:layout_alignLeft=\"@+id/imageView\"\n android:layout_alignStart=\"@+id/imageView\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"load\"\n android:id=\"@+id/button2\"\n android:layout_alignTop=\"@+id/button\"\n android:layout_alignRight=\"@+id/editText\"\n android:layout_alignEnd=\"@+id/editText\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Read\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/editText\"\n android:layout_toLeftOf=\"@+id/button2\"\n android:layout_toStartOf=\"@+id/button2\"\n android:textColor=\"#ff5bff1f\"\n android:textSize=\"25dp\" />\n \n</RelativeLayout>"
},
{
"code": null,
"e": 11928,
"s": 11873,
"text": "Following is the content of the res/values/string.xml."
},
{
"code": null,
"e": 12004,
"s": 11928,
"text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>"
},
{
"code": null,
"e": 12058,
"s": 12004,
"text": "Following is the content of AndroidManifest.xml file."
},
{
"code": null,
"e": 12759,
"s": 12058,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 13162,
"s": 12759,
"text": "Let's try to run our Storage application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −"
},
{
"code": null,
"e": 13337,
"s": 13162,
"text": "Now what you need to do is to enter any text in the field. For example , i have entered some text. Press the save button. The following notification would appear in you AVD −"
},
{
"code": null,
"e": 13483,
"s": 13337,
"text": "Now when you press the load button, the application will read the file , and display the data. In case of our, following data would be returned −"
},
{
"code": null,
"e": 13601,
"s": 13483,
"text": "Note you can actually view this file by switching to DDMS tab. In DDMS , select file explorer and navigate this path."
},
{
"code": null,
"e": 13639,
"s": 13601,
"text": "tools>android>android device Monitor\n"
}
] |
How to create buttons in Jupyter? | 24 Feb, 2021
In this article, we will learn How to create an interactive button in Jupyter using Python Program. An Interactive Button is a button which when clicked by a user performs a specific function. For the following task, we need the ipywidgets library module. ipywidgets, also known as jupyter-widgets or simply widgets, are interactive HTML widgets for Jupyter notebooks and the IPython kernel.
If your console does not have the module, you can install it by using the following command:
pip install ipywidgets
In most cases, installing the Python ipywidgets package will also automatically configure classic Jupyter Notebook and JupyterLab 3.0 to display ipywidgets.
Example 1: Creating a simple button.
Syntax: widgets.Button(description=’My Button’)
Code:
Python3
# import moduleimport ipywidgets as widgets # creating buttonwidgets.Button(description = 'My Button')
Output:
Example 2:
Here, we will create an interactive button that will help us to select a random language from a list of given Languages.
interact_manual(): Automatically creates a User Interface Control for exploring code and data interactively.
choice(): Returns a randomly selected element from the specified sequence.
Code:
Python3
import ipywidgets as widgetsfrom ipywidgets import interact, interact_manual, fixed from random import choice def lang(): langSelect = ["English","Deustche","Espanol","Italiano","한국어","日本人"] print(choice(langSelect)) interact_manual(lang)
Output:
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 420,
"s": 28,
"text": "In this article, we will learn How to create an interactive button in Jupyter using Python Program. An Interactive Button is a button which when clicked by a user performs a specific function. For the following task, we need the ipywidgets library module. ipywidgets, also known as jupyter-widgets or simply widgets, are interactive HTML widgets for Jupyter notebooks and the IPython kernel."
},
{
"code": null,
"e": 513,
"s": 420,
"text": "If your console does not have the module, you can install it by using the following command:"
},
{
"code": null,
"e": 536,
"s": 513,
"text": "pip install ipywidgets"
},
{
"code": null,
"e": 694,
"s": 536,
"text": "In most cases, installing the Python ipywidgets package will also automatically configure classic Jupyter Notebook and JupyterLab 3.0 to display ipywidgets. "
},
{
"code": null,
"e": 731,
"s": 694,
"text": "Example 1: Creating a simple button."
},
{
"code": null,
"e": 779,
"s": 731,
"text": "Syntax: widgets.Button(description=’My Button’)"
},
{
"code": null,
"e": 785,
"s": 779,
"text": "Code:"
},
{
"code": null,
"e": 793,
"s": 785,
"text": "Python3"
},
{
"code": "# import moduleimport ipywidgets as widgets # creating buttonwidgets.Button(description = 'My Button')",
"e": 897,
"s": 793,
"text": null
},
{
"code": null,
"e": 905,
"s": 897,
"text": "Output:"
},
{
"code": null,
"e": 917,
"s": 905,
"text": "Example 2: "
},
{
"code": null,
"e": 1038,
"s": 917,
"text": "Here, we will create an interactive button that will help us to select a random language from a list of given Languages."
},
{
"code": null,
"e": 1147,
"s": 1038,
"text": "interact_manual(): Automatically creates a User Interface Control for exploring code and data interactively."
},
{
"code": null,
"e": 1222,
"s": 1147,
"text": "choice(): Returns a randomly selected element from the specified sequence."
},
{
"code": null,
"e": 1228,
"s": 1222,
"text": "Code:"
},
{
"code": null,
"e": 1236,
"s": 1228,
"text": "Python3"
},
{
"code": "import ipywidgets as widgetsfrom ipywidgets import interact, interact_manual, fixed from random import choice def lang(): langSelect = [\"English\",\"Deustche\",\"Espanol\",\"Italiano\",\"한국어\",\"日本人\"] print(choice(langSelect)) interact_manual(lang)",
"e": 1487,
"s": 1236,
"text": null
},
{
"code": null,
"e": 1495,
"s": 1487,
"text": "Output:"
},
{
"code": null,
"e": 1502,
"s": 1495,
"text": "Picked"
},
{
"code": null,
"e": 1517,
"s": 1502,
"text": "python-utility"
},
{
"code": null,
"e": 1524,
"s": 1517,
"text": "Python"
},
{
"code": null,
"e": 1622,
"s": 1524,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1654,
"s": 1622,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1681,
"s": 1654,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1702,
"s": 1681,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1733,
"s": 1702,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1789,
"s": 1733,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1812,
"s": 1789,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1854,
"s": 1812,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1896,
"s": 1854,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1935,
"s": 1896,
"text": "Python | datetime.timedelta() function"
}
] |
Python | Grouping list values into dictionary | 26 Aug, 2019
Sometimes, while working with data, we can be encountered with a situation in which we have list of list and we need to group it’s 2nd index with the common initial element in lists. Let’s discuss way in which this problem can be solved.
Method : Using defaultdict() + loop + dict()
The defaultdict can be used to initialize the group elements and loop can be used to group the values together and conversion to dictionary can be done using dict().
# Python3 code to demonstrate working of# Grouping list values into dictionary# Using defaultdict() + loop + dict()from collections import defaultdict # initializing listtest_list = [['Gfg', 1], ['Gfg', 2], ['is', 3], ['best', 4], ['is', 5]] # printing original listprint("The original list is : " + str(test_list)) # Grouping list values into dictionary# Using defaultdict() + loop + dict()temp = defaultdict(list)for key, val in test_list: temp[key].append(val)res = dict((key, tuple(val)) for key, val in temp.items()) # printing resultprint("The grouped dictionary is : " + str(res))
The original list is : [['Gfg', 1], ['Gfg', 2], ['is', 3], ['best', 4], ['is', 5]]
The grouped dictionary is : {'Gfg': (1, 2), 'best': (4, ), 'is': (3, 5)}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "Sometimes, while working with data, we can be encountered with a situation in which we have list of list and we need to group it’s 2nd index with the common initial element in lists. Let’s discuss way in which this problem can be solved."
},
{
"code": null,
"e": 311,
"s": 266,
"text": "Method : Using defaultdict() + loop + dict()"
},
{
"code": null,
"e": 477,
"s": 311,
"text": "The defaultdict can be used to initialize the group elements and loop can be used to group the values together and conversion to dictionary can be done using dict()."
},
{
"code": "# Python3 code to demonstrate working of# Grouping list values into dictionary# Using defaultdict() + loop + dict()from collections import defaultdict # initializing listtest_list = [['Gfg', 1], ['Gfg', 2], ['is', 3], ['best', 4], ['is', 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # Grouping list values into dictionary# Using defaultdict() + loop + dict()temp = defaultdict(list)for key, val in test_list: temp[key].append(val)res = dict((key, tuple(val)) for key, val in temp.items()) # printing resultprint(\"The grouped dictionary is : \" + str(res))",
"e": 1073,
"s": 477,
"text": null
},
{
"code": null,
"e": 1231,
"s": 1073,
"text": "The original list is : [['Gfg', 1], ['Gfg', 2], ['is', 3], ['best', 4], ['is', 5]]\nThe grouped dictionary is : {'Gfg': (1, 2), 'best': (4, ), 'is': (3, 5)}\n"
},
{
"code": null,
"e": 1260,
"s": 1233,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 1267,
"s": 1260,
"text": "Python"
},
{
"code": null,
"e": 1283,
"s": 1267,
"text": "Python Programs"
},
{
"code": null,
"e": 1381,
"s": 1283,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1399,
"s": 1381,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1441,
"s": 1399,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1463,
"s": 1441,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1498,
"s": 1463,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1530,
"s": 1498,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1573,
"s": 1530,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1595,
"s": 1573,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1634,
"s": 1595,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1672,
"s": 1634,
"text": "Python | Convert a list to dictionary"
}
] |
ascii_letters in Python | 23 Oct, 2020
In Python3, ascii_letters is a pre-initialized string used as string constant.ascii_letters is basically concatenation of ascii_lowercase and ascii_uppercase string constants. Also, the value generated is not locale-dependent, hence, doesn’t change.
Syntax :
string.ascii_letters
Note : Make sure to import string library function inorder to use ascii_letters.
Parameters :
Doesn't take any parameter, since it's not a function.
Returns :
Return all ASCII letters (both lower and upper case)
Code #1 :
# import string library functionimport string # Storing the value in variable resultresult = string.ascii_letters # Printing the valueprint(result)
Output :
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Code #2 :Given code checks if the string input has only ASCII characters or not.
# importing string library functionimport string # Function checks if input string# has only ascii letters or notdef check(value): for letter in value: # If anything other than ascii # letter is present, then return # False, else return True if letter not in string.ascii_letters: return False return True # Driver Codeinput1 = "GeeksForGeeks"print(input1, "--> ", check(input1)) input2 = "Geeks for Geeks"print(input2, "--> ", check(input2)) input3 = "Geeks_for_geeks"print(input3, "--> ", check(input3))
Output :
GeeksForGeeks --> True
Geeks for Geeks --> False
Geeks_for_geeks --> False
Applications :The string constant ascii_letters can be used in many practical applications.Let’s see a code explaining how to use ascii_letters to generate strong random passwords of given size.
Code #1 :
# Importing random to generate# random string sequenceimport random # Importing string library functionimport string def rand_pass(size): # Takes random choices from # ascii_letters and digits generate_pass = ''.join([random.choice( string.ascii_letters + string.digits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10)print(password)
Output :
oQjI5MOXQ3
Note : Above given code will print random (different) password everytime, for the size provided. Code #2 :Say if you want to generate random password, but from the set of given string. Let’s see how can we do this using ascii_letters :
# Importing random to generate# random string sequenceimport random # Importing string library functionimport string def rand_pass(size, scope = string.ascii_letters + string.digits): # Takes random choices from ascii_letters and digits generate_pass = ''.join([random.choice(scope) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10, 'Geeks3F0rgeeKs')print(password)
Output :
kg3g03keG3
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 304,
"s": 54,
"text": "In Python3, ascii_letters is a pre-initialized string used as string constant.ascii_letters is basically concatenation of ascii_lowercase and ascii_uppercase string constants. Also, the value generated is not locale-dependent, hence, doesn’t change."
},
{
"code": null,
"e": 313,
"s": 304,
"text": "Syntax :"
},
{
"code": null,
"e": 334,
"s": 313,
"text": "string.ascii_letters"
},
{
"code": null,
"e": 415,
"s": 334,
"text": "Note : Make sure to import string library function inorder to use ascii_letters."
},
{
"code": null,
"e": 428,
"s": 415,
"text": "Parameters :"
},
{
"code": null,
"e": 485,
"s": 428,
"text": " Doesn't take any parameter, since it's not a function. "
},
{
"code": null,
"e": 495,
"s": 485,
"text": "Returns :"
},
{
"code": null,
"e": 549,
"s": 495,
"text": " Return all ASCII letters (both lower and upper case)"
},
{
"code": null,
"e": 560,
"s": 549,
"text": " Code #1 :"
},
{
"code": "# import string library functionimport string # Storing the value in variable resultresult = string.ascii_letters # Printing the valueprint(result)",
"e": 710,
"s": 560,
"text": null
},
{
"code": null,
"e": 719,
"s": 710,
"text": "Output :"
},
{
"code": null,
"e": 772,
"s": 719,
"text": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
},
{
"code": null,
"e": 855,
"s": 774,
"text": "Code #2 :Given code checks if the string input has only ASCII characters or not."
},
{
"code": "# importing string library functionimport string # Function checks if input string# has only ascii letters or notdef check(value): for letter in value: # If anything other than ascii # letter is present, then return # False, else return True if letter not in string.ascii_letters: return False return True # Driver Codeinput1 = \"GeeksForGeeks\"print(input1, \"--> \", check(input1)) input2 = \"Geeks for Geeks\"print(input2, \"--> \", check(input2)) input3 = \"Geeks_for_geeks\"print(input3, \"--> \", check(input3))",
"e": 1421,
"s": 855,
"text": null
},
{
"code": null,
"e": 1430,
"s": 1421,
"text": "Output :"
},
{
"code": null,
"e": 1508,
"s": 1430,
"text": "GeeksForGeeks --> True\nGeeks for Geeks --> False\nGeeks_for_geeks --> False"
},
{
"code": null,
"e": 1704,
"s": 1508,
"text": " Applications :The string constant ascii_letters can be used in many practical applications.Let’s see a code explaining how to use ascii_letters to generate strong random passwords of given size."
},
{
"code": null,
"e": 1714,
"s": 1704,
"text": "Code #1 :"
},
{
"code": "# Importing random to generate# random string sequenceimport random # Importing string library functionimport string def rand_pass(size): # Takes random choices from # ascii_letters and digits generate_pass = ''.join([random.choice( string.ascii_letters + string.digits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10)print(password) ",
"e": 2186,
"s": 1714,
"text": null
},
{
"code": null,
"e": 2195,
"s": 2186,
"text": "Output :"
},
{
"code": null,
"e": 2206,
"s": 2195,
"text": "oQjI5MOXQ3"
},
{
"code": null,
"e": 2442,
"s": 2206,
"text": "Note : Above given code will print random (different) password everytime, for the size provided. Code #2 :Say if you want to generate random password, but from the set of given string. Let’s see how can we do this using ascii_letters :"
},
{
"code": "# Importing random to generate# random string sequenceimport random # Importing string library functionimport string def rand_pass(size, scope = string.ascii_letters + string.digits): # Takes random choices from ascii_letters and digits generate_pass = ''.join([random.choice(scope) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10, 'Geeks3F0rgeeKs')print(password)",
"e": 2912,
"s": 2442,
"text": null
},
{
"code": null,
"e": 2921,
"s": 2912,
"text": "Output :"
},
{
"code": null,
"e": 2932,
"s": 2921,
"text": "kg3g03keG3"
},
{
"code": null,
"e": 2946,
"s": 2932,
"text": "python-string"
},
{
"code": null,
"e": 2953,
"s": 2946,
"text": "Python"
},
{
"code": null,
"e": 3051,
"s": 2953,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3093,
"s": 3051,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3115,
"s": 3093,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3141,
"s": 3115,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3173,
"s": 3141,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3202,
"s": 3173,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3229,
"s": 3202,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3250,
"s": 3229,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3273,
"s": 3250,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3309,
"s": 3273,
"text": "Convert integer to string in Python"
}
] |
Simple Text editor using File System Access API | 20 Dec, 2020
In this article, we will create a simple text editor like application that we can use to open, edit, and save text files with the help of File System Access API.
File System Access API enables us to interact with files on our local devices like photo and video editors. When the user gives permission, this helps us to read or save changes directly to files and folders on the local storage. Using this API we can read, write, modify, and also we can open a directory to modify its content.
We will create this application in three steps.
Make a general structure using HTML.
Give a general style using CSS.
Writing some code in JavaScript with the help of File System Access API.
HTML code: We will use HTML to design the web page structure or layout. Create a container with a text area and two buttons to open the file and save the file.
HTML
<!DOCTYPE html><html> <body> <div class="container"> <!--Text Area --> <textarea id="content" placeholder="Lets Write "> </textarea> <!--Buttons --> <div class="buttons"> <!--To open --> <button id="openfile"> Open </button> <!-- To save--> <button id="savefile"> Save </button> </div> </div></body> </html>
CSS code: CSS is used to give general styling and make it more visually appealing. Give general styling to the whole page like color and alignment. We use flex to center the elements. Include the following in the above HTML code in the style section of the head part of the code.
/* General Alignment to container
using flexbox */
.container{
display: flex;
height: 100vh;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
/* Styling to the textarea */
textarea {
width: 90vw;
color: #777;
font-size: 1.1rem;
min-height: 20rem;
border: 2px dashed rgba(0, 0, 0, 0.2);
padding: 1.5rem;
}
/* Aligning buttons to center */
.buttons{
width: 100%;
display: flex;
justify-content: center;
}
/* General styling to button */
button{
margin:0 0.5rem;
font-size: 1.1rem;
font-weight: 800;
background-color: blue;
color: #ffffff;
padding: 1rem 1.5rem;
}
Output:
JavaScript: We will use filesystem API to open, edit, and save the file. We will break our JavaScript code into three steps.
Creating variables and get access to elements with id, open files, and save the file.
To create a function to open the file.
To create a function to close the file
Step 1: Getting access to the elements
HTML
const openFile = document.getElementById('openfile');const saveFile = document.getElementById('savefile');const contentTextArea = document.getElementById('content');let fileHandle;
Step 2: It demonstrates a function to open the file. To open a file, first we need to prompt the user to select a file. For this, we will use the showOpenFilePicker() method. This method will return an array of filehandles.
Now we have a filehandle, so we can access the file itself by using the method filehandle.getFile() it returns the file object, which contains a blob. To access the data we will use method text().
HTML
const open = async () => { [fileHandle] = await window.showOpenFilePicker(); const file = await fileHandle.getFile(); const contents = await file.text(); contentTextArea.value = contents;}
Step 3: It demonstrates the function to save the file. To save the file we will use the showSaveFilePicker() method. We also want to save it in .txt format, so we will provide some optional parameters.
Now we have to write the file on a disk for this we will use the FileSystemWritableFileStream object. We will create a stream by calling the createWritable() method. When this method is called, it will check for write permission if permission is not given it will ask the user for permission. If permission is denied, it will throw an exception. Then we will write the contents of the file to the stream using the write() method. We will close the writable stream and will return the handle.
HTML
const save = async content => { try { const handle = await window.showSaveFilePicker({ types: [ { accept: { 'text/plain': ['.txt'], }, }, ], }) // Create a FileSystemWritableFileStream to write const writable = await handle.createWritable(); // Write the contents of the file to the stream await writable.write(content); // Close the file and write the contents to disk await writable.close(); return handle; } catch (err) { console.error(err.name); }}
At the end, we will associate the open and save method to our variable open file and save file.
HTML
openFile.addEventListener('click', () => open());saveFile.addEventListener('click', () => save(contentTextArea.value));
Output: So our editor is ready now.
https://github.com/Nandini-72/Notepad
CSS-Misc
HTML-Misc
JavaScript-Misc
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Dec, 2020"
},
{
"code": null,
"e": 217,
"s": 54,
"text": "In this article, we will create a simple text editor like application that we can use to open, edit, and save text files with the help of File System Access API. "
},
{
"code": null,
"e": 546,
"s": 217,
"text": "File System Access API enables us to interact with files on our local devices like photo and video editors. When the user gives permission, this helps us to read or save changes directly to files and folders on the local storage. Using this API we can read, write, modify, and also we can open a directory to modify its content."
},
{
"code": null,
"e": 594,
"s": 546,
"text": "We will create this application in three steps."
},
{
"code": null,
"e": 631,
"s": 594,
"text": "Make a general structure using HTML."
},
{
"code": null,
"e": 663,
"s": 631,
"text": "Give a general style using CSS."
},
{
"code": null,
"e": 736,
"s": 663,
"text": "Writing some code in JavaScript with the help of File System Access API."
},
{
"code": null,
"e": 896,
"s": 736,
"text": "HTML code: We will use HTML to design the web page structure or layout. Create a container with a text area and two buttons to open the file and save the file."
},
{
"code": null,
"e": 901,
"s": 896,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <div class=\"container\"> <!--Text Area --> <textarea id=\"content\" placeholder=\"Lets Write \"> </textarea> <!--Buttons --> <div class=\"buttons\"> <!--To open --> <button id=\"openfile\"> Open </button> <!-- To save--> <button id=\"savefile\"> Save </button> </div> </div></body> </html>",
"e": 1375,
"s": 901,
"text": null
},
{
"code": null,
"e": 1655,
"s": 1375,
"text": "CSS code: CSS is used to give general styling and make it more visually appealing. Give general styling to the whole page like color and alignment. We use flex to center the elements. Include the following in the above HTML code in the style section of the head part of the code."
},
{
"code": null,
"e": 2316,
"s": 1655,
"text": "/* General Alignment to container \nusing flexbox */\n.container{\n display: flex;\n height: 100vh;\n flex-wrap: wrap;\n align-items: center;\n justify-content: center;\n}\n\n/* Styling to the textarea */\ntextarea {\n width: 90vw;\n color: #777;\n font-size: 1.1rem;\n min-height: 20rem;\n border: 2px dashed rgba(0, 0, 0, 0.2);\n padding: 1.5rem;\n}\n\n/* Aligning buttons to center */\n.buttons{\n width: 100%;\n display: flex;\n justify-content: center;\n}\n\n/* General styling to button */\nbutton{\n margin:0 0.5rem;\n font-size: 1.1rem;\n font-weight: 800;\n background-color: blue;\n color: #ffffff;\n padding: 1rem 1.5rem;\n}"
},
{
"code": null,
"e": 2324,
"s": 2316,
"text": "Output:"
},
{
"code": null,
"e": 2449,
"s": 2324,
"text": "JavaScript: We will use filesystem API to open, edit, and save the file. We will break our JavaScript code into three steps."
},
{
"code": null,
"e": 2535,
"s": 2449,
"text": "Creating variables and get access to elements with id, open files, and save the file."
},
{
"code": null,
"e": 2574,
"s": 2535,
"text": "To create a function to open the file."
},
{
"code": null,
"e": 2614,
"s": 2574,
"text": "To create a function to close the file "
},
{
"code": null,
"e": 2653,
"s": 2614,
"text": "Step 1: Getting access to the elements"
},
{
"code": null,
"e": 2658,
"s": 2653,
"text": "HTML"
},
{
"code": "const openFile = document.getElementById('openfile');const saveFile = document.getElementById('savefile');const contentTextArea = document.getElementById('content');let fileHandle;",
"e": 2839,
"s": 2658,
"text": null
},
{
"code": null,
"e": 3063,
"s": 2839,
"text": "Step 2: It demonstrates a function to open the file. To open a file, first we need to prompt the user to select a file. For this, we will use the showOpenFilePicker() method. This method will return an array of filehandles."
},
{
"code": null,
"e": 3260,
"s": 3063,
"text": "Now we have a filehandle, so we can access the file itself by using the method filehandle.getFile() it returns the file object, which contains a blob. To access the data we will use method text()."
},
{
"code": null,
"e": 3265,
"s": 3260,
"text": "HTML"
},
{
"code": "const open = async () => { [fileHandle] = await window.showOpenFilePicker(); const file = await fileHandle.getFile(); const contents = await file.text(); contentTextArea.value = contents;}",
"e": 3458,
"s": 3265,
"text": null
},
{
"code": null,
"e": 3661,
"s": 3458,
"text": "Step 3: It demonstrates the function to save the file. To save the file we will use the showSaveFilePicker() method. We also want to save it in .txt format, so we will provide some optional parameters."
},
{
"code": null,
"e": 4153,
"s": 3661,
"text": "Now we have to write the file on a disk for this we will use the FileSystemWritableFileStream object. We will create a stream by calling the createWritable() method. When this method is called, it will check for write permission if permission is not given it will ask the user for permission. If permission is denied, it will throw an exception. Then we will write the contents of the file to the stream using the write() method. We will close the writable stream and will return the handle."
},
{
"code": null,
"e": 4158,
"s": 4153,
"text": "HTML"
},
{
"code": "const save = async content => { try { const handle = await window.showSaveFilePicker({ types: [ { accept: { 'text/plain': ['.txt'], }, }, ], }) // Create a FileSystemWritableFileStream to write const writable = await handle.createWritable(); // Write the contents of the file to the stream await writable.write(content); // Close the file and write the contents to disk await writable.close(); return handle; } catch (err) { console.error(err.name); }}",
"e": 4817,
"s": 4158,
"text": null
},
{
"code": null,
"e": 4913,
"s": 4817,
"text": "At the end, we will associate the open and save method to our variable open file and save file."
},
{
"code": null,
"e": 4918,
"s": 4913,
"text": "HTML"
},
{
"code": "openFile.addEventListener('click', () => open());saveFile.addEventListener('click', () => save(contentTextArea.value));",
"e": 5042,
"s": 4918,
"text": null
},
{
"code": null,
"e": 5078,
"s": 5042,
"text": "Output: So our editor is ready now."
},
{
"code": null,
"e": 5117,
"s": 5078,
"text": " https://github.com/Nandini-72/Notepad"
},
{
"code": null,
"e": 5126,
"s": 5117,
"text": "CSS-Misc"
},
{
"code": null,
"e": 5136,
"s": 5126,
"text": "HTML-Misc"
},
{
"code": null,
"e": 5152,
"s": 5136,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 5176,
"s": 5152,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5180,
"s": 5176,
"text": "CSS"
},
{
"code": null,
"e": 5185,
"s": 5180,
"text": "HTML"
},
{
"code": null,
"e": 5196,
"s": 5185,
"text": "JavaScript"
},
{
"code": null,
"e": 5215,
"s": 5196,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5220,
"s": 5215,
"text": "HTML"
},
{
"code": null,
"e": 5318,
"s": 5220,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5357,
"s": 5318,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 5396,
"s": 5357,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 5435,
"s": 5396,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 5464,
"s": 5435,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 5501,
"s": 5464,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 5525,
"s": 5501,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5578,
"s": 5525,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 5638,
"s": 5578,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 5699,
"s": 5638,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
React Native Flexbox alignItems Property | 25 May, 2021
In this article, We are going to see the Flexbox alignItems Property in React Native. Flexbox has three main properties. One of them is alignItems. alignItems property is used to determine how should children’s components be aligned along the secondary axis of their container. The secondary axis is always opposite to the primary axis. If the primary axis is a column, then the secondary will be a row, and vice-versa.
Syntax:
alignItems: stretch|center|flex-start|flex-end|baseline;
Property Values:
stretch: It is the default value of alignItems. In this, the children’s components are stretched to fit the height of the container’s secondary axis.
center: Alignment of the children components should be at the center of the container’s secondary axis.
flex-start: Children components will be aligned to the beginning of the container’s secondary axis.
flex-end: Children components will be aligned to the end of the container’s secondary axis.
baseline: Children’s components will be aligned to the baseline of the container.
Implementation:
Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
Step 2: Now create a project by the following command.expo init myapp
Step 2: Now create a project by the following command.
expo init myapp
Step 3: Now go into your project folder i.e. myappcd myapp
Step 3: Now go into your project folder i.e. myapp
cd myapp
Project Structure:
Example 1: Here in this example, flex-direction is set to row, and alignItems property value is stretch. When we put the value stretch for alignItems then we do not give the dimension to our secondary axis. Hence, in the following code, we have not given the height to our item.
App.js
import React, { Component } from 'react';import { View, StyleSheet } from 'react-native'; const App = (props) => { return ( <View style = {styles.container}> <View style = {[styles.item,{backgroundColor:'green'}]} /> <View style = {[styles.item,{backgroundColor:'blue'}]} /> <View style = {[styles.item,{backgroundColor:'red'}]} /> </View> )}export default App; const styles = StyleSheet.create ({ container: { flexDirection: 'row', alignItems: 'stretch', height: 700 }, item:{ width:100 }})
Start the server by using the following command.
npm run android
Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again.
GFG
Example 2: In this example, the entire code will be the same we will just change the value of alignItems property to center and provide the height to the item.
App.js
import React, { Component } from 'react';import { View, StyleSheet } from 'react-native'; const App = (props) => { return ( <View style = {styles.container}> <View style = {[styles.item,{backgroundColor:'green'}]} /> <View style = {[styles.item,{backgroundColor:'blue'}]} /> <View style = {[styles.item,{backgroundColor:'red'}]} /> </View> )}export default App; const styles = StyleSheet.create ({ container: { flexDirection: 'row', alignItems: 'center', height: 700 }, item:{ width:100, height:100 }})
Output:
GFG
Now we will keep the entire code the same and just do the changes in alignItems property value to see the change.
Property flex-start illustration, use the following syntax:alignItems : 'flex-start',GFG
Property flex-start illustration, use the following syntax:
alignItems : 'flex-start',
GFG
Property flex-end illustration, use the following syntax:alignItems:'flex-end',GFG
Property flex-end illustration, use the following syntax:
alignItems:'flex-end',
GFG
Property baseline illustration, use the following syntax:alignItems:'baseline',GFG
Property baseline illustration, use the following syntax:
alignItems:'baseline',
GFG
Reference:https://reactnative.dev/docs/flexbox#align-items
Picked
React-Native
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 448,
"s": 28,
"text": "In this article, We are going to see the Flexbox alignItems Property in React Native. Flexbox has three main properties. One of them is alignItems. alignItems property is used to determine how should children’s components be aligned along the secondary axis of their container. The secondary axis is always opposite to the primary axis. If the primary axis is a column, then the secondary will be a row, and vice-versa."
},
{
"code": null,
"e": 458,
"s": 448,
"text": "Syntax: "
},
{
"code": null,
"e": 515,
"s": 458,
"text": "alignItems: stretch|center|flex-start|flex-end|baseline;"
},
{
"code": null,
"e": 532,
"s": 515,
"text": "Property Values:"
},
{
"code": null,
"e": 682,
"s": 532,
"text": "stretch: It is the default value of alignItems. In this, the children’s components are stretched to fit the height of the container’s secondary axis."
},
{
"code": null,
"e": 786,
"s": 682,
"text": "center: Alignment of the children components should be at the center of the container’s secondary axis."
},
{
"code": null,
"e": 886,
"s": 786,
"text": "flex-start: Children components will be aligned to the beginning of the container’s secondary axis."
},
{
"code": null,
"e": 978,
"s": 886,
"text": "flex-end: Children components will be aligned to the end of the container’s secondary axis."
},
{
"code": null,
"e": 1060,
"s": 978,
"text": "baseline: Children’s components will be aligned to the baseline of the container."
},
{
"code": null,
"e": 1076,
"s": 1060,
"text": "Implementation:"
},
{
"code": null,
"e": 1173,
"s": 1076,
"text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli"
},
{
"code": null,
"e": 1247,
"s": 1173,
"text": "Step 1: Open your terminal and install expo-cli by the following command."
},
{
"code": null,
"e": 1271,
"s": 1247,
"text": "npm install -g expo-cli"
},
{
"code": null,
"e": 1341,
"s": 1271,
"text": "Step 2: Now create a project by the following command.expo init myapp"
},
{
"code": null,
"e": 1396,
"s": 1341,
"text": "Step 2: Now create a project by the following command."
},
{
"code": null,
"e": 1412,
"s": 1396,
"text": "expo init myapp"
},
{
"code": null,
"e": 1471,
"s": 1412,
"text": "Step 3: Now go into your project folder i.e. myappcd myapp"
},
{
"code": null,
"e": 1522,
"s": 1471,
"text": "Step 3: Now go into your project folder i.e. myapp"
},
{
"code": null,
"e": 1531,
"s": 1522,
"text": "cd myapp"
},
{
"code": null,
"e": 1550,
"s": 1531,
"text": "Project Structure:"
},
{
"code": null,
"e": 1829,
"s": 1550,
"text": "Example 1: Here in this example, flex-direction is set to row, and alignItems property value is stretch. When we put the value stretch for alignItems then we do not give the dimension to our secondary axis. Hence, in the following code, we have not given the height to our item."
},
{
"code": null,
"e": 1836,
"s": 1829,
"text": "App.js"
},
{
"code": "import React, { Component } from 'react';import { View, StyleSheet } from 'react-native'; const App = (props) => { return ( <View style = {styles.container}> <View style = {[styles.item,{backgroundColor:'green'}]} /> <View style = {[styles.item,{backgroundColor:'blue'}]} /> <View style = {[styles.item,{backgroundColor:'red'}]} /> </View> )}export default App; const styles = StyleSheet.create ({ container: { flexDirection: 'row', alignItems: 'stretch', height: 700 }, item:{ width:100 }})",
"e": 2380,
"s": 1836,
"text": null
},
{
"code": null,
"e": 2429,
"s": 2380,
"text": "Start the server by using the following command."
},
{
"code": null,
"e": 2445,
"s": 2429,
"text": "npm run android"
},
{
"code": null,
"e": 2614,
"s": 2445,
"text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. "
},
{
"code": null,
"e": 2618,
"s": 2614,
"text": "GFG"
},
{
"code": null,
"e": 2778,
"s": 2618,
"text": "Example 2: In this example, the entire code will be the same we will just change the value of alignItems property to center and provide the height to the item."
},
{
"code": null,
"e": 2785,
"s": 2778,
"text": "App.js"
},
{
"code": "import React, { Component } from 'react';import { View, StyleSheet } from 'react-native'; const App = (props) => { return ( <View style = {styles.container}> <View style = {[styles.item,{backgroundColor:'green'}]} /> <View style = {[styles.item,{backgroundColor:'blue'}]} /> <View style = {[styles.item,{backgroundColor:'red'}]} /> </View> )}export default App; const styles = StyleSheet.create ({ container: { flexDirection: 'row', alignItems: 'center', height: 700 }, item:{ width:100, height:100 }})",
"e": 3343,
"s": 2785,
"text": null
},
{
"code": null,
"e": 3351,
"s": 3343,
"text": "Output:"
},
{
"code": null,
"e": 3355,
"s": 3351,
"text": "GFG"
},
{
"code": null,
"e": 3469,
"s": 3355,
"text": "Now we will keep the entire code the same and just do the changes in alignItems property value to see the change."
},
{
"code": null,
"e": 3558,
"s": 3469,
"text": "Property flex-start illustration, use the following syntax:alignItems : 'flex-start',GFG"
},
{
"code": null,
"e": 3618,
"s": 3558,
"text": "Property flex-start illustration, use the following syntax:"
},
{
"code": null,
"e": 3645,
"s": 3618,
"text": "alignItems : 'flex-start',"
},
{
"code": null,
"e": 3649,
"s": 3645,
"text": "GFG"
},
{
"code": null,
"e": 3732,
"s": 3649,
"text": "Property flex-end illustration, use the following syntax:alignItems:'flex-end',GFG"
},
{
"code": null,
"e": 3790,
"s": 3732,
"text": "Property flex-end illustration, use the following syntax:"
},
{
"code": null,
"e": 3813,
"s": 3790,
"text": "alignItems:'flex-end',"
},
{
"code": null,
"e": 3817,
"s": 3813,
"text": "GFG"
},
{
"code": null,
"e": 3900,
"s": 3817,
"text": "Property baseline illustration, use the following syntax:alignItems:'baseline',GFG"
},
{
"code": null,
"e": 3958,
"s": 3900,
"text": "Property baseline illustration, use the following syntax:"
},
{
"code": null,
"e": 3981,
"s": 3958,
"text": "alignItems:'baseline',"
},
{
"code": null,
"e": 3985,
"s": 3981,
"text": "GFG"
},
{
"code": null,
"e": 4044,
"s": 3985,
"text": "Reference:https://reactnative.dev/docs/flexbox#align-items"
},
{
"code": null,
"e": 4051,
"s": 4044,
"text": "Picked"
},
{
"code": null,
"e": 4064,
"s": 4051,
"text": "React-Native"
},
{
"code": null,
"e": 4081,
"s": 4064,
"text": "Web Technologies"
}
] |
Sort a Linked List of 0s and 1s | 03 Feb, 2022
Given the head of a Linked List of size N, consisting of binary integers 0s and 1s, the task is to sort the given linked list.
Examples:
Input: head = 1 -> 0 -> 1 -> 0 -> 1 -> 0 -> NULL Output: 0 -> 0 -> 0 -> 1 -> 1 -> 1 -> NULL
Input: head = 1 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 1 -> NULL
Naive Approach: The simplest approach to solve the given problem is to perform the merge sort or insertion sort on the given linked list and sort it. The Implementation of Sorting the Linked list using Merge sort and Sorting the linked list using Insertion sort is discussed already.
Time complexity: O(N * log N)Auxiliary Space: O(N)
Efficient Approach: The above approach can also be optimized by counting the number of 1s and 0s in the given linked list and update the value of nodes accordingly in the linked list. Follow the steps to solve the problem:
Traverse the given linked list and store the count of 0s and 1s in variables, say zeroes and ones respectively.
Now, traverse the linked list again and change the first zeroes nodes with value 0 and then the remaining nodes with the value 1.
After completing the above steps, print the linked list as the resultant sorted list.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Link list nodeclass Node {public: int data; Node* next;}; // Function to print linked listvoid printList(Node* node){ // Iterate until node is NOT NULL while (node != NULL) { // Print the data cout << node->data << " "; node = node->next; }} // Function to sort the linked list// consisting of 0s and 1svoid sortList(Node* head){ // Base Case if ((head == NULL) || (head->next == NULL)) { return; } // Store the count of 0s and 1s int count0 = 0, count1 = 0; // Stores the head node Node* temp = head; // Traverse the list Head while (temp != NULL) { // If node->data value is 0 if (temp->data == 0) { // Increment count0 by 1 count0++; } // Otherwise, increment the // count of 1s else { count1++; } // Update the temp node temp = temp->next; } // Update the temp to head temp = head; // Traverse the list and update // the first count0 nodes as 0 while (count0--) { temp->data = 0; temp = temp->next; } // Now, update the value of the // remaining count1 nodes as 1 while (count1--) { temp->data = 1; temp = temp->next; } // Print the Linked List printList(head);} // Function to push a nodevoid push(Node** head_ref, int new_data){ // Allocate node Node* new_node = new Node(); // Put in the data new_node->data = new_data; // Link the old list of the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} // Driver Codeint main(void){ Node* head = NULL; push(&head, 0); push(&head, 1); push(&head, 0); push(&head, 1); push(&head, 1); push(&head, 1); push(&head, 1); push(&head, 1); push(&head, 0); sortList(head); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Link list node static class Node { int data; Node next; }; // Function to print linked list static void printList(Node node) { // Iterate until node is NOT null while (node != null) { // Print the data System.out.print(node.data+ " "); node = node.next; } } // Function to sort the linked list // consisting of 0s and 1s static void sortList(Node head) { // Base Case if ((head == null) || (head.next == null)) { return; } // Store the count of 0s and 1s int count0 = 0, count1 = 0; // Stores the head node Node temp = head; // Traverse the list Head while (temp != null) { // If node.data value is 0 if (temp.data == 0) { // Increment count0 by 1 count0++; } // Otherwise, increment the // count of 1s else { count1++; } // Update the temp node temp = temp.next; } // Update the temp to head temp = head; // Traverse the list and update // the first count0 nodes as 0 while (count0>0) { temp.data = 0; temp = temp.next; count0--; } // Now, update the value of the // remaining count1 nodes as 1 while (count1>0) { temp.data = 1; temp = temp.next; count1--; } // Print the Linked List printList(head); } // Function to push a node static Node push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list of the // new node new_node.next = head_ref; // Move the head to point to // the new node head_ref = new_node; return head_ref; } // Driver Code public static void main(String[] args) { Node head = null; head = push(head, 0); head = push(head, 1); head = push(head, 0); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 0); sortList(head); }} // This code is contributed by umadevi9616
# Python program for the above approach # Link list Nodeclass Node: def __init__(self): self.data = 0; self.next = None; # Function to print linked listdef printList(Node): # Iterate until Node is NOT None while (Node != None): # Print data print(Node.data, end=" "); Node = Node.next; # Function to sort the linked list# consisting of 0s and 1sdef sortList(head): # Base Case if ((head == None) or (head.next == None)): return; # Store the count of 0s and 1s count0 = 0; count1 = 0; # Stores the head Node temp = head; # Traverse the list Head while (temp != None): # If Node.data value is 0 if (temp.data == 0): # Increment count0 by 1 count0 += 1; # Otherwise, increment the # count of 1s else: count1 += 1; # Update the temp Node temp = temp.next; # Update the temp to head temp = head; # Traverse the list and update # the first count0 Nodes as 0 while (count0 > 0): temp.data = 0; temp = temp.next; count0 -= 1; # Now, update the value of the # remaining count1 Nodes as 1 while (count1 > 0): temp.data = 1; temp = temp.next; count1 -= 1; # Print the Linked List printList(head); # Function to push a Nodedef push(head_ref, new_data): # Allocate Node new_Node = Node(); # Put in the data new_Node.data = new_data; # Link the old list of the # new Node new_Node.next = head_ref; # Move the head to point to # the new Node head_ref = new_Node; return head_ref; # Driver Codeif __name__ == '__main__': head = None; head = push(head, 0); head = push(head, 1); head = push(head, 0); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 0); sortList(head); # This code is contributed by umadevi9616
// C# program for the above approachusing System; public class GFG { // Link list nodepublic class Node { public int data; public Node next; }; // Function to print linked list static void printList(Node node) { // Iterate until node is NOT null while (node != null) { // Print the data Console.Write(node.data + " "); node = node.next; } } // Function to sort the linked list // consisting of 0s and 1s static void sortList(Node head) { // Base Case if ((head == null) || (head.next == null)) { return; } // Store the count of 0s and 1s int count0 = 0, count1 = 0; // Stores the head node Node temp = head; // Traverse the list Head while (temp != null) { // If node.data value is 0 if (temp.data == 0) { // Increment count0 by 1 count0++; } // Otherwise, increment the // count of 1s else { count1++; } // Update the temp node temp = temp.next; } // Update the temp to head temp = head; // Traverse the list and update // the first count0 nodes as 0 while (count0 > 0) { temp.data = 0; temp = temp.next; count0--; } // Now, update the value of the // remaining count1 nodes as 1 while (count1 > 0) { temp.data = 1; temp = temp.next; count1--; } // Print the Linked List printList(head); } // Function to push a node static Node push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list of the // new node new_node.next = head_ref; // Move the head to point to // the new node head_ref = new_node; return head_ref; } // Driver Code public static void Main(String[] args) { Node head = null; head = push(head, 0); head = push(head, 1); head = push(head, 0); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 0); sortList(head); }} // This code is contributed by umadevi9616
<script>// javascript program for the above approach // Link list nodeclass Node { constructor() { this.data = 0; this.next = null; }} // Function to print linked list function printList(node) { // Iterate until node is NOT null while (node != null) { // Print the data document.write(node.data + " "); node = node.next; } } // Function to sort the linked list // consisting of 0s and 1s function sortList(head) { // Base Case if ((head == null) || (head.next == null)) { return; } // Store the count of 0s and 1s var count0 = 0, count1 = 0; // Stores the head node var temp = head; // Traverse the list Head while (temp != null) { // If node.data value is 0 if (temp.data == 0) { // Increment count0 by 1 count0++; } // Otherwise, increment the // count of 1s else { count1++; } // Update the temp node temp = temp.next; } // Update the temp to head temp = head; // Traverse the list and update // the first count0 nodes as 0 while (count0 > 0) { temp.data = 0; temp = temp.next; count0--; } // Now, update the value of the // remaining count1 nodes as 1 while (count1 > 0) { temp.data = 1; temp = temp.next; count1--; } // Print the Linked List printList(head); } // Function to push a node function push(head_ref , new_data) { // Allocate node var new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list of the // new node new_node.next = head_ref; // Move the head to point to // the new node head_ref = new_node; return head_ref; } // Driver Code var head = null; head = push(head, 0); head = push(head, 1); head = push(head, 0); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 0); sortList(head); // This code is contributed by umadevi9616</script>
0 0 0 1 1 1 1 1 1
Time Complexity: O(N)Auxiliary Space: O(1)
umadevi9616
khushboogoyal499
simranarora5sos
adnanirshad158
surinderdawra388
Linked Lists
Linked-List-Sorting
Linked List
Sorting
Linked List
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Rearrange a given linked list in-place.
Types of Linked List
Find first node of loop in a linked list
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 180,
"s": 53,
"text": "Given the head of a Linked List of size N, consisting of binary integers 0s and 1s, the task is to sort the given linked list."
},
{
"code": null,
"e": 190,
"s": 180,
"text": "Examples:"
},
{
"code": null,
"e": 282,
"s": 190,
"text": "Input: head = 1 -> 0 -> 1 -> 0 -> 1 -> 0 -> NULL Output: 0 -> 0 -> 0 -> 1 -> 1 -> 1 -> NULL"
},
{
"code": null,
"e": 344,
"s": 282,
"text": "Input: head = 1 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 1 -> NULL"
},
{
"code": null,
"e": 629,
"s": 344,
"text": "Naive Approach: The simplest approach to solve the given problem is to perform the merge sort or insertion sort on the given linked list and sort it. The Implementation of Sorting the Linked list using Merge sort and Sorting the linked list using Insertion sort is discussed already. "
},
{
"code": null,
"e": 680,
"s": 629,
"text": "Time complexity: O(N * log N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 903,
"s": 680,
"text": "Efficient Approach: The above approach can also be optimized by counting the number of 1s and 0s in the given linked list and update the value of nodes accordingly in the linked list. Follow the steps to solve the problem:"
},
{
"code": null,
"e": 1015,
"s": 903,
"text": "Traverse the given linked list and store the count of 0s and 1s in variables, say zeroes and ones respectively."
},
{
"code": null,
"e": 1145,
"s": 1015,
"text": "Now, traverse the linked list again and change the first zeroes nodes with value 0 and then the remaining nodes with the value 1."
},
{
"code": null,
"e": 1231,
"s": 1145,
"text": "After completing the above steps, print the linked list as the resultant sorted list."
},
{
"code": null,
"e": 1282,
"s": 1231,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1286,
"s": 1282,
"text": "C++"
},
{
"code": null,
"e": 1291,
"s": 1286,
"text": "Java"
},
{
"code": null,
"e": 1299,
"s": 1291,
"text": "Python3"
},
{
"code": null,
"e": 1302,
"s": 1299,
"text": "C#"
},
{
"code": null,
"e": 1313,
"s": 1302,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Link list nodeclass Node {public: int data; Node* next;}; // Function to print linked listvoid printList(Node* node){ // Iterate until node is NOT NULL while (node != NULL) { // Print the data cout << node->data << \" \"; node = node->next; }} // Function to sort the linked list// consisting of 0s and 1svoid sortList(Node* head){ // Base Case if ((head == NULL) || (head->next == NULL)) { return; } // Store the count of 0s and 1s int count0 = 0, count1 = 0; // Stores the head node Node* temp = head; // Traverse the list Head while (temp != NULL) { // If node->data value is 0 if (temp->data == 0) { // Increment count0 by 1 count0++; } // Otherwise, increment the // count of 1s else { count1++; } // Update the temp node temp = temp->next; } // Update the temp to head temp = head; // Traverse the list and update // the first count0 nodes as 0 while (count0--) { temp->data = 0; temp = temp->next; } // Now, update the value of the // remaining count1 nodes as 1 while (count1--) { temp->data = 1; temp = temp->next; } // Print the Linked List printList(head);} // Function to push a nodevoid push(Node** head_ref, int new_data){ // Allocate node Node* new_node = new Node(); // Put in the data new_node->data = new_data; // Link the old list of the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} // Driver Codeint main(void){ Node* head = NULL; push(&head, 0); push(&head, 1); push(&head, 0); push(&head, 1); push(&head, 1); push(&head, 1); push(&head, 1); push(&head, 1); push(&head, 0); sortList(head); return 0;}",
"e": 3308,
"s": 1313,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Link list node static class Node { int data; Node next; }; // Function to print linked list static void printList(Node node) { // Iterate until node is NOT null while (node != null) { // Print the data System.out.print(node.data+ \" \"); node = node.next; } } // Function to sort the linked list // consisting of 0s and 1s static void sortList(Node head) { // Base Case if ((head == null) || (head.next == null)) { return; } // Store the count of 0s and 1s int count0 = 0, count1 = 0; // Stores the head node Node temp = head; // Traverse the list Head while (temp != null) { // If node.data value is 0 if (temp.data == 0) { // Increment count0 by 1 count0++; } // Otherwise, increment the // count of 1s else { count1++; } // Update the temp node temp = temp.next; } // Update the temp to head temp = head; // Traverse the list and update // the first count0 nodes as 0 while (count0>0) { temp.data = 0; temp = temp.next; count0--; } // Now, update the value of the // remaining count1 nodes as 1 while (count1>0) { temp.data = 1; temp = temp.next; count1--; } // Print the Linked List printList(head); } // Function to push a node static Node push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list of the // new node new_node.next = head_ref; // Move the head to point to // the new node head_ref = new_node; return head_ref; } // Driver Code public static void main(String[] args) { Node head = null; head = push(head, 0); head = push(head, 1); head = push(head, 0); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 0); sortList(head); }} // This code is contributed by umadevi9616",
"e": 5446,
"s": 3308,
"text": null
},
{
"code": "# Python program for the above approach # Link list Nodeclass Node: def __init__(self): self.data = 0; self.next = None; # Function to print linked listdef printList(Node): # Iterate until Node is NOT None while (Node != None): # Print data print(Node.data, end=\" \"); Node = Node.next; # Function to sort the linked list# consisting of 0s and 1sdef sortList(head): # Base Case if ((head == None) or (head.next == None)): return; # Store the count of 0s and 1s count0 = 0; count1 = 0; # Stores the head Node temp = head; # Traverse the list Head while (temp != None): # If Node.data value is 0 if (temp.data == 0): # Increment count0 by 1 count0 += 1; # Otherwise, increment the # count of 1s else: count1 += 1; # Update the temp Node temp = temp.next; # Update the temp to head temp = head; # Traverse the list and update # the first count0 Nodes as 0 while (count0 > 0): temp.data = 0; temp = temp.next; count0 -= 1; # Now, update the value of the # remaining count1 Nodes as 1 while (count1 > 0): temp.data = 1; temp = temp.next; count1 -= 1; # Print the Linked List printList(head); # Function to push a Nodedef push(head_ref, new_data): # Allocate Node new_Node = Node(); # Put in the data new_Node.data = new_data; # Link the old list of the # new Node new_Node.next = head_ref; # Move the head to point to # the new Node head_ref = new_Node; return head_ref; # Driver Codeif __name__ == '__main__': head = None; head = push(head, 0); head = push(head, 1); head = push(head, 0); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 0); sortList(head); # This code is contributed by umadevi9616",
"e": 7470,
"s": 5446,
"text": null
},
{
"code": "// C# program for the above approachusing System; public class GFG { // Link list nodepublic class Node { public int data; public Node next; }; // Function to print linked list static void printList(Node node) { // Iterate until node is NOT null while (node != null) { // Print the data Console.Write(node.data + \" \"); node = node.next; } } // Function to sort the linked list // consisting of 0s and 1s static void sortList(Node head) { // Base Case if ((head == null) || (head.next == null)) { return; } // Store the count of 0s and 1s int count0 = 0, count1 = 0; // Stores the head node Node temp = head; // Traverse the list Head while (temp != null) { // If node.data value is 0 if (temp.data == 0) { // Increment count0 by 1 count0++; } // Otherwise, increment the // count of 1s else { count1++; } // Update the temp node temp = temp.next; } // Update the temp to head temp = head; // Traverse the list and update // the first count0 nodes as 0 while (count0 > 0) { temp.data = 0; temp = temp.next; count0--; } // Now, update the value of the // remaining count1 nodes as 1 while (count1 > 0) { temp.data = 1; temp = temp.next; count1--; } // Print the Linked List printList(head); } // Function to push a node static Node push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list of the // new node new_node.next = head_ref; // Move the head to point to // the new node head_ref = new_node; return head_ref; } // Driver Code public static void Main(String[] args) { Node head = null; head = push(head, 0); head = push(head, 1); head = push(head, 0); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 0); sortList(head); }} // This code is contributed by umadevi9616",
"e": 9977,
"s": 7470,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Link list nodeclass Node { constructor() { this.data = 0; this.next = null; }} // Function to print linked list function printList(node) { // Iterate until node is NOT null while (node != null) { // Print the data document.write(node.data + \" \"); node = node.next; } } // Function to sort the linked list // consisting of 0s and 1s function sortList(head) { // Base Case if ((head == null) || (head.next == null)) { return; } // Store the count of 0s and 1s var count0 = 0, count1 = 0; // Stores the head node var temp = head; // Traverse the list Head while (temp != null) { // If node.data value is 0 if (temp.data == 0) { // Increment count0 by 1 count0++; } // Otherwise, increment the // count of 1s else { count1++; } // Update the temp node temp = temp.next; } // Update the temp to head temp = head; // Traverse the list and update // the first count0 nodes as 0 while (count0 > 0) { temp.data = 0; temp = temp.next; count0--; } // Now, update the value of the // remaining count1 nodes as 1 while (count1 > 0) { temp.data = 1; temp = temp.next; count1--; } // Print the Linked List printList(head); } // Function to push a node function push(head_ref , new_data) { // Allocate node var new_node = new Node(); // Put in the data new_node.data = new_data; // Link the old list of the // new node new_node.next = head_ref; // Move the head to point to // the new node head_ref = new_node; return head_ref; } // Driver Code var head = null; head = push(head, 0); head = push(head, 1); head = push(head, 0); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 1); head = push(head, 0); sortList(head); // This code is contributed by umadevi9616</script>",
"e": 12432,
"s": 9977,
"text": null
},
{
"code": null,
"e": 12450,
"s": 12432,
"text": "0 0 0 1 1 1 1 1 1"
},
{
"code": null,
"e": 12495,
"s": 12452,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12507,
"s": 12495,
"text": "umadevi9616"
},
{
"code": null,
"e": 12524,
"s": 12507,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 12540,
"s": 12524,
"text": "simranarora5sos"
},
{
"code": null,
"e": 12555,
"s": 12540,
"text": "adnanirshad158"
},
{
"code": null,
"e": 12572,
"s": 12555,
"text": "surinderdawra388"
},
{
"code": null,
"e": 12585,
"s": 12572,
"text": "Linked Lists"
},
{
"code": null,
"e": 12605,
"s": 12585,
"text": "Linked-List-Sorting"
},
{
"code": null,
"e": 12617,
"s": 12605,
"text": "Linked List"
},
{
"code": null,
"e": 12625,
"s": 12617,
"text": "Sorting"
},
{
"code": null,
"e": 12637,
"s": 12625,
"text": "Linked List"
},
{
"code": null,
"e": 12645,
"s": 12637,
"text": "Sorting"
},
{
"code": null,
"e": 12743,
"s": 12645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12775,
"s": 12743,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 12839,
"s": 12775,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 12879,
"s": 12839,
"text": "Rearrange a given linked list in-place."
},
{
"code": null,
"e": 12900,
"s": 12879,
"text": "Types of Linked List"
},
{
"code": null,
"e": 12941,
"s": 12900,
"text": "Find first node of loop in a linked list"
},
{
"code": null,
"e": 12952,
"s": 12941,
"text": "Merge Sort"
},
{
"code": null,
"e": 12974,
"s": 12952,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 12984,
"s": 12974,
"text": "QuickSort"
},
{
"code": null,
"e": 12999,
"s": 12984,
"text": "Insertion Sort"
}
] |
std::next in C++ | 02 Aug, 2017
std::next returns an iterator pointing to the element after being advanced by certain no. of positions. It is defined inside the header file .
It does not modify its arguments and returns a copy of the argument advanced by the specified amount. If it is a random-access iterator, the function uses just once operator + or operator – for advancing. Otherwise, the function uses repeatedly the increase or decrease operator (operator ++ or operator –) on the copied iterator until n elements have been advanced.
Syntax:
ForwardIterator next (ForwardIterator it,
typename iterator_traits::difference_type n = 1);
it: Iterator to the base position.
difference_type: It is the numerical type that represents
distances between iterators of the ForwardIterator type.
n: Total no. of positions by which the
iterator has to be advanced. In the syntax, n is assigned
a default value 1 so it will atleast advance by 1 position.
Returns: It returns an iterator to the element
n positions away from it.
// C++ program to demonstrate std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3, 4, 5, 6, 7 }; // Declaring another container deque<int> v2 = { 8, 9, 10 }; // Declaring an iterator deque<int>::iterator i1; // i1 points to 1 i1 = v1.begin(); // Declaring another iterator to store return // value and using std::next deque<int>::iterator i2; i2 = std::next(i1, 4); // Using std::copy std::copy(i1, i2, std::back_inserter(v2)); // Remember, i1 stills points to 1 // and i2 points to 5 // v2 now contains 8 9 10 1 2 3 4 // Displaying v1 and v2 cout << "v1 = "; int i; for (i = 0; i < 7; ++i) { cout << v1[i] << " "; } cout << "\nv2 = "; for (i = 0; i < 7; ++i) { cout << v2[i] << " "; } return 0;}
Output:
v1 = 1 2 3 4 5 6 7
v2 = 8 9 10 1 2 3 4
How can it be helpful ?
Advancing iterator in Lists: Since, lists support bidirectional iterators, which can be incremented only by using ++ and – – operator. So, if we want to advance the iterator by more than one position, then using std::next can be extremely useful.// C++ program to demonstrate std::next#include <iostream>#include <iterator>#include <list>#include <algorithm>using namespace std;int main(){ // Declaring first container list<int> v1 = { 1, 2, 3, 7, 8, 9 }; // Declaring second container list<int> v2 = { 4, 5, 6 }; list<int>::iterator i1; i1 = v1.begin(); // i1 points to 1 in v1 list<int>::iterator i2; // i2 = v1.begin() + 3; // This cannot be used with lists // so use std::next for this i2 = std::next(i1, 3); // Using std::copy std::copy(i1, i2, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 3 // Displaying v1 and v2 cout << "v1 = "; int i; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { cout << *i1 << " "; } cout << "\nv2 = "; for (i1 = v2.begin(); i1 != v2.end(); ++i1) { cout << *i1 << " "; } return 0;}Output:v1 = 1 2 3 7 8 9
v2 = 4 5 6 1 2 3
Explanation: Here, just look how if we want copy only a selected portion of the list, then we can make use of std::next, as otherwise we cannot use any +=, -= operators with bidirectional iterators supported by lists. So, we used std::next and directly advanced the iterator by three positions.
// C++ program to demonstrate std::next#include <iostream>#include <iterator>#include <list>#include <algorithm>using namespace std;int main(){ // Declaring first container list<int> v1 = { 1, 2, 3, 7, 8, 9 }; // Declaring second container list<int> v2 = { 4, 5, 6 }; list<int>::iterator i1; i1 = v1.begin(); // i1 points to 1 in v1 list<int>::iterator i2; // i2 = v1.begin() + 3; // This cannot be used with lists // so use std::next for this i2 = std::next(i1, 3); // Using std::copy std::copy(i1, i2, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 3 // Displaying v1 and v2 cout << "v1 = "; int i; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { cout << *i1 << " "; } cout << "\nv2 = "; for (i1 = v2.begin(); i1 != v2.end(); ++i1) { cout << *i1 << " "; } return 0;}
Output:
v1 = 1 2 3 7 8 9
v2 = 4 5 6 1 2 3
Explanation: Here, just look how if we want copy only a selected portion of the list, then we can make use of std::next, as otherwise we cannot use any +=, -= operators with bidirectional iterators supported by lists. So, we used std::next and directly advanced the iterator by three positions.
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.
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": 52,
"s": 24,
"text": "\n02 Aug, 2017"
},
{
"code": null,
"e": 195,
"s": 52,
"text": "std::next returns an iterator pointing to the element after being advanced by certain no. of positions. It is defined inside the header file ."
},
{
"code": null,
"e": 562,
"s": 195,
"text": "It does not modify its arguments and returns a copy of the argument advanced by the specified amount. If it is a random-access iterator, the function uses just once operator + or operator – for advancing. Otherwise, the function uses repeatedly the increase or decrease operator (operator ++ or operator –) on the copied iterator until n elements have been advanced."
},
{
"code": null,
"e": 570,
"s": 562,
"text": "Syntax:"
},
{
"code": null,
"e": 1054,
"s": 570,
"text": "ForwardIterator next (ForwardIterator it,\n typename iterator_traits::difference_type n = 1);\nit: Iterator to the base position.\ndifference_type: It is the numerical type that represents \ndistances between iterators of the ForwardIterator type.\nn: Total no. of positions by which the\niterator has to be advanced. In the syntax, n is assigned\na default value 1 so it will atleast advance by 1 position.\n\nReturns: It returns an iterator to the element \nn positions away from it.\n\n"
},
{
"code": "// C++ program to demonstrate std::next#include <iostream>#include <iterator>#include <deque>#include <algorithm>using namespace std;int main(){ // Declaring first container deque<int> v1 = { 1, 2, 3, 4, 5, 6, 7 }; // Declaring another container deque<int> v2 = { 8, 9, 10 }; // Declaring an iterator deque<int>::iterator i1; // i1 points to 1 i1 = v1.begin(); // Declaring another iterator to store return // value and using std::next deque<int>::iterator i2; i2 = std::next(i1, 4); // Using std::copy std::copy(i1, i2, std::back_inserter(v2)); // Remember, i1 stills points to 1 // and i2 points to 5 // v2 now contains 8 9 10 1 2 3 4 // Displaying v1 and v2 cout << \"v1 = \"; int i; for (i = 0; i < 7; ++i) { cout << v1[i] << \" \"; } cout << \"\\nv2 = \"; for (i = 0; i < 7; ++i) { cout << v2[i] << \" \"; } return 0;}",
"e": 1979,
"s": 1054,
"text": null
},
{
"code": null,
"e": 1987,
"s": 1979,
"text": "Output:"
},
{
"code": null,
"e": 2027,
"s": 1987,
"text": "v1 = 1 2 3 4 5 6 7\nv2 = 8 9 10 1 2 3 4\n"
},
{
"code": null,
"e": 2051,
"s": 2027,
"text": "How can it be helpful ?"
},
{
"code": null,
"e": 3512,
"s": 2051,
"text": "Advancing iterator in Lists: Since, lists support bidirectional iterators, which can be incremented only by using ++ and – – operator. So, if we want to advance the iterator by more than one position, then using std::next can be extremely useful.// C++ program to demonstrate std::next#include <iostream>#include <iterator>#include <list>#include <algorithm>using namespace std;int main(){ // Declaring first container list<int> v1 = { 1, 2, 3, 7, 8, 9 }; // Declaring second container list<int> v2 = { 4, 5, 6 }; list<int>::iterator i1; i1 = v1.begin(); // i1 points to 1 in v1 list<int>::iterator i2; // i2 = v1.begin() + 3; // This cannot be used with lists // so use std::next for this i2 = std::next(i1, 3); // Using std::copy std::copy(i1, i2, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 3 // Displaying v1 and v2 cout << \"v1 = \"; int i; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { cout << *i1 << \" \"; } cout << \"\\nv2 = \"; for (i1 = v2.begin(); i1 != v2.end(); ++i1) { cout << *i1 << \" \"; } return 0;}Output:v1 = 1 2 3 7 8 9\nv2 = 4 5 6 1 2 3 \nExplanation: Here, just look how if we want copy only a selected portion of the list, then we can make use of std::next, as otherwise we cannot use any +=, -= operators with bidirectional iterators supported by lists. So, we used std::next and directly advanced the iterator by three positions."
},
{
"code": "// C++ program to demonstrate std::next#include <iostream>#include <iterator>#include <list>#include <algorithm>using namespace std;int main(){ // Declaring first container list<int> v1 = { 1, 2, 3, 7, 8, 9 }; // Declaring second container list<int> v2 = { 4, 5, 6 }; list<int>::iterator i1; i1 = v1.begin(); // i1 points to 1 in v1 list<int>::iterator i2; // i2 = v1.begin() + 3; // This cannot be used with lists // so use std::next for this i2 = std::next(i1, 3); // Using std::copy std::copy(i1, i2, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 3 // Displaying v1 and v2 cout << \"v1 = \"; int i; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { cout << *i1 << \" \"; } cout << \"\\nv2 = \"; for (i1 = v2.begin(); i1 != v2.end(); ++i1) { cout << *i1 << \" \"; } return 0;}",
"e": 4390,
"s": 3512,
"text": null
},
{
"code": null,
"e": 4398,
"s": 4390,
"text": "Output:"
},
{
"code": null,
"e": 4435,
"s": 4398,
"text": "v1 = 1 2 3 7 8 9\nv2 = 4 5 6 1 2 3 \n"
},
{
"code": null,
"e": 4730,
"s": 4435,
"text": "Explanation: Here, just look how if we want copy only a selected portion of the list, then we can make use of std::next, as otherwise we cannot use any +=, -= operators with bidirectional iterators supported by lists. So, we used std::next and directly advanced the iterator by three positions."
},
{
"code": null,
"e": 5033,
"s": 4730,
"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": 5158,
"s": 5033,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5171,
"s": 5158,
"text": "cpp-iterator"
},
{
"code": null,
"e": 5175,
"s": 5171,
"text": "STL"
},
{
"code": null,
"e": 5179,
"s": 5175,
"text": "C++"
},
{
"code": null,
"e": 5183,
"s": 5179,
"text": "STL"
},
{
"code": null,
"e": 5187,
"s": 5183,
"text": "CPP"
}
] |
Ruby | Operators | 10 Feb, 2022
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Ruby as follows:
Arithmetic Operators
These are used to perform arithmetic/mathematical operations on operands.
Addition(+): operator adds two operands. For example, x+y.
Subtraction(-): operator subtracts two operands. For example, x-y.
Multiplication(*): operator multiplies two operands. For example, x*y.
Division(/): operator divides the first operand by the second. For example, x/y.
Modulus(%): operator returns the remainder when first operand is divided by the second. For example, x%y.
Exponent(**): operator returns exponential(power) of the operands. For example, x**y.
Example:
Ruby
# Ruby program to demonstrate# the Arithmetic Operators # Additionputs ("Addition:")puts (10 + 20) # Subtractionputs ("Subtraction:")puts (40 - 20) # Divisionputs ("Division:")puts (100 / 20) # Multiplicationputs ("Multiplication:")puts (10 * 20) # Modulusputs ("Modulus:")puts (20 % 7) # Exponentputs ("Exponent:")puts (2 ** 4)
Output:
Addition:
30
Subtraction:
20
Division:
5
Multiplication:
200
Modulus:
6
Exponent:
16
Comparison Operators
Comparison operators or Relational operators are used for comparison of two values. Let’s see them one by one:
Equal To(==) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true.
Not Equal To(!=) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false.
Greater Than(>) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
Less than(<) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false.
Greater Than Equal To(>=) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true.
Less Than Equal To(<=) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true.
Combined combination (<=>) operator return 0 when first operand equal to second, return 1 when first operand is greater than second operand, and return -1 when first operator is less than second operand.
Case Equality Operator(===) It will test equality in case statement.
‘.eql?’ This operator returns true if the receiver and argument have both the same type and equal values.
‘Equal?’ This operator Returns true if if the receiver and argument have the same object id.
Example:
Ruby
# Ruby program to demonstrate# the Comparison Operators puts "Equal To Operator:"puts (10 == 20) puts "Not Equal To Operator:"puts (40 != 20) puts "Greater than Operator"puts (100 > 20) puts "Less than Operator"puts (10 < 20) puts "Less than Equal To Operator"puts (2 <= 5) puts "Greater than Equal To Operator"puts (2 >= 5) puts "Combined combination operator"puts(20 <=> 20)puts(10 <=> 20)puts(20 <=> 10)
Output:
Equal To Operator:
false
Not Equal To Operator:
true
Greater than Operator
true
Less than Operator
true
Less than Equal To Operator
true
Greater than Equal To Operator
false
Combined combination operator
0
-1
1
Logical Operators
They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:
Logical AND(&&) operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. Using “and” is an alternate for && operator. For example, a && b returns true when both a and b are true (i.e. non-zero).
Logical OR(||) operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. Using “or” is an alternate for || operator. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.
Logical NOT(!): operator returns true the condition in consideration is not satisfied. Otherwise it returns false. Using “not” is an alternate for ! operator. For example, !true returns false.
Example:
Ruby
# Ruby program to demonstrate# the Logical Operators # Variablesa = 10b = 20c = 30 # using && operatorif a == 10 && b == 20 && c == 30 puts "Logical AND Operator" puts result = a * b * cend # using || operatorputs "Logical OR operator"if a == 10 || b == 20 puts result = a + b + cend # using ! operatorputs "Logical Not Operator"puts !(true)
Output:
Logical AND Operator
6000
Logical OR operator
60
Logical Not Operator
false
Assignment Operators
Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below:
Simple Assignment (=): operator is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.
Add AND Assignment (+=) operator is used for adding left operand with right operand and then assigning it to variable on the left.
Subtract AND Assignment (-=) operator is used for subtracting left operand with right operand and then assigning it to variable on the left.
Multiply AND Assignment (*=) operator is used for multiplying left operand with right operand and then assigning it to variable on the left.
Divide AND Assignment (/=) operator is used for dividing left operand with right operand and then assigning it to variable on the left.
Modulus AND Assignment (%=) operator is used for assigning modulo of left operand with right operand and then assigning it to variable on the left.
Exponent AND Assignment (**=) operator is used for raising power of left operand to right operand and assigning it to variable on the left.
Example:
Ruby
# Ruby program to demonstrate# the Assignments Operators puts "Simple assignment operator"puts a = 20 puts "Add AND assignment operator"puts a += 10 puts "Subtract AND assignment operator"puts a -= 5 puts "Multiply AND assignment operator"puts a *= 10 puts "Divide AND assignment operator"puts a /= 4 puts "Modulus AND assignment operator"puts a %= 3 puts "Exponent AND assignment operator"puts a **= 3
Output:
Simple assignment operator
20
Add AND assignment operator
30
Subtract AND assignment operator
25
Multiply AND assignment operator
250
Divide AND assignment operator
62
Modulus AND assignment operator
2
Exponent AND assignment operator
8
Bitwise Operators
In Ruby, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators :
Bitwise AND (&) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
Bitwise OR (|) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
Bitwise XOR (^) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
Left Shift (<<) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
Right Shift (>>) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.
Ones Complement (~) This operator takes a single number and used to perform complement operation of 8-bit.
Example:
Ruby
# Ruby program to demonstrate# the Bitwise Operators # variablesa = 10b = 20 puts "Bitwise AND operator"puts (a & b) puts "Bitwise OR operator"puts (a |b) puts "Bitwise XOR operator"puts (a ^ b) puts "Bitwise Complement operator"puts (~a) puts "Binary right shift operator"puts (a >> 2) puts "Binary left shift operator"puts (a << 2)
Output:
Bitwise AND operator
0
Bitwise OR operator
30
Bitwise XOR operator
30
Bitwise Complement operator
-11
Binary right shift operator
2
Binary left shift operator
40
Ternary Operator
It is a conditional operator which is a shorthand version of the if-else statement. It has three operands and hence the name ternary. It will return one of two values depending on the value of a Boolean expression. Syntax :
condition ? first_expression : second_expression;
Explanation :
condition: It be evaluated to true or false.
If the condition is true
first_expression is evaluated and becomes the result.
If the condition is false,
second_expression is evaluated and becomes the result.
Example :
Ruby
# Ruby program to demonstrate# the Ternary Operator # variablemarks_obtained = 100 # using ternary operatorresult = marks_obtained > 40 ? 'Pass' : 'Fail' # displaying outputputs result
Output:
Pass
Range Operators
In Ruby, range operators are used for creating the specified sequence range of specified elements. There are two range operators in Ruby as follows:
Double Dot (..) operator is used to create a specified sequence range in which both the starting and ending element will be inclusive. For example, 7 .. 10 will create a sequence like 7, 8, 9, 10.
Triple Dot (...) operator is used to create a specified sequence range in which only starting element will be inclusive and ending element will be exclusive. For example, 7 .. 10 will create a sequence like 7, 8, 9.
Example:
Ruby
# Ruby program to demonstrate# the Range Operator # Array value separator$, =", " # using .. Operatorrange_op = (7 .. 10).to_a # displaying resultputs "#{range_op}" # using ... Operatorrange_op1 = (7 ... 10).to_a # displaying resultputs "#{range_op1}"
Output:
[7, 8, 9, 10]
[7, 8, 9]
defined? Operator
The defined? the operator is a special operator which is used to check whether the passed expression is defined or not. It returns nil if passed argument is not defined, otherwise, it returns a string of that argument which defines that.Syntax:
defined? expression_to_be_checked
Example:
Ruby
# Ruby program to demonstrate# the defined? Operator # variablesGFG = 1Geeks = 70 puts ("define? Operator Results") # using defined? Operator# it returns constantputs defined? GFG # it returns constantputs defined? Geeks # it returns expressionputs defined? a # it returns expressionputs defined? 50
Output:
define? Operator Results
constant
constant
expression
Dot “.” and Double Colon “::” Operators
Dot (.) operator is used to access the methods of a class.
Double Colon (::) operator is used to access the constants, class methods, and instance methods defined within a class or module to anywhere outside the class or module. The important point to remember is that classes and methods may be considered constants in Ruby and also prefix the :: Const_name with the expression which returns the appropriate class object. If no prefix expression is used then by default the main Object class is used.
Example:
Ruby
# Ruby program to demonstrate# Dot “.” and Double Colon# “::” Operators # defined constant on main Object classCONS = 5 # define modulemodule Geeks CONS = 5 # set global CONS to 7 ::CONS = 7 # set local CONS to 10 CONS = 10 end # displaying global CONS valueputs CONS # displaying local "Geeks" CONS value# using :: operatorputs Geeks::CONS class Gfg def Geeks2 puts "Dot Operator" endend # calling Geeks2 module using# Dot(.) operatorputs Gfg.new.Geeks2
Output:
7
10
Dot Operator
main.rb:14: warning: already initialized constant CONS
main.rb:6: warning: previous definition of CONS was here
main.rb:17: warning: already initialized constant Geeks::CONS
main.rb:11: warning: previous definition of CONS was here
Akanksha_Rai
surinderdawra388
sagartomar9927
simranarora5sos
Ruby-Basics
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Ruby | Array class find_index() operation | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 345,
"s": 53,
"text": "An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Ruby as follows: "
},
{
"code": null,
"e": 366,
"s": 345,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 442,
"s": 366,
"text": "These are used to perform arithmetic/mathematical operations on operands. "
},
{
"code": null,
"e": 501,
"s": 442,
"text": "Addition(+): operator adds two operands. For example, x+y."
},
{
"code": null,
"e": 568,
"s": 501,
"text": "Subtraction(-): operator subtracts two operands. For example, x-y."
},
{
"code": null,
"e": 639,
"s": 568,
"text": "Multiplication(*): operator multiplies two operands. For example, x*y."
},
{
"code": null,
"e": 720,
"s": 639,
"text": "Division(/): operator divides the first operand by the second. For example, x/y."
},
{
"code": null,
"e": 826,
"s": 720,
"text": "Modulus(%): operator returns the remainder when first operand is divided by the second. For example, x%y."
},
{
"code": null,
"e": 912,
"s": 826,
"text": "Exponent(**): operator returns exponential(power) of the operands. For example, x**y."
},
{
"code": null,
"e": 922,
"s": 912,
"text": "Example: "
},
{
"code": null,
"e": 927,
"s": 922,
"text": "Ruby"
},
{
"code": "# Ruby program to demonstrate# the Arithmetic Operators # Additionputs (\"Addition:\")puts (10 + 20) # Subtractionputs (\"Subtraction:\")puts (40 - 20) # Divisionputs (\"Division:\")puts (100 / 20) # Multiplicationputs (\"Multiplication:\")puts (10 * 20) # Modulusputs (\"Modulus:\")puts (20 % 7) # Exponentputs (\"Exponent:\")puts (2 ** 4)",
"e": 1256,
"s": 927,
"text": null
},
{
"code": null,
"e": 1266,
"s": 1256,
"text": "Output: "
},
{
"code": null,
"e": 1351,
"s": 1266,
"text": "Addition:\n30\nSubtraction:\n20\nDivision:\n5\nMultiplication:\n200\nModulus:\n6\nExponent:\n16"
},
{
"code": null,
"e": 1374,
"s": 1353,
"text": "Comparison Operators"
},
{
"code": null,
"e": 1486,
"s": 1374,
"text": "Comparison operators or Relational operators are used for comparison of two values. Let’s see them one by one: "
},
{
"code": null,
"e": 1652,
"s": 1486,
"text": "Equal To(==) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 5==5 will return true."
},
{
"code": null,
"e": 1881,
"s": 1652,
"text": "Not Equal To(!=) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false."
},
{
"code": null,
"e": 2062,
"s": 1881,
"text": "Greater Than(>) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true."
},
{
"code": null,
"e": 2240,
"s": 2062,
"text": "Less than(<) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will return false."
},
{
"code": null,
"e": 2444,
"s": 2240,
"text": "Greater Than Equal To(>=) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true."
},
{
"code": null,
"e": 2649,
"s": 2444,
"text": "Less Than Equal To(<=) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true."
},
{
"code": null,
"e": 2853,
"s": 2649,
"text": "Combined combination (<=>) operator return 0 when first operand equal to second, return 1 when first operand is greater than second operand, and return -1 when first operator is less than second operand."
},
{
"code": null,
"e": 2922,
"s": 2853,
"text": "Case Equality Operator(===) It will test equality in case statement."
},
{
"code": null,
"e": 3028,
"s": 2922,
"text": "‘.eql?’ This operator returns true if the receiver and argument have both the same type and equal values."
},
{
"code": null,
"e": 3121,
"s": 3028,
"text": "‘Equal?’ This operator Returns true if if the receiver and argument have the same object id."
},
{
"code": null,
"e": 3131,
"s": 3121,
"text": "Example: "
},
{
"code": null,
"e": 3136,
"s": 3131,
"text": "Ruby"
},
{
"code": "# Ruby program to demonstrate# the Comparison Operators puts \"Equal To Operator:\"puts (10 == 20) puts \"Not Equal To Operator:\"puts (40 != 20) puts \"Greater than Operator\"puts (100 > 20) puts \"Less than Operator\"puts (10 < 20) puts \"Less than Equal To Operator\"puts (2 <= 5) puts \"Greater than Equal To Operator\"puts (2 >= 5) puts \"Combined combination operator\"puts(20 <=> 20)puts(10 <=> 20)puts(20 <=> 10)",
"e": 3554,
"s": 3136,
"text": null
},
{
"code": null,
"e": 3564,
"s": 3554,
"text": "Output: "
},
{
"code": null,
"e": 3775,
"s": 3564,
"text": "Equal To Operator:\nfalse\nNot Equal To Operator:\ntrue\nGreater than Operator\ntrue\nLess than Operator\ntrue\nLess than Equal To Operator\ntrue\nGreater than Equal To Operator\nfalse\nCombined combination operator\n0\n-1\n1"
},
{
"code": null,
"e": 3795,
"s": 3777,
"text": "Logical Operators"
},
{
"code": null,
"e": 3958,
"s": 3795,
"text": "They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below: "
},
{
"code": null,
"e": 4203,
"s": 3958,
"text": "Logical AND(&&) operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. Using “and” is an alternate for && operator. For example, a && b returns true when both a and b are true (i.e. non-zero)."
},
{
"code": null,
"e": 4510,
"s": 4203,
"text": "Logical OR(||) operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. Using “or” is an alternate for || operator. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true."
},
{
"code": null,
"e": 4703,
"s": 4510,
"text": "Logical NOT(!): operator returns true the condition in consideration is not satisfied. Otherwise it returns false. Using “not” is an alternate for ! operator. For example, !true returns false."
},
{
"code": null,
"e": 4713,
"s": 4703,
"text": "Example: "
},
{
"code": null,
"e": 4718,
"s": 4713,
"text": "Ruby"
},
{
"code": "# Ruby program to demonstrate# the Logical Operators # Variablesa = 10b = 20c = 30 # using && operatorif a == 10 && b == 20 && c == 30 puts \"Logical AND Operator\" puts result = a * b * cend # using || operatorputs \"Logical OR operator\"if a == 10 || b == 20 puts result = a + b + cend # using ! operatorputs \"Logical Not Operator\"puts !(true) ",
"e": 5074,
"s": 4718,
"text": null
},
{
"code": null,
"e": 5084,
"s": 5074,
"text": "Output: "
},
{
"code": null,
"e": 5160,
"s": 5084,
"text": "Logical AND Operator\n6000\nLogical OR operator\n60\nLogical Not Operator\nfalse"
},
{
"code": null,
"e": 5183,
"s": 5162,
"text": "Assignment Operators"
},
{
"code": null,
"e": 5568,
"s": 5183,
"text": "Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below: "
},
{
"code": null,
"e": 5721,
"s": 5568,
"text": "Simple Assignment (=): operator is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left."
},
{
"code": null,
"e": 5852,
"s": 5721,
"text": "Add AND Assignment (+=) operator is used for adding left operand with right operand and then assigning it to variable on the left."
},
{
"code": null,
"e": 5993,
"s": 5852,
"text": "Subtract AND Assignment (-=) operator is used for subtracting left operand with right operand and then assigning it to variable on the left."
},
{
"code": null,
"e": 6134,
"s": 5993,
"text": "Multiply AND Assignment (*=) operator is used for multiplying left operand with right operand and then assigning it to variable on the left."
},
{
"code": null,
"e": 6270,
"s": 6134,
"text": "Divide AND Assignment (/=) operator is used for dividing left operand with right operand and then assigning it to variable on the left."
},
{
"code": null,
"e": 6418,
"s": 6270,
"text": "Modulus AND Assignment (%=) operator is used for assigning modulo of left operand with right operand and then assigning it to variable on the left."
},
{
"code": null,
"e": 6558,
"s": 6418,
"text": "Exponent AND Assignment (**=) operator is used for raising power of left operand to right operand and assigning it to variable on the left."
},
{
"code": null,
"e": 6568,
"s": 6558,
"text": "Example: "
},
{
"code": null,
"e": 6573,
"s": 6568,
"text": "Ruby"
},
{
"code": "# Ruby program to demonstrate# the Assignments Operators puts \"Simple assignment operator\"puts a = 20 puts \"Add AND assignment operator\"puts a += 10 puts \"Subtract AND assignment operator\"puts a -= 5 puts \"Multiply AND assignment operator\"puts a *= 10 puts \"Divide AND assignment operator\"puts a /= 4 puts \"Modulus AND assignment operator\"puts a %= 3 puts \"Exponent AND assignment operator\"puts a **= 3",
"e": 6977,
"s": 6573,
"text": null
},
{
"code": null,
"e": 6987,
"s": 6977,
"text": "Output: "
},
{
"code": null,
"e": 7224,
"s": 6987,
"text": "Simple assignment operator\n20\nAdd AND assignment operator\n30\nSubtract AND assignment operator\n25\nMultiply AND assignment operator\n250\nDivide AND assignment operator\n62\nModulus AND assignment operator\n2\nExponent AND assignment operator\n8"
},
{
"code": null,
"e": 7244,
"s": 7226,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 7389,
"s": 7244,
"text": "In Ruby, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators : "
},
{
"code": null,
"e": 7525,
"s": 7389,
"text": "Bitwise AND (&) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1."
},
{
"code": null,
"e": 7659,
"s": 7525,
"text": "Bitwise OR (|) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1."
},
{
"code": null,
"e": 7801,
"s": 7659,
"text": "Bitwise XOR (^) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different."
},
{
"code": null,
"e": 7937,
"s": 7801,
"text": "Left Shift (<<) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift."
},
{
"code": null,
"e": 8075,
"s": 7937,
"text": "Right Shift (>>) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift."
},
{
"code": null,
"e": 8182,
"s": 8075,
"text": "Ones Complement (~) This operator takes a single number and used to perform complement operation of 8-bit."
},
{
"code": null,
"e": 8193,
"s": 8182,
"text": "Example: "
},
{
"code": null,
"e": 8198,
"s": 8193,
"text": "Ruby"
},
{
"code": "# Ruby program to demonstrate# the Bitwise Operators # variablesa = 10b = 20 puts \"Bitwise AND operator\"puts (a & b) puts \"Bitwise OR operator\"puts (a |b) puts \"Bitwise XOR operator\"puts (a ^ b) puts \"Bitwise Complement operator\"puts (~a) puts \"Binary right shift operator\"puts (a >> 2) puts \"Binary left shift operator\"puts (a << 2)",
"e": 8532,
"s": 8198,
"text": null
},
{
"code": null,
"e": 8542,
"s": 8532,
"text": "Output: "
},
{
"code": null,
"e": 8704,
"s": 8542,
"text": "Bitwise AND operator\n0\nBitwise OR operator\n30\nBitwise XOR operator\n30\nBitwise Complement operator\n-11\nBinary right shift operator\n2\nBinary left shift operator\n40"
},
{
"code": null,
"e": 8723,
"s": 8706,
"text": "Ternary Operator"
},
{
"code": null,
"e": 8949,
"s": 8723,
"text": "It is a conditional operator which is a shorthand version of the if-else statement. It has three operands and hence the name ternary. It will return one of two values depending on the value of a Boolean expression. Syntax : "
},
{
"code": null,
"e": 8999,
"s": 8949,
"text": "condition ? first_expression : second_expression;"
},
{
"code": null,
"e": 9015,
"s": 8999,
"text": "Explanation : "
},
{
"code": null,
"e": 9228,
"s": 9015,
"text": "condition: It be evaluated to true or false.\n\nIf the condition is true\n first_expression is evaluated and becomes the result. \n\nIf the condition is false, \n second_expression is evaluated and becomes the result. "
},
{
"code": null,
"e": 9239,
"s": 9228,
"text": "Example : "
},
{
"code": null,
"e": 9244,
"s": 9239,
"text": "Ruby"
},
{
"code": "# Ruby program to demonstrate# the Ternary Operator # variablemarks_obtained = 100 # using ternary operatorresult = marks_obtained > 40 ? 'Pass' : 'Fail' # displaying outputputs result",
"e": 9429,
"s": 9244,
"text": null
},
{
"code": null,
"e": 9439,
"s": 9429,
"text": "Output: "
},
{
"code": null,
"e": 9444,
"s": 9439,
"text": "Pass"
},
{
"code": null,
"e": 9462,
"s": 9446,
"text": "Range Operators"
},
{
"code": null,
"e": 9612,
"s": 9462,
"text": "In Ruby, range operators are used for creating the specified sequence range of specified elements. There are two range operators in Ruby as follows: "
},
{
"code": null,
"e": 9809,
"s": 9612,
"text": "Double Dot (..) operator is used to create a specified sequence range in which both the starting and ending element will be inclusive. For example, 7 .. 10 will create a sequence like 7, 8, 9, 10."
},
{
"code": null,
"e": 10025,
"s": 9809,
"text": "Triple Dot (...) operator is used to create a specified sequence range in which only starting element will be inclusive and ending element will be exclusive. For example, 7 .. 10 will create a sequence like 7, 8, 9."
},
{
"code": null,
"e": 10035,
"s": 10025,
"text": "Example: "
},
{
"code": null,
"e": 10040,
"s": 10035,
"text": "Ruby"
},
{
"code": "# Ruby program to demonstrate# the Range Operator # Array value separator$, =\", \" # using .. Operatorrange_op = (7 .. 10).to_a # displaying resultputs \"#{range_op}\" # using ... Operatorrange_op1 = (7 ... 10).to_a # displaying resultputs \"#{range_op1}\"",
"e": 10293,
"s": 10040,
"text": null
},
{
"code": null,
"e": 10303,
"s": 10293,
"text": "Output: "
},
{
"code": null,
"e": 10327,
"s": 10303,
"text": "[7, 8, 9, 10]\n[7, 8, 9]"
},
{
"code": null,
"e": 10347,
"s": 10329,
"text": "defined? Operator"
},
{
"code": null,
"e": 10593,
"s": 10347,
"text": "The defined? the operator is a special operator which is used to check whether the passed expression is defined or not. It returns nil if passed argument is not defined, otherwise, it returns a string of that argument which defines that.Syntax: "
},
{
"code": null,
"e": 10628,
"s": 10593,
"text": "defined? expression_to_be_checked "
},
{
"code": null,
"e": 10639,
"s": 10628,
"text": "Example: "
},
{
"code": null,
"e": 10644,
"s": 10639,
"text": "Ruby"
},
{
"code": "# Ruby program to demonstrate# the defined? Operator # variablesGFG = 1Geeks = 70 puts (\"define? Operator Results\") # using defined? Operator# it returns constantputs defined? GFG # it returns constantputs defined? Geeks # it returns expressionputs defined? a # it returns expressionputs defined? 50 ",
"e": 10963,
"s": 10644,
"text": null
},
{
"code": null,
"e": 10973,
"s": 10963,
"text": "Output: "
},
{
"code": null,
"e": 11028,
"s": 10973,
"text": "define? Operator Results\nconstant\nconstant\n\nexpression"
},
{
"code": null,
"e": 11070,
"s": 11030,
"text": "Dot “.” and Double Colon “::” Operators"
},
{
"code": null,
"e": 11131,
"s": 11072,
"text": "Dot (.) operator is used to access the methods of a class."
},
{
"code": null,
"e": 11574,
"s": 11131,
"text": "Double Colon (::) operator is used to access the constants, class methods, and instance methods defined within a class or module to anywhere outside the class or module. The important point to remember is that classes and methods may be considered constants in Ruby and also prefix the :: Const_name with the expression which returns the appropriate class object. If no prefix expression is used then by default the main Object class is used."
},
{
"code": null,
"e": 11585,
"s": 11574,
"text": "Example: "
},
{
"code": null,
"e": 11590,
"s": 11585,
"text": "Ruby"
},
{
"code": "# Ruby program to demonstrate# Dot “.” and Double Colon# “::” Operators # defined constant on main Object classCONS = 5 # define modulemodule Geeks CONS = 5 # set global CONS to 7 ::CONS = 7 # set local CONS to 10 CONS = 10 end # displaying global CONS valueputs CONS # displaying local \"Geeks\" CONS value# using :: operatorputs Geeks::CONS class Gfg def Geeks2 puts \"Dot Operator\" endend # calling Geeks2 module using# Dot(.) operatorputs Gfg.new.Geeks2",
"e": 12094,
"s": 11590,
"text": null
},
{
"code": null,
"e": 12104,
"s": 12094,
"text": "Output: "
},
{
"code": null,
"e": 12355,
"s": 12104,
"text": "7\n10\nDot Operator\n\nmain.rb:14: warning: already initialized constant CONS\nmain.rb:6: warning: previous definition of CONS was here\nmain.rb:17: warning: already initialized constant Geeks::CONS\nmain.rb:11: warning: previous definition of CONS was here"
},
{
"code": null,
"e": 12370,
"s": 12357,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 12387,
"s": 12370,
"text": "surinderdawra388"
},
{
"code": null,
"e": 12402,
"s": 12387,
"text": "sagartomar9927"
},
{
"code": null,
"e": 12418,
"s": 12402,
"text": "simranarora5sos"
},
{
"code": null,
"e": 12430,
"s": 12418,
"text": "Ruby-Basics"
},
{
"code": null,
"e": 12435,
"s": 12430,
"text": "Ruby"
},
{
"code": null,
"e": 12533,
"s": 12435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12579,
"s": 12533,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 12606,
"s": 12579,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 12630,
"s": 12606,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 12673,
"s": 12630,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 12704,
"s": 12673,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 12726,
"s": 12704,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 12770,
"s": 12726,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 12800,
"s": 12770,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 12818,
"s": 12800,
"text": "Ruby | Data Types"
}
] |
Replace Character Value with NA in R | 29 Sep, 2021
In this article, we are going to see how to replace character value with NA in R Programming Language.
We can replace a character value with NA in a vector and in a dataframe.
In a vector, we can replace it by using the indexing operation.
Syntax:
vector[vector == “character”] <- NA
R
# create a vector with 10 charactersvector = c("a", "d", "A", "g", "S", "S", "t", "S", "e", "S") # store actual vector in finalfinal = vector # replace character S with NAfinal[final == "S"] <- NA # display final vectorprint(final)
Output:
[1] "a" "d" "A" "g" NA NA "t" NA "e" NA
Replace character value with NA in dataframe.
Syntax:
dataframe[dataframe== “character”] <- NA
R
# create a dataframe with 10 charactersdata = data.frame("a", "d", "A", "g", "S", "S", "t", "S", "e", "S") # store actual dataframe in finalfinal = data # replace character A with NAfinal[final == "A"] <- NA # display final dataframeprint(final)
Output:
X.a. X.d. X.A. X.g. X.S. X.S..1 X.t. X.S..2 X.e. X.S..3
1 a d <NA> g S S t S e S
anikakapoor
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "In this article, we are going to see how to replace character value with NA in R Programming Language."
},
{
"code": null,
"e": 204,
"s": 131,
"text": "We can replace a character value with NA in a vector and in a dataframe."
},
{
"code": null,
"e": 268,
"s": 204,
"text": "In a vector, we can replace it by using the indexing operation."
},
{
"code": null,
"e": 276,
"s": 268,
"text": "Syntax:"
},
{
"code": null,
"e": 313,
"s": 276,
"text": "vector[vector == “character”] <- NA "
},
{
"code": null,
"e": 315,
"s": 313,
"text": "R"
},
{
"code": "# create a vector with 10 charactersvector = c(\"a\", \"d\", \"A\", \"g\", \"S\", \"S\", \"t\", \"S\", \"e\", \"S\") # store actual vector in finalfinal = vector # replace character S with NAfinal[final == \"S\"] <- NA # display final vectorprint(final)",
"e": 557,
"s": 315,
"text": null
},
{
"code": null,
"e": 565,
"s": 557,
"text": "Output:"
},
{
"code": null,
"e": 609,
"s": 565,
"text": " [1] \"a\" \"d\" \"A\" \"g\" NA NA \"t\" NA \"e\" NA"
},
{
"code": null,
"e": 655,
"s": 609,
"text": "Replace character value with NA in dataframe."
},
{
"code": null,
"e": 663,
"s": 655,
"text": "Syntax:"
},
{
"code": null,
"e": 704,
"s": 663,
"text": "dataframe[dataframe== “character”] <- NA"
},
{
"code": null,
"e": 706,
"s": 704,
"text": "R"
},
{
"code": "# create a dataframe with 10 charactersdata = data.frame(\"a\", \"d\", \"A\", \"g\", \"S\", \"S\", \"t\", \"S\", \"e\", \"S\") # store actual dataframe in finalfinal = data # replace character A with NAfinal[final == \"A\"] <- NA # display final dataframeprint(final)",
"e": 969,
"s": 706,
"text": null
},
{
"code": null,
"e": 977,
"s": 969,
"text": "Output:"
},
{
"code": null,
"e": 1093,
"s": 977,
"text": " X.a. X.d. X.A. X.g. X.S. X.S..1 X.t. X.S..2 X.e. X.S..3\n1 a d <NA> g S S t S e S"
},
{
"code": null,
"e": 1105,
"s": 1093,
"text": "anikakapoor"
},
{
"code": null,
"e": 1112,
"s": 1105,
"text": "Picked"
},
{
"code": null,
"e": 1130,
"s": 1112,
"text": "R String-Programs"
},
{
"code": null,
"e": 1140,
"s": 1130,
"text": "R-strings"
},
{
"code": null,
"e": 1151,
"s": 1140,
"text": "R Language"
},
{
"code": null,
"e": 1162,
"s": 1151,
"text": "R Programs"
},
{
"code": null,
"e": 1260,
"s": 1162,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1312,
"s": 1260,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 1370,
"s": 1312,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 1405,
"s": 1370,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 1443,
"s": 1405,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 1492,
"s": 1443,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 1550,
"s": 1492,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 1599,
"s": 1550,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 1642,
"s": 1599,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 1680,
"s": 1642,
"text": "Merge DataFrames by Column Names in R"
}
] |
MongoDB query with case insensitive search? | For case, insensitive search, use regex in find() method. Following is the syntax −
db.demo572.find({"yourFieldName" : { '$regex':/^yourValue$/i}});
To understand the above syntax, let us create a collection with documents −
> db.demo572.insertOne({"CountryName":"US"});{
"acknowledged" : true, "insertedId" : ObjectId("5e915f0e581e9acd78b427f1")
}
> db.demo572.insertOne({"CountryName":"UK"});{
"acknowledged" : true, "insertedId" : ObjectId("5e915f17581e9acd78b427f2")
}
> db.demo572.insertOne({"CountryName":"Us"});{
"acknowledged" : true, "insertedId" : ObjectId("5e915f1b581e9acd78b427f3")
}
> db.demo572.insertOne({"CountryName":"AUS"});{
"acknowledged" : true, "insertedId" : ObjectId("5e915f20581e9acd78b427f4")
}
> db.demo572.insertOne({"CountryName":"us"});{
"acknowledged" : true, "insertedId" : ObjectId("5e915f25581e9acd78b427f5")
}
Display all documents from a collection with the help of find() method −
> db.demo572.find();
This will produce the following output −
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" }
{ "_id" : ObjectId("5e915f17581e9acd78b427f2"), "CountryName" : "UK" }
{ "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" }
{ "_id" : ObjectId("5e915f20581e9acd78b427f4"), "CountryName" : "AUS" }
{ "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" }
Following is the query for case insensitive search −
> db.demo572.find({"CountryName" : { '$regex':/^US$/i}});
This will produce the following output −
{ "_id" : ObjectId("5e915f0e581e9acd78b427f1"), "CountryName" : "US" }
{ "_id" : ObjectId("5e915f1b581e9acd78b427f3"), "CountryName" : "Us" }
{ "_id" : ObjectId("5e915f25581e9acd78b427f5"), "CountryName" : "us" } | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "For case, insensitive search, use regex in find() method. Following is the syntax −"
},
{
"code": null,
"e": 1211,
"s": 1146,
"text": "db.demo572.find({\"yourFieldName\" : { '$regex':/^yourValue$/i}});"
},
{
"code": null,
"e": 1287,
"s": 1211,
"text": "To understand the above syntax, let us create a collection with documents −"
},
{
"code": null,
"e": 1923,
"s": 1287,
"text": "> db.demo572.insertOne({\"CountryName\":\"US\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e915f0e581e9acd78b427f1\")\n}\n> db.demo572.insertOne({\"CountryName\":\"UK\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e915f17581e9acd78b427f2\")\n}\n> db.demo572.insertOne({\"CountryName\":\"Us\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e915f1b581e9acd78b427f3\")\n}\n> db.demo572.insertOne({\"CountryName\":\"AUS\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e915f20581e9acd78b427f4\")\n}\n> db.demo572.insertOne({\"CountryName\":\"us\"});{\n \"acknowledged\" : true, \"insertedId\" : ObjectId(\"5e915f25581e9acd78b427f5\")\n}"
},
{
"code": null,
"e": 1996,
"s": 1923,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2017,
"s": 1996,
"text": "> db.demo572.find();"
},
{
"code": null,
"e": 2058,
"s": 2017,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2414,
"s": 2058,
"text": "{ \"_id\" : ObjectId(\"5e915f0e581e9acd78b427f1\"), \"CountryName\" : \"US\" }\n{ \"_id\" : ObjectId(\"5e915f17581e9acd78b427f2\"), \"CountryName\" : \"UK\" }\n{ \"_id\" : ObjectId(\"5e915f1b581e9acd78b427f3\"), \"CountryName\" : \"Us\" }\n{ \"_id\" : ObjectId(\"5e915f20581e9acd78b427f4\"), \"CountryName\" : \"AUS\" }\n{ \"_id\" : ObjectId(\"5e915f25581e9acd78b427f5\"), \"CountryName\" : \"us\" }"
},
{
"code": null,
"e": 2467,
"s": 2414,
"text": "Following is the query for case insensitive search −"
},
{
"code": null,
"e": 2525,
"s": 2467,
"text": "> db.demo572.find({\"CountryName\" : { '$regex':/^US$/i}});"
},
{
"code": null,
"e": 2566,
"s": 2525,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2779,
"s": 2566,
"text": "{ \"_id\" : ObjectId(\"5e915f0e581e9acd78b427f1\"), \"CountryName\" : \"US\" }\n{ \"_id\" : ObjectId(\"5e915f1b581e9acd78b427f3\"), \"CountryName\" : \"Us\" }\n{ \"_id\" : ObjectId(\"5e915f25581e9acd78b427f5\"), \"CountryName\" : \"us\" }"
}
] |
Group all documents with common fields in MongoDB? | For this, use the $addToSet operator. Let us first create a collection with documents −
> db.findDocumentWithCommonFieldsDemo.insertOne(
{
"UserId":1,
"UserName":"Carol"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdf8ebebf3115999ed51200")
}
> db.findDocumentWithCommonFieldsDemo.insertOne(
{
"UserId":2,
"UserName":"David"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdf8ebebf3115999ed51201")
}
>
> db.findDocumentWithCommonFieldsDemo.insertOne(
{
"UserId":1,
"UserName":"Sam"
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdf8ebebf3115999ed51202")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findDocumentWithCommonFieldsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cdf8ebebf3115999ed51200"), "UserId" : 1, "UserName" : "Carol" }
{ "_id" : ObjectId("5cdf8ebebf3115999ed51201"), "UserId" : 2, "UserName" : "David" }
{ "_id" : ObjectId("5cdf8ebebf3115999ed51202"), "UserId" : 1, "UserName" : "Sam" }
Following is the query to find all documents with common fields in MongoDB −
> db.findDocumentWithCommonFieldsDemo.aggregate({$group : {_id : "$UserId", "UserDetails": {$addToSet : "$UserName"}}});
This will produce the following output −
{ "_id" : 2, "UserDetails" : [ "David" ] }
{ "_id" : 1, "UserDetails" : [ "Sam", "Carol" ] } | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "For this, use the $addToSet operator. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1720,
"s": 1150,
"text": "> db.findDocumentWithCommonFieldsDemo.insertOne(\n {\n \"UserId\":1,\n \"UserName\":\"Carol\"\n }\n);\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdf8ebebf3115999ed51200\")\n}\n> db.findDocumentWithCommonFieldsDemo.insertOne(\n {\n \"UserId\":2,\n \"UserName\":\"David\"\n }\n);\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdf8ebebf3115999ed51201\")\n}\n>\n> db.findDocumentWithCommonFieldsDemo.insertOne(\n {\n \"UserId\":1,\n \"UserName\":\"Sam\"\n }\n);\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdf8ebebf3115999ed51202\")\n}"
},
{
"code": null,
"e": 1819,
"s": 1720,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1865,
"s": 1819,
"text": "> db.findDocumentWithCommonFieldsDemo.find();"
},
{
"code": null,
"e": 1906,
"s": 1865,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2159,
"s": 1906,
"text": "{ \"_id\" : ObjectId(\"5cdf8ebebf3115999ed51200\"), \"UserId\" : 1, \"UserName\" : \"Carol\" }\n{ \"_id\" : ObjectId(\"5cdf8ebebf3115999ed51201\"), \"UserId\" : 2, \"UserName\" : \"David\" }\n{ \"_id\" : ObjectId(\"5cdf8ebebf3115999ed51202\"), \"UserId\" : 1, \"UserName\" : \"Sam\" }"
},
{
"code": null,
"e": 2236,
"s": 2159,
"text": "Following is the query to find all documents with common fields in MongoDB −"
},
{
"code": null,
"e": 2357,
"s": 2236,
"text": "> db.findDocumentWithCommonFieldsDemo.aggregate({$group : {_id : \"$UserId\", \"UserDetails\": {$addToSet : \"$UserName\"}}});"
},
{
"code": null,
"e": 2398,
"s": 2357,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2491,
"s": 2398,
"text": "{ \"_id\" : 2, \"UserDetails\" : [ \"David\" ] }\n{ \"_id\" : 1, \"UserDetails\" : [ \"Sam\", \"Carol\" ] }"
}
] |
How to get the top 3 salaries from a MySQL table with record of Employee Salaries? | For this, use LIMIT and OFFSET. Let us first create a table −
mysql> create table DemoTable867(EmployeeSalary int);
Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable867 values(63737);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable867 values(899833);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable867 values(23644);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable867 values(89393);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable867 values(534333);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable867 values(889322);
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable867;
This will produce the following output −
+----------------+
| EmployeeSalary |
+----------------+
| 63737 |
| 899833 |
| 23644 |
| 89393 |
| 534333 |
| 889322 |
+----------------+
6 rows in set (0.00 sec)
Here is the query to get first highest salary −
mysql> select distinct(EmployeeSalary) from DemoTable867 order by EmployeeSalary DESC LIMIT 1;
This will produce the following output −
+----------------+
| EmployeeSalary |
+----------------+
| 899833 |
+----------------+
1 row in set (0.02 sec)
Here is the query to get second highest salary −
mysql> select distinct(EmployeeSalary) from DemoTable867 order by EmployeeSalary DESC LIMIT 1 OFFSET 1;
This will produce the following output −
+----------------+
| EmployeeSalary |
+----------------+
| 889322 |
+----------------+
1 row in set (0.00 sec)
Following is the query to get third highest salary −
mysql> select distinct(EmployeeSalary) from DemoTable867 order by EmployeeSalary DESC LIMIT 1 OFFSET 2;
This will produce the following output −
+----------------+
| EmployeeSalary |
+----------------+
| 534333 |
+----------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1124,
"s": 1062,
"text": "For this, use LIMIT and OFFSET. Let us first create a table −"
},
{
"code": null,
"e": 1215,
"s": 1124,
"text": "mysql> create table DemoTable867(EmployeeSalary int);\nQuery OK, 0 rows affected (0.64 sec)"
},
{
"code": null,
"e": 1271,
"s": 1215,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1772,
"s": 1271,
"text": "mysql> insert into DemoTable867 values(63737);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable867 values(899833);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable867 values(23644);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable867 values(89393);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable867 values(534333);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable867 values(889322);\nQuery OK, 1 row affected (0.08 sec)"
},
{
"code": null,
"e": 1832,
"s": 1772,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1866,
"s": 1832,
"text": "mysql> select *from DemoTable867;"
},
{
"code": null,
"e": 1907,
"s": 1866,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2122,
"s": 1907,
"text": "+----------------+\n| EmployeeSalary |\n+----------------+\n| 63737 |\n| 899833 |\n| 23644 |\n| 89393 |\n| 534333 |\n| 889322 |\n+----------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2170,
"s": 2122,
"text": "Here is the query to get first highest salary −"
},
{
"code": null,
"e": 2265,
"s": 2170,
"text": "mysql> select distinct(EmployeeSalary) from DemoTable867 order by EmployeeSalary DESC LIMIT 1;"
},
{
"code": null,
"e": 2306,
"s": 2265,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2425,
"s": 2306,
"text": "+----------------+\n| EmployeeSalary |\n+----------------+\n| 899833 |\n+----------------+\n1 row in set (0.02 sec)"
},
{
"code": null,
"e": 2474,
"s": 2425,
"text": "Here is the query to get second highest salary −"
},
{
"code": null,
"e": 2578,
"s": 2474,
"text": "mysql> select distinct(EmployeeSalary) from DemoTable867 order by EmployeeSalary DESC LIMIT 1 OFFSET 1;"
},
{
"code": null,
"e": 2619,
"s": 2578,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2738,
"s": 2619,
"text": "+----------------+\n| EmployeeSalary |\n+----------------+\n| 889322 |\n+----------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2791,
"s": 2738,
"text": "Following is the query to get third highest salary −"
},
{
"code": null,
"e": 2895,
"s": 2791,
"text": "mysql> select distinct(EmployeeSalary) from DemoTable867 order by EmployeeSalary DESC LIMIT 1 OFFSET 2;"
},
{
"code": null,
"e": 2936,
"s": 2895,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3055,
"s": 2936,
"text": "+----------------+\n| EmployeeSalary |\n+----------------+\n| 534333 |\n+----------------+\n1 row in set (0.00 sec)"
}
] |
Integrating Python with MySQL. A data analyst or data scientist get... | by Sanjana Ramankandath | Towards Data Science | A data analyst or data scientist get lots of opportunity to work on Python and SQL. Python with its enormous library support provides data analyst with a magic wand to manipulate and visualize data. Likewise SQL helps us store millions of records and establish relationships with other tables for optimal data management. There are scenarios that require a Python program to directly load data into a back-end database. For example, if a data frame is dynamically modified periodically or at random instances, uploading the csv file for each data update into the database is not feasible. In this post, we will go through how to integrate a Python program with MySQL database.
First, I created a small dataset in Python. It has two columns, first column stores index and second column stores time stamp.
from datetime import datetime # Current date time in local system col_1 = col_1+1 col_2 = datetime.now()print('ID:',col_1)print('Timestamp:',col_2)
Creating a table in MySQL
Meanwhile we can create a table in MySQL db which will be used to store the data that we generated in the first step. It is also possible to create a table in MySQL from python itself. As this is a one time process, it will be easier to create the table in the database directly.
#Create table called details.create table `details`(Id int(20) not null,Time datetime null );
Connecting Python to MySQL
First we need to import the mysql.connector package, if it is not available then we need to install it using below code
pip install mysql.connector#or!pip install mysql.connector
We need to import the error code from mysql.connector. This will be helpful for identifying the issues, if any, while inserting into the DB.Some of the errors that one might encounter will be primary key null error and duplicate entries (if the table is set with a primary key).
We need to specify our MySQL credentials in the code. We first open a connection to the MySQL server and store the variable connection object in the variable cnct. We then create a new cursor, using the connection's cursor() method.
We will store the insert statement in the variable sql_query and the data in variable info is used to replace the %s markers in the query .
The execute statement will execute the query which is stored in the variable sql_query
Once the above code is executed, let’s check the database to see if the data is loaded dynamically.
Wonderful!! The data has been loaded.
Now lets see how the data is loaded into the database, if I ran the code 5 times.
Each time you run the code or job , the database will be dynamically loaded and refreshed.
Conclusion
Similarly we can perform any operation like creating database or tables, insert, update, delete and select operations from the Python interface itself and it will be reflected in the MySQL database.
This integration will prove useful for scenarios that involve ever changing data. For example, data that is scraped often from website or fetching live data from Twitter or Facebook feeds.
Jupyter notebook is available on Github. | [
{
"code": null,
"e": 849,
"s": 172,
"text": "A data analyst or data scientist get lots of opportunity to work on Python and SQL. Python with its enormous library support provides data analyst with a magic wand to manipulate and visualize data. Likewise SQL helps us store millions of records and establish relationships with other tables for optimal data management. There are scenarios that require a Python program to directly load data into a back-end database. For example, if a data frame is dynamically modified periodically or at random instances, uploading the csv file for each data update into the database is not feasible. In this post, we will go through how to integrate a Python program with MySQL database."
},
{
"code": null,
"e": 976,
"s": 849,
"text": "First, I created a small dataset in Python. It has two columns, first column stores index and second column stores time stamp."
},
{
"code": null,
"e": 1124,
"s": 976,
"text": "from datetime import datetime # Current date time in local system col_1 = col_1+1 col_2 = datetime.now()print('ID:',col_1)print('Timestamp:',col_2)"
},
{
"code": null,
"e": 1150,
"s": 1124,
"text": "Creating a table in MySQL"
},
{
"code": null,
"e": 1430,
"s": 1150,
"text": "Meanwhile we can create a table in MySQL db which will be used to store the data that we generated in the first step. It is also possible to create a table in MySQL from python itself. As this is a one time process, it will be easier to create the table in the database directly."
},
{
"code": null,
"e": 1525,
"s": 1430,
"text": "#Create table called details.create table `details`(Id int(20) not null,Time datetime null );"
},
{
"code": null,
"e": 1552,
"s": 1525,
"text": "Connecting Python to MySQL"
},
{
"code": null,
"e": 1672,
"s": 1552,
"text": "First we need to import the mysql.connector package, if it is not available then we need to install it using below code"
},
{
"code": null,
"e": 1731,
"s": 1672,
"text": "pip install mysql.connector#or!pip install mysql.connector"
},
{
"code": null,
"e": 2010,
"s": 1731,
"text": "We need to import the error code from mysql.connector. This will be helpful for identifying the issues, if any, while inserting into the DB.Some of the errors that one might encounter will be primary key null error and duplicate entries (if the table is set with a primary key)."
},
{
"code": null,
"e": 2243,
"s": 2010,
"text": "We need to specify our MySQL credentials in the code. We first open a connection to the MySQL server and store the variable connection object in the variable cnct. We then create a new cursor, using the connection's cursor() method."
},
{
"code": null,
"e": 2383,
"s": 2243,
"text": "We will store the insert statement in the variable sql_query and the data in variable info is used to replace the %s markers in the query ."
},
{
"code": null,
"e": 2470,
"s": 2383,
"text": "The execute statement will execute the query which is stored in the variable sql_query"
},
{
"code": null,
"e": 2570,
"s": 2470,
"text": "Once the above code is executed, let’s check the database to see if the data is loaded dynamically."
},
{
"code": null,
"e": 2608,
"s": 2570,
"text": "Wonderful!! The data has been loaded."
},
{
"code": null,
"e": 2690,
"s": 2608,
"text": "Now lets see how the data is loaded into the database, if I ran the code 5 times."
},
{
"code": null,
"e": 2781,
"s": 2690,
"text": "Each time you run the code or job , the database will be dynamically loaded and refreshed."
},
{
"code": null,
"e": 2792,
"s": 2781,
"text": "Conclusion"
},
{
"code": null,
"e": 2991,
"s": 2792,
"text": "Similarly we can perform any operation like creating database or tables, insert, update, delete and select operations from the Python interface itself and it will be reflected in the MySQL database."
},
{
"code": null,
"e": 3180,
"s": 2991,
"text": "This integration will prove useful for scenarios that involve ever changing data. For example, data that is scraped often from website or fetching live data from Twitter or Facebook feeds."
}
] |
JavaScript - Array pop() Method | Javascript array pop() method removes the last element from an array and returns that element.
Its syntax is as follows −
array.pop();
Returns the removed element from the array.
Try the following example.
<html>
<head>
<title>JavaScript Array pop Method</title>
</head>
<body>
<script type = "text/javascript">
var numbers = [1, 4, 9];
var element = numbers.pop();
document.write("element is : " + element );
var element = numbers.pop();
document.write("<br />element is : " + element );
</script>
</body>
</html>
element is : 9
element is : 4
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2562,
"s": 2466,
"text": "Javascript array pop() method removes the last element from an array and returns that element."
},
{
"code": null,
"e": 2589,
"s": 2562,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2603,
"s": 2589,
"text": "array.pop();\n"
},
{
"code": null,
"e": 2647,
"s": 2603,
"text": "Returns the removed element from the array."
},
{
"code": null,
"e": 2674,
"s": 2647,
"text": "Try the following example."
},
{
"code": null,
"e": 3092,
"s": 2674,
"text": "<html>\n <head>\n <title>JavaScript Array pop Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var numbers = [1, 4, 9];\n \n var element = numbers.pop();\n document.write(\"element is : \" + element ); \n \n var element = numbers.pop();\n document.write(\"<br />element is : \" + element );\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3125,
"s": 3092,
"text": "element is : 9\nelement is : 4 \n"
},
{
"code": null,
"e": 3160,
"s": 3125,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3174,
"s": 3160,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3208,
"s": 3174,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3222,
"s": 3208,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3257,
"s": 3222,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3274,
"s": 3257,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3309,
"s": 3274,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3326,
"s": 3309,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3359,
"s": 3326,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3387,
"s": 3359,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3421,
"s": 3387,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3449,
"s": 3421,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3456,
"s": 3449,
"text": " Print"
},
{
"code": null,
"e": 3467,
"s": 3456,
"text": " Add Notes"
}
] |
C# | Convert.ToDecimal(String, IFormatProvider) Method - GeeksforGeeks | 29 Aug, 2021
This method is used to convert the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information.
Syntax:
public static decimal ToDecimal (string value, IFormatProvider provider);
Parameters:
value: It is a string that contains a number to convert.
provider: It is an object that supplies culture-specific formatting information.
Return Value: This method returns a decimal number that is equivalent to the number in value, or 0 (zero) if value is null.Exceptions:
FormatException: If the value is not a number in a valid format.
OverflowException: If the value represents a number that is less than MinValue or greater than MaxValue.
Below programs illustrate the use of Convert.ToDecimal(String, IFormatProvider) Method:Example 1:
csharp
// C# program to demonstrate the// Convert.ToDecimal() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array string[] values = {"123456789", "12345.6789", "123,456,789.0123"}; // calling get() Method Console.WriteLine("Converted decimal value "+ "of specified strings: "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified char decimal val = Convert.ToDecimal(s, cultures); // display the converted char value Console.Write(" {0}, ", val);}}
Converted decimal value of specified strings:
123456789, 12345.6789, 123456789.0123,
Example 2: For FormatException
csharp
// C# program to demonstrate the// Convert.ToDecimal() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array string[] values = {"123456789", "12345.6789", "123,456,789.0123"}; // calling get() Method Console.WriteLine("Converted decimal value"+ " of specified strings: "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } Console.WriteLine("\n"); string s = "123 456, 789"; Console.WriteLine("format of s is invalid "); // converting string to specified char decimal val = Convert.ToDecimal(s, cultures); // display the converted char value Console.Write(" {0}, ", val); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to // specified decimal value decimal val = Convert.ToDecimal(s, cultures); // display the converted decimal value Console.Write(" {0}, ", val);}}
Converted decimal value of specified strings:
123456789, 12345.6789, 123456789.0123,
format of s is invalid
Exception Thrown: System.FormatException
Example 3: For OverflowException
csharp
// C# program to demonstrate the// Convert.ToDecimal() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array string[] values = {"123456789", "12345.6789", "123,456,789.0123"}; // calling get() Method Console.WriteLine("Converted decimal value "+ "of specified strings: "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } Console.WriteLine("\n"); string s = "-7922816251426433759354395033500000"; Console.WriteLine("s is less than the MinValue"); // converting string to specified char decimal val = Convert.ToDecimal(s, cultures); // display the converted char value Console.Write(" {0}, ", val); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to // specified decimal value decimal val = Convert.ToDecimal(s, cultures); // display the converted decimal value Console.Write(" {0}, ", val);}}
Converted decimal value of specified strings:
123456789, 12345.6789, 123456789.0123,
s is less than the MinValue
Exception Thrown: System.OverflowException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.convert.todecimal?view=netframework-4.7.2#System_Convert_ToDecimal_System_String_System_IFormatProvider_
sagartomar9927
CSharp Convert Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Delegates
C# | Abstract Classes
C# | Data Types | [
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n29 Aug, 2021"
},
{
"code": null,
"e": 24866,
"s": 24692,
"text": "This method is used to convert the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information. "
},
{
"code": null,
"e": 24875,
"s": 24866,
"text": "Syntax: "
},
{
"code": null,
"e": 24949,
"s": 24875,
"text": "public static decimal ToDecimal (string value, IFormatProvider provider);"
},
{
"code": null,
"e": 24962,
"s": 24949,
"text": "Parameters: "
},
{
"code": null,
"e": 25019,
"s": 24962,
"text": "value: It is a string that contains a number to convert."
},
{
"code": null,
"e": 25100,
"s": 25019,
"text": "provider: It is an object that supplies culture-specific formatting information."
},
{
"code": null,
"e": 25236,
"s": 25100,
"text": "Return Value: This method returns a decimal number that is equivalent to the number in value, or 0 (zero) if value is null.Exceptions: "
},
{
"code": null,
"e": 25301,
"s": 25236,
"text": "FormatException: If the value is not a number in a valid format."
},
{
"code": null,
"e": 25406,
"s": 25301,
"text": "OverflowException: If the value represents a number that is less than MinValue or greater than MaxValue."
},
{
"code": null,
"e": 25505,
"s": 25406,
"text": "Below programs illustrate the use of Convert.ToDecimal(String, IFormatProvider) Method:Example 1: "
},
{
"code": null,
"e": 25512,
"s": 25505,
"text": "csharp"
},
{
"code": "// C# program to demonstrate the// Convert.ToDecimal() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo(\"en-US\"); // declaring and initializing String array string[] values = {\"123456789\", \"12345.6789\", \"123,456,789.0123\"}; // calling get() Method Console.WriteLine(\"Converted decimal value \"+ \"of specified strings: \"); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified char decimal val = Convert.ToDecimal(s, cultures); // display the converted char value Console.Write(\" {0}, \", val);}}",
"e": 26823,
"s": 25512,
"text": null
},
{
"code": null,
"e": 26913,
"s": 26823,
"text": "Converted decimal value of specified strings: \n 123456789, 12345.6789, 123456789.0123, "
},
{
"code": null,
"e": 26947,
"s": 26915,
"text": "Example 2: For FormatException "
},
{
"code": null,
"e": 26954,
"s": 26947,
"text": "csharp"
},
{
"code": "// C# program to demonstrate the// Convert.ToDecimal() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo(\"en-US\"); // declaring and initializing String array string[] values = {\"123456789\", \"12345.6789\", \"123,456,789.0123\"}; // calling get() Method Console.WriteLine(\"Converted decimal value\"+ \" of specified strings: \"); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } Console.WriteLine(\"\\n\"); string s = \"123 456, 789\"; Console.WriteLine(\"format of s is invalid \"); // converting string to specified char decimal val = Convert.ToDecimal(s, cultures); // display the converted char value Console.Write(\" {0}, \", val); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to // specified decimal value decimal val = Convert.ToDecimal(s, cultures); // display the converted decimal value Console.Write(\" {0}, \", val);}}",
"e": 28533,
"s": 26954,
"text": null
},
{
"code": null,
"e": 28689,
"s": 28533,
"text": "Converted decimal value of specified strings: \n 123456789, 12345.6789, 123456789.0123, \n\nformat of s is invalid \nException Thrown: System.FormatException"
},
{
"code": null,
"e": 28724,
"s": 28691,
"text": "Example 3: For OverflowException"
},
{
"code": null,
"e": 28731,
"s": 28724,
"text": "csharp"
},
{
"code": "// C# program to demonstrate the// Convert.ToDecimal() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo(\"en-US\"); // declaring and initializing String array string[] values = {\"123456789\", \"12345.6789\", \"123,456,789.0123\"}; // calling get() Method Console.WriteLine(\"Converted decimal value \"+ \"of specified strings: \"); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } Console.WriteLine(\"\\n\"); string s = \"-7922816251426433759354395033500000\"; Console.WriteLine(\"s is less than the MinValue\"); // converting string to specified char decimal val = Convert.ToDecimal(s, cultures); // display the converted char value Console.Write(\" {0}, \", val); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to // specified decimal value decimal val = Convert.ToDecimal(s, cultures); // display the converted decimal value Console.Write(\" {0}, \", val);}}",
"e": 30318,
"s": 28731,
"text": null
},
{
"code": null,
"e": 30480,
"s": 30318,
"text": "Converted decimal value of specified strings: \n 123456789, 12345.6789, 123456789.0123, \n\ns is less than the MinValue\nException Thrown: System.OverflowException"
},
{
"code": null,
"e": 30494,
"s": 30482,
"text": "Reference: "
},
{
"code": null,
"e": 30650,
"s": 30494,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.convert.todecimal?view=netframework-4.7.2#System_Convert_ToDecimal_System_String_System_IFormatProvider_"
},
{
"code": null,
"e": 30665,
"s": 30650,
"text": "sagartomar9927"
},
{
"code": null,
"e": 30686,
"s": 30665,
"text": "CSharp Convert Class"
},
{
"code": null,
"e": 30700,
"s": 30686,
"text": "CSharp-method"
},
{
"code": null,
"e": 30703,
"s": 30700,
"text": "C#"
},
{
"code": null,
"e": 30801,
"s": 30703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30810,
"s": 30801,
"text": "Comments"
},
{
"code": null,
"e": 30823,
"s": 30810,
"text": "Old Comments"
},
{
"code": null,
"e": 30851,
"s": 30823,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 30874,
"s": 30851,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 30896,
"s": 30874,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 30942,
"s": 30896,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 30960,
"s": 30942,
"text": "C# | Constructors"
},
{
"code": null,
"e": 30991,
"s": 30960,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 31014,
"s": 30991,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 31029,
"s": 31014,
"text": "C# | Delegates"
},
{
"code": null,
"e": 31051,
"s": 31029,
"text": "C# | Abstract Classes"
}
] |
Count of binary strings of length N with even set bit count and at most K consecutive 1s - GeeksforGeeks | 11 Jun, 2021
Given two integers N and K, the task is to find the number of binary strings of length N having an even number of 1’s out of which less than K are consecutive.Examples:
Input: N = 4, K = 2 Output: 4 Explanation: The possible binary strings are 0000, 0101, 1001, 1010. They all have even number of 1’s with less than 2 of them occuring consecutively.Input: N = 3, K = 2 Output: 2 Explanation: The possible binary strings are 000, 101. All other strings that is 001, 010, 011, 100, 110, 111 does not meet the criteria.
Approach: This problem can be solved by Dynamic Programming.Let us consider a 3D table dp[][][] to store the solution of each subproblem, such that, dp[n][i][s] denotes the number of binary strings of length n having i consecutive 1’s and sum of 1’s = s. As it is only required to check whether the total number of 1’s is even or not we store s % 2. So, dp[n][i][s] can be calculated as follows:
If we place 0 at the nth position, the number of 1’s remain unchanged. Hence, dp[n][i][s] = dp[n – 1][0][s].If we place 1 at the nth position, dp[n][i][s] = dp[n – 1][i + 1][(s + 1) % 2] .From the above two points the recurrence relation formed is given by:
If we place 0 at the nth position, the number of 1’s remain unchanged. Hence, dp[n][i][s] = dp[n – 1][0][s].
If we place 1 at the nth position, dp[n][i][s] = dp[n – 1][i + 1][(s + 1) % 2] .
From the above two points the recurrence relation formed is given by:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Table to store solution// of each subproblemint dp[100001][20][2]; // Function to calculate// the possible binary// stringsint possibleBinaries(int pos, int ones, int sum, int k){ // If number of ones // is equal to K if (ones == k) return 0; // pos: current position // Base Case: When n // length is traversed if (pos == 0) // sum: count of 1's // Return the count // of 1's obtained return (sum == 0) ? 1 : 0; // If the subproblem has already // been solved if (dp[pos][ones][sum] != -1) // Return the answer return dp[pos][ones][sum]; // Recursive call when current // position is filled with 1 int ret = possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) // Recursive call when current // position is filled with 0 + possibleBinaries(pos - 1, 0, sum, k); // Store the solution // to this subproblem dp[pos][ones][sum] = ret; return dp[pos][ones][sum];} // Driver Codeint main(){ int N = 3; int K = 2; // Initialising the // table with -1 memset(dp, -1, sizeof dp); cout << possibleBinaries(N, 0, 0, K);}
// Java program for the above approachclass GFG{ // Table to store solution// of each subproblemstatic int [][][]dp = new int[100001][20][2]; // Function to calculate// the possible binary// Stringsstatic int possibleBinaries(int pos, int ones, int sum, int k){ // If number of ones // is equal to K if (ones == k) return 0; // pos: current position // Base Case: When n // length is traversed if (pos == 0) // sum: count of 1's // Return the count // of 1's obtained return (sum == 0) ? 1 : 0; // If the subproblem has already // been solved if (dp[pos][ones][sum] != -1) // Return the answer return dp[pos][ones][sum]; // Recursive call when current // position is filled with 1 int ret = possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) + // Recursive call when current // position is filled with 0 possibleBinaries(pos - 1, 0, sum, k); // Store the solution // to this subproblem dp[pos][ones][sum] = ret; return dp[pos][ones][sum];} // Driver Codepublic static void main(String[] args){ int N = 3; int K = 2; // Initialising the // table with -1 for(int i = 0; i < 100001; i++) { for(int j = 0; j < 20; j++) { for(int l = 0; l < 2; l++) dp[i][j][l] = -1; } } System.out.print(possibleBinaries(N, 0, 0, K));}} // This code is contributed by Rohit_ranjan
# Python3 program for the above approachimport numpy as np # Table to store solution# of each subproblemdp = np.ones(((100002, 21, 3)))dp = -1 * dp # Function to calculate# the possible binary# stringsdef possibleBinaries(pos, ones, sum, k): # If number of ones # is equal to K if (ones == k): return 0 # pos: current position # Base Case: When n # length is traversed if (pos == 0): # sum: count of 1's # Return the count # of 1's obtained return 1 if (sum == 0) else 0 # If the subproblem has already # been solved if (dp[pos][ones][sum] != -1): # Return the answer return dp[pos][ones][sum] # Recursive call when current # position is filled with 1 ret = (possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) + # Recursive call when current # position is filled with 0 possibleBinaries(pos - 1, 0, sum, k)) # Store the solution # to this subproblem dp[pos][ones][sum] = ret return dp[pos][ones][sum] # Driver CodeN = 3K = 2 print(int(possibleBinaries(N, 0, 0, K))) # This code is contributed by sanjoy_62
// C# program for the above approachusing System; class GFG{ // Table to store solution// of each subproblemstatic int [,,]dp = new int[100001, 20, 2]; // Function to calculate the// possible binary Stringsstatic int possibleBinaries(int pos, int ones, int sum, int k){ // If number of ones // is equal to K if (ones == k) return 0; // pos: current position // Base Case: When n // length is traversed if (pos == 0) // sum: count of 1's // Return the count // of 1's obtained return (sum == 0) ? 1 : 0; // If the subproblem has already // been solved if (dp[pos, ones, sum] != -1) // Return the answer return dp[pos, ones, sum]; // Recursive call when current // position is filled with 1 int ret = possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) + // Recursive call when current // position is filled with 0 possibleBinaries(pos - 1, 0, sum, k); // Store the solution // to this subproblem dp[pos, ones, sum] = ret; return dp[pos, ones, sum];} // Driver Codepublic static void Main(String[] args){ int N = 3; int K = 2; // Initialising the // table with -1 for(int i = 0; i < 100001; i++) { for(int j = 0; j < 20; j++) { for(int l = 0; l < 2; l++) dp[i, j, l] = -1; } } Console.Write(possibleBinaries(N, 0, 0, K));}} // This code is contributed by Amit Katiyar
<script>// Javascript program for the above approach // Table to store solution// of each subproblemlet dp = new Array(100001).fill(-1).map((t) => new Array(20).fill(-1).map((r) => new Array(2).fill(-1))); // Function to calculate// the possible binary// stringsfunction possibleBinaries(pos, ones, sum, k){ // If number of ones // is equal to K if (ones == k) return 0; // pos: current position // Base Case: When n // length is traversed if (pos == 0) // sum: count of 1's // Return the count // of 1's obtained return (sum == 0) ? 1 : 0; // If the subproblem has already // been solved if (dp[pos][ones][sum] != -1) // Return the answer return dp[pos][ones][sum]; // Recursive call when current // position is filled with 1 let ret = possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) // Recursive call when current // position is filled with 0 + possibleBinaries(pos - 1, 0, sum, k); // Store the solution // to this subproblem dp[pos][ones][sum] = ret; return dp[pos][ones][sum];} // Driver Codelet N = 3;let K = 2; // Initialising the// table with -1document.write(possibleBinaries(N, 0, 0, K)); // This code is contributed by _saurabh_jaiswal</script>
2
Time Complexity: O(2*N*K)
Rohit_ranjan
amit143katiyar
sanjoy_62
_saurabh_jaiswal
binary-string
setBitCount
strings
Bit Magic
Competitive Programming
Dynamic Programming
Strings
Strings
Dynamic Programming
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Hamming code Implementation in C/C++
Check whether K-th bit is set or not
Write an Efficient Method to Check if a Number is Multiple of 3
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Top 10 Algorithms and Data Structures for Competitive Programming | [
{
"code": null,
"e": 25014,
"s": 24986,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 25185,
"s": 25014,
"text": "Given two integers N and K, the task is to find the number of binary strings of length N having an even number of 1’s out of which less than K are consecutive.Examples: "
},
{
"code": null,
"e": 25533,
"s": 25185,
"text": "Input: N = 4, K = 2 Output: 4 Explanation: The possible binary strings are 0000, 0101, 1001, 1010. They all have even number of 1’s with less than 2 of them occuring consecutively.Input: N = 3, K = 2 Output: 2 Explanation: The possible binary strings are 000, 101. All other strings that is 001, 010, 011, 100, 110, 111 does not meet the criteria."
},
{
"code": null,
"e": 25931,
"s": 25533,
"text": "Approach: This problem can be solved by Dynamic Programming.Let us consider a 3D table dp[][][] to store the solution of each subproblem, such that, dp[n][i][s] denotes the number of binary strings of length n having i consecutive 1’s and sum of 1’s = s. As it is only required to check whether the total number of 1’s is even or not we store s % 2. So, dp[n][i][s] can be calculated as follows: "
},
{
"code": null,
"e": 26191,
"s": 25931,
"text": "If we place 0 at the nth position, the number of 1’s remain unchanged. Hence, dp[n][i][s] = dp[n – 1][0][s].If we place 1 at the nth position, dp[n][i][s] = dp[n – 1][i + 1][(s + 1) % 2] .From the above two points the recurrence relation formed is given by: "
},
{
"code": null,
"e": 26300,
"s": 26191,
"text": "If we place 0 at the nth position, the number of 1’s remain unchanged. Hence, dp[n][i][s] = dp[n – 1][0][s]."
},
{
"code": null,
"e": 26381,
"s": 26300,
"text": "If we place 1 at the nth position, dp[n][i][s] = dp[n – 1][i + 1][(s + 1) % 2] ."
},
{
"code": null,
"e": 26453,
"s": 26381,
"text": "From the above two points the recurrence relation formed is given by: "
},
{
"code": null,
"e": 26505,
"s": 26453,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26509,
"s": 26505,
"text": "C++"
},
{
"code": null,
"e": 26514,
"s": 26509,
"text": "Java"
},
{
"code": null,
"e": 26522,
"s": 26514,
"text": "Python3"
},
{
"code": null,
"e": 26525,
"s": 26522,
"text": "C#"
},
{
"code": null,
"e": 26536,
"s": 26525,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Table to store solution// of each subproblemint dp[100001][20][2]; // Function to calculate// the possible binary// stringsint possibleBinaries(int pos, int ones, int sum, int k){ // If number of ones // is equal to K if (ones == k) return 0; // pos: current position // Base Case: When n // length is traversed if (pos == 0) // sum: count of 1's // Return the count // of 1's obtained return (sum == 0) ? 1 : 0; // If the subproblem has already // been solved if (dp[pos][ones][sum] != -1) // Return the answer return dp[pos][ones][sum]; // Recursive call when current // position is filled with 1 int ret = possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) // Recursive call when current // position is filled with 0 + possibleBinaries(pos - 1, 0, sum, k); // Store the solution // to this subproblem dp[pos][ones][sum] = ret; return dp[pos][ones][sum];} // Driver Codeint main(){ int N = 3; int K = 2; // Initialising the // table with -1 memset(dp, -1, sizeof dp); cout << possibleBinaries(N, 0, 0, K);}",
"e": 27980,
"s": 26536,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Table to store solution// of each subproblemstatic int [][][]dp = new int[100001][20][2]; // Function to calculate// the possible binary// Stringsstatic int possibleBinaries(int pos, int ones, int sum, int k){ // If number of ones // is equal to K if (ones == k) return 0; // pos: current position // Base Case: When n // length is traversed if (pos == 0) // sum: count of 1's // Return the count // of 1's obtained return (sum == 0) ? 1 : 0; // If the subproblem has already // been solved if (dp[pos][ones][sum] != -1) // Return the answer return dp[pos][ones][sum]; // Recursive call when current // position is filled with 1 int ret = possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) + // Recursive call when current // position is filled with 0 possibleBinaries(pos - 1, 0, sum, k); // Store the solution // to this subproblem dp[pos][ones][sum] = ret; return dp[pos][ones][sum];} // Driver Codepublic static void main(String[] args){ int N = 3; int K = 2; // Initialising the // table with -1 for(int i = 0; i < 100001; i++) { for(int j = 0; j < 20; j++) { for(int l = 0; l < 2; l++) dp[i][j][l] = -1; } } System.out.print(possibleBinaries(N, 0, 0, K));}} // This code is contributed by Rohit_ranjan",
"e": 29648,
"s": 27980,
"text": null
},
{
"code": "# Python3 program for the above approachimport numpy as np # Table to store solution# of each subproblemdp = np.ones(((100002, 21, 3)))dp = -1 * dp # Function to calculate# the possible binary# stringsdef possibleBinaries(pos, ones, sum, k): # If number of ones # is equal to K if (ones == k): return 0 # pos: current position # Base Case: When n # length is traversed if (pos == 0): # sum: count of 1's # Return the count # of 1's obtained return 1 if (sum == 0) else 0 # If the subproblem has already # been solved if (dp[pos][ones][sum] != -1): # Return the answer return dp[pos][ones][sum] # Recursive call when current # position is filled with 1 ret = (possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) + # Recursive call when current # position is filled with 0 possibleBinaries(pos - 1, 0, sum, k)) # Store the solution # to this subproblem dp[pos][ones][sum] = ret return dp[pos][ones][sum] # Driver CodeN = 3K = 2 print(int(possibleBinaries(N, 0, 0, K))) # This code is contributed by sanjoy_62",
"e": 30876,
"s": 29648,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Table to store solution// of each subproblemstatic int [,,]dp = new int[100001, 20, 2]; // Function to calculate the// possible binary Stringsstatic int possibleBinaries(int pos, int ones, int sum, int k){ // If number of ones // is equal to K if (ones == k) return 0; // pos: current position // Base Case: When n // length is traversed if (pos == 0) // sum: count of 1's // Return the count // of 1's obtained return (sum == 0) ? 1 : 0; // If the subproblem has already // been solved if (dp[pos, ones, sum] != -1) // Return the answer return dp[pos, ones, sum]; // Recursive call when current // position is filled with 1 int ret = possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) + // Recursive call when current // position is filled with 0 possibleBinaries(pos - 1, 0, sum, k); // Store the solution // to this subproblem dp[pos, ones, sum] = ret; return dp[pos, ones, sum];} // Driver Codepublic static void Main(String[] args){ int N = 3; int K = 2; // Initialising the // table with -1 for(int i = 0; i < 100001; i++) { for(int j = 0; j < 20; j++) { for(int l = 0; l < 2; l++) dp[i, j, l] = -1; } } Console.Write(possibleBinaries(N, 0, 0, K));}} // This code is contributed by Amit Katiyar",
"e": 32521,
"s": 30876,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Table to store solution// of each subproblemlet dp = new Array(100001).fill(-1).map((t) => new Array(20).fill(-1).map((r) => new Array(2).fill(-1))); // Function to calculate// the possible binary// stringsfunction possibleBinaries(pos, ones, sum, k){ // If number of ones // is equal to K if (ones == k) return 0; // pos: current position // Base Case: When n // length is traversed if (pos == 0) // sum: count of 1's // Return the count // of 1's obtained return (sum == 0) ? 1 : 0; // If the subproblem has already // been solved if (dp[pos][ones][sum] != -1) // Return the answer return dp[pos][ones][sum]; // Recursive call when current // position is filled with 1 let ret = possibleBinaries(pos - 1, ones + 1, (sum + 1) % 2, k) // Recursive call when current // position is filled with 0 + possibleBinaries(pos - 1, 0, sum, k); // Store the solution // to this subproblem dp[pos][ones][sum] = ret; return dp[pos][ones][sum];} // Driver Codelet N = 3;let K = 2; // Initialising the// table with -1document.write(possibleBinaries(N, 0, 0, K)); // This code is contributed by _saurabh_jaiswal</script>",
"e": 33852,
"s": 32521,
"text": null
},
{
"code": null,
"e": 33854,
"s": 33852,
"text": "2"
},
{
"code": null,
"e": 33883,
"s": 33856,
"text": "Time Complexity: O(2*N*K) "
},
{
"code": null,
"e": 33896,
"s": 33883,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 33911,
"s": 33896,
"text": "amit143katiyar"
},
{
"code": null,
"e": 33921,
"s": 33911,
"text": "sanjoy_62"
},
{
"code": null,
"e": 33938,
"s": 33921,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 33952,
"s": 33938,
"text": "binary-string"
},
{
"code": null,
"e": 33964,
"s": 33952,
"text": "setBitCount"
},
{
"code": null,
"e": 33972,
"s": 33964,
"text": "strings"
},
{
"code": null,
"e": 33982,
"s": 33972,
"text": "Bit Magic"
},
{
"code": null,
"e": 34006,
"s": 33982,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34026,
"s": 34006,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34034,
"s": 34026,
"text": "Strings"
},
{
"code": null,
"e": 34042,
"s": 34034,
"text": "Strings"
},
{
"code": null,
"e": 34062,
"s": 34042,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34072,
"s": 34062,
"text": "Bit Magic"
},
{
"code": null,
"e": 34170,
"s": 34072,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34179,
"s": 34170,
"text": "Comments"
},
{
"code": null,
"e": 34192,
"s": 34179,
"text": "Old Comments"
},
{
"code": null,
"e": 34243,
"s": 34192,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 34266,
"s": 34243,
"text": "Program to find parity"
},
{
"code": null,
"e": 34303,
"s": 34266,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 34340,
"s": 34303,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 34404,
"s": 34340,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 34447,
"s": 34404,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 34488,
"s": 34447,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 34531,
"s": 34488,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 34558,
"s": 34531,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Passing NULL to printf in C - GeeksforGeeks | 02 Jun, 2017
Consider the following C code snippet.
char* p = NULL;
printf("%s", p);
What should be the output of the above program?The print expects a ‘\0’ terminated array of characters (or string literal) whereas it receives a null pointer. Passing NULL to printf is undefined behavior.
According to Section 7.1.4(of C99 or C11) : Use of library functions
If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined.
Some compilers may produce null while others Segmentation Fault. GCC prints (null).
// Effect of passing null pointers to ( %s ) // printf in C#include <stdio.h> int main(){ char* p = NULL; printf( "%s", p); return 0;}
Output in GCC:
(null)
Note that the above program may cause undefined behavior as per C standard.
This article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
C-Pointers
C Language
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
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
Understanding "extern" keyword in C
Storage Classes in C
Smart Pointers in C++ and How to Use Them
Switch Statement in C/C++ | [
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n02 Jun, 2017"
},
{
"code": null,
"e": 24271,
"s": 24232,
"text": "Consider the following C code snippet."
},
{
"code": null,
"e": 24305,
"s": 24271,
"text": "char* p = NULL;\nprintf(\"%s\", p);\n"
},
{
"code": null,
"e": 24510,
"s": 24305,
"text": "What should be the output of the above program?The print expects a ‘\\0’ terminated array of characters (or string literal) whereas it receives a null pointer. Passing NULL to printf is undefined behavior."
},
{
"code": null,
"e": 24579,
"s": 24510,
"text": "According to Section 7.1.4(of C99 or C11) : Use of library functions"
},
{
"code": null,
"e": 24969,
"s": 24579,
"text": "If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined."
},
{
"code": null,
"e": 25053,
"s": 24969,
"text": "Some compilers may produce null while others Segmentation Fault. GCC prints (null)."
},
{
"code": "// Effect of passing null pointers to ( %s ) // printf in C#include <stdio.h> int main(){ char* p = NULL; printf( \"%s\", p); return 0;}",
"e": 25195,
"s": 25053,
"text": null
},
{
"code": null,
"e": 25210,
"s": 25195,
"text": "Output in GCC:"
},
{
"code": null,
"e": 25217,
"s": 25210,
"text": "(null)"
},
{
"code": null,
"e": 25293,
"s": 25217,
"text": "Note that the above program may cause undefined behavior as per C standard."
},
{
"code": null,
"e": 25566,
"s": 25295,
"text": "This article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 25690,
"s": 25566,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 25701,
"s": 25690,
"text": "C-Pointers"
},
{
"code": null,
"e": 25712,
"s": 25701,
"text": "C Language"
},
{
"code": null,
"e": 25810,
"s": 25712,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25819,
"s": 25810,
"text": "Comments"
},
{
"code": null,
"e": 25832,
"s": 25819,
"text": "Old Comments"
},
{
"code": null,
"e": 25870,
"s": 25832,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25896,
"s": 25870,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 25916,
"s": 25896,
"text": "Multithreading in C"
},
{
"code": null,
"e": 25938,
"s": 25916,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 25976,
"s": 25938,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26017,
"s": 25976,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 26053,
"s": 26017,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 26074,
"s": 26053,
"text": "Storage Classes in C"
},
{
"code": null,
"e": 26116,
"s": 26074,
"text": "Smart Pointers in C++ and How to Use Them"
}
] |
Kruskal’s Minimum Spanning Tree Algorithm | There is a connected graph G(V, E) and the weight or cost for every edge is given. Kruskal’s algorithm will find the minimum spanning tree using the graph and the cost.
It is the merge-tree approach. Initially, there are different trees, this algorithm will merge them by taking those edges whose cost is minimum, and form a single tree.
In this problem, all of the edges are listed and sorted based on their cost. From the list, edges with minimum costs are taken out and added in the tree, and every there is a check whether the edge forming cycle or not, if it forms a cycle then discard the edge from the list and go for next edge.
The time complexity of this algorithm is O(E log E) or O(E log V), where E is a number of edges and V is a number of vertices.
Input:
Adjacency matrix
Output:
Edge: B--A And Cost: 1
Edge: E--B And Cost: 2
Edge: F--E And Cost: 2
Edge: C--A And Cost: 3
Edge: G--F And Cost: 3
Edge: D--A And Cost: 4
Total Cost: 15
kruskal(g: Graph, t: Tree)
Input − The given graph g, and an empty tree t
Output − The tree t with selected edges
Begin
create set for each vertices in graph g
for each set of vertex u do
add u in the vertexSet[u]
done
sort the edge list.
count := 0
while count <= V – 1 do //as tree must have V – 1 edges
ed := edgeList[count] //take an edge from edge list
if the starting vertex and ending vertex of ed are in same set then
merge vertexSet[start] and vertexSet[end]
add the ed into tree t
count := count +1
done
End
#include<iostream>
#define V 7
#define INF 999
using namespace std;
//Cost matrix of the graph
int costMat[V][V] = {
{0, 1, 3, 4, INF, 5, INF},
{1, 0, INF, 7, 2, INF, INF},
{3, INF, 0, INF, 8, INF, INF},
{4, 7, INF, 0, INF, INF, INF},
{INF, 2, 8, INF, 0, 2, 4},
{5, INF, INF, INF, 2, 0, 3},
{INF, INF, INF, INF, 4, 3, 0}
};
typedef struct {
int u, v, cost;
}edge;
void swapping(edge &e1, edge &e2) {
edge temp;
temp = e1;
e1 = e2;
e2 = temp;
}
class Tree {
int n;
edge edges[V-1]; //as a tree has vertex-1 edges
public:
Tree() {
n = 0;
}
void addEdge(edge e) {
edges[n] = e; //add edge e into the tree
n++;
}
void printEdges() { //print edge, cost and total cost
int tCost = 0;
for(int i = 0; i<n; i++) {
cout << "Edge: " << char(edges[i].u+'A') << "--" <<char(edges[i].v+'A');
cout << " And Cost: " << edges[i].cost << endl;
tCost += edges[i].cost;
}
cout << "Total Cost: " << tCost << endl;
}
};
class VSet {
int n;
int set[V]; //a set can hold maximum V vertices
public:
VSet() {
n = -1;
}
void addVertex(int vert) {
set[++n] = vert; //add vertex to the set
}
int deleteVertex() {
return set[n--];
}
friend int findVertex(VSet *vertSetArr, int vert);
friend void merge(VSet &set1, VSet &set2);
};
void merge(VSet &set1, VSet &set2) {
//merge two vertex sets together
while(set2.n >= 0)
set1.addVertex(set2.deleteVertex());
//addToSet(vSet1, delFromSet(vSet2));
}
int findVertex(VSet *vertSetArr, int vert) {
//find the vertex in different vertex sets
for(int i = 0; i<V; i++)
for(int j = 0; j<=vertSetArr[i].n; j++)
if(vert == vertSetArr[i].set[j])
return i; //node found in i-th vertex set
}
int findEdge(edge *edgeList) {
//find the edges from the cost matrix of Graph and store to edgeList
int count = -1, i, j;
for(i = 0; i<V; i++)
for(j = 0; j<i; j++)
if(costMat[i][j] != INF) {
count++;
//fill edge list for the position 'count'
edgeList[count].u = i; edgeList[count].v = j;
edgeList[count].cost = costMat[i][j];
}
return count+1;
}
void sortEdge(edge *edgeList, int n) {
//sort the edges of graph in ascending order of cost
int flag = 1, i, j;
for(i = 0; i<(n-1) && flag; i++) { //modified bubble sort is used
flag = 0;
for(j = 0; j<(n-i-1); j++)
if(edgeList[j].cost > edgeList[j+1].cost) {
swapping(edgeList[j], edgeList[j+1]);
flag = 1;
}
}
}
void kruskal(Tree &tr) {
int ecount, maxEdge = V*(V-1)/2; //max n(n-1)/2 edges can have in a graph
edge edgeList[maxEdge], ed;
int uloc, vloc;
VSet VSetArray[V];
ecount = findEdge(edgeList);
for(int i = 0; i < V; i++)
VSetArray[i].addVertex(i); //each set contains one element
sortEdge(edgeList, ecount); //ecount number of edges in the graph
int count = 0;
while(count <= V-1) {
ed = edgeList[count];
uloc = findVertex(VSetArray, ed.u);
vloc = findVertex(VSetArray, ed.v);
if(uloc != vloc) { //check whether source abd dest is in same set or not
merge(VSetArray[uloc], VSetArray[vloc]);
tr.addEdge(ed);
}
count++;
}
}
int main() {
Tree tr;
kruskal(tr);
tr.printEdges();
}
Edge: B--A And Cost: 1
Edge: E--B And Cost: 2
Edge: F--E And Cost: 2
Edge: C--A And Cost: 3
Edge: G--F And Cost: 3
Edge: D--A And Cost: 4
Total Cost: 15 | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "There is a connected graph G(V, E) and the weight or cost for every edge is given. Kruskal’s algorithm will find the minimum spanning tree using the graph and the cost."
},
{
"code": null,
"e": 1400,
"s": 1231,
"text": "It is the merge-tree approach. Initially, there are different trees, this algorithm will merge them by taking those edges whose cost is minimum, and form a single tree."
},
{
"code": null,
"e": 1698,
"s": 1400,
"text": "In this problem, all of the edges are listed and sorted based on their cost. From the list, edges with minimum costs are taken out and added in the tree, and every there is a check whether the edge forming cycle or not, if it forms a cycle then discard the edge from the list and go for next edge."
},
{
"code": null,
"e": 1825,
"s": 1698,
"text": "The time complexity of this algorithm is O(E log E) or O(E log V), where E is a number of edges and V is a number of vertices."
},
{
"code": null,
"e": 2011,
"s": 1825,
"text": "Input:\nAdjacency matrix\n\nOutput:\nEdge: B--A And Cost: 1\nEdge: E--B And Cost: 2\nEdge: F--E And Cost: 2\nEdge: C--A And Cost: 3\nEdge: G--F And Cost: 3\nEdge: D--A And Cost: 4\nTotal Cost: 15"
},
{
"code": null,
"e": 2038,
"s": 2011,
"text": "kruskal(g: Graph, t: Tree)"
},
{
"code": null,
"e": 2085,
"s": 2038,
"text": "Input − The given graph g, and an empty tree t"
},
{
"code": null,
"e": 2125,
"s": 2085,
"text": "Output − The tree t with selected edges"
},
{
"code": null,
"e": 2598,
"s": 2125,
"text": "Begin\n create set for each vertices in graph g\n for each set of vertex u do\n add u in the vertexSet[u]\n done\n\n sort the edge list.\n count := 0\n while count <= V – 1 do //as tree must have V – 1 edges\n ed := edgeList[count] //take an edge from edge list\n if the starting vertex and ending vertex of ed are in same set then\n merge vertexSet[start] and vertexSet[end]\n add the ed into tree t\n count := count +1\n done\nEnd"
},
{
"code": null,
"e": 6142,
"s": 2598,
"text": "#include<iostream>\n#define V 7\n#define INF 999\nusing namespace std;\n\n//Cost matrix of the graph\nint costMat[V][V] = {\n {0, 1, 3, 4, INF, 5, INF},\n {1, 0, INF, 7, 2, INF, INF},\n {3, INF, 0, INF, 8, INF, INF},\n {4, 7, INF, 0, INF, INF, INF},\n {INF, 2, 8, INF, 0, 2, 4},\n {5, INF, INF, INF, 2, 0, 3},\n {INF, INF, INF, INF, 4, 3, 0}\n};\n\ntypedef struct {\n int u, v, cost;\n}edge;\n\nvoid swapping(edge &e1, edge &e2) {\n edge temp;\n temp = e1;\n e1 = e2;\n e2 = temp;\n}\n\nclass Tree {\n int n;\n edge edges[V-1]; //as a tree has vertex-1 edges\n public:\n Tree() {\n n = 0;\n }\n\n void addEdge(edge e) {\n edges[n] = e; //add edge e into the tree\n n++;\n }\n\n void printEdges() { //print edge, cost and total cost\n int tCost = 0;\n\n for(int i = 0; i<n; i++) {\n cout << \"Edge: \" << char(edges[i].u+'A') << \"--\" <<char(edges[i].v+'A');\n cout << \" And Cost: \" << edges[i].cost << endl;\n tCost += edges[i].cost;\n }\n cout << \"Total Cost: \" << tCost << endl;\n }\n};\n\nclass VSet {\n int n;\n int set[V]; //a set can hold maximum V vertices\n public:\n VSet() {\n n = -1;\n }\n\n void addVertex(int vert) {\n set[++n] = vert; //add vertex to the set\n }\n\n int deleteVertex() {\n return set[n--];\n }\n\n friend int findVertex(VSet *vertSetArr, int vert);\n friend void merge(VSet &set1, VSet &set2);\n};\n\nvoid merge(VSet &set1, VSet &set2) {\n //merge two vertex sets together\n while(set2.n >= 0)\n set1.addVertex(set2.deleteVertex());\n //addToSet(vSet1, delFromSet(vSet2));\n}\n\nint findVertex(VSet *vertSetArr, int vert) {\n //find the vertex in different vertex sets\n for(int i = 0; i<V; i++)\n for(int j = 0; j<=vertSetArr[i].n; j++)\n if(vert == vertSetArr[i].set[j])\n return i; //node found in i-th vertex set\n}\n\nint findEdge(edge *edgeList) {\n //find the edges from the cost matrix of Graph and store to edgeList\n int count = -1, i, j;\n for(i = 0; i<V; i++)\n for(j = 0; j<i; j++)\n if(costMat[i][j] != INF) {\n count++;\n //fill edge list for the position 'count'\n edgeList[count].u = i; edgeList[count].v = j;\n edgeList[count].cost = costMat[i][j];\n }\n return count+1;\n}\n\nvoid sortEdge(edge *edgeList, int n) {\n //sort the edges of graph in ascending order of cost\n int flag = 1, i, j;\n\n for(i = 0; i<(n-1) && flag; i++) { //modified bubble sort is used\n flag = 0;\n for(j = 0; j<(n-i-1); j++)\n if(edgeList[j].cost > edgeList[j+1].cost) {\n swapping(edgeList[j], edgeList[j+1]);\n flag = 1;\n }\n }\n}\n\nvoid kruskal(Tree &tr) {\n int ecount, maxEdge = V*(V-1)/2; //max n(n-1)/2 edges can have in a graph\n edge edgeList[maxEdge], ed;\n int uloc, vloc;\n VSet VSetArray[V];\n ecount = findEdge(edgeList);\n\n for(int i = 0; i < V; i++)\n VSetArray[i].addVertex(i); //each set contains one element\n sortEdge(edgeList, ecount); //ecount number of edges in the graph\n int count = 0;\n\n while(count <= V-1) {\n ed = edgeList[count];\n uloc = findVertex(VSetArray, ed.u);\n vloc = findVertex(VSetArray, ed.v);\n\n if(uloc != vloc) { //check whether source abd dest is in same set or not\n merge(VSetArray[uloc], VSetArray[vloc]);\n tr.addEdge(ed);\n }\n count++;\n }\n}\n\nint main() {\n Tree tr;\n kruskal(tr);\n tr.printEdges();\n}"
},
{
"code": null,
"e": 6295,
"s": 6142,
"text": "Edge: B--A And Cost: 1\nEdge: E--B And Cost: 2\nEdge: F--E And Cost: 2\nEdge: C--A And Cost: 3\nEdge: G--F And Cost: 3\nEdge: D--A And Cost: 4\nTotal Cost: 15"
}
] |
Airbnb in Seattle — Data Analysis | by Jingles (Hong Jing) | Towards Data Science | For all prospective Airbnb hosts in Seattle, I will answer these questions in this article:
when to rent to maximise revenue?
when is the off-peak season for maintenance?
common group size of Seattle travellers, is it 2 or family or 4 or larger?
bedroom configurations to maximise booking rates?
how to achieve a good rating?
do hosts with higher rating have higher revenue?
amenities to include?
In this article, I will perform exploratory data analysis on the Airbnb dataset gotten from Inside Airbnb.
Our data will be loaded in pandas, comma-separated values (CSV) files can be easily loaded into DataFrame with the read_csv function.
Let us look at what the first 10 rows looks like with pd_listings.head(10):
And examine the summary of the numerical data with pd_listings.describe():
Observations:
there are 3813 listings in this dataset
values in the price column contain the dollar symbol ($)
there are missing values in columns bathrooms, bedrooms, and beds
there are missing values in reviews rating columns (review_scores_rating, review_scores_accuracy, review_scores_cleanliness, review_scores_checkin, review_scores_communication, review_scores_location, review_scores_value)
The column price, which is the price of the listing, it contains the dollar sign ($). We still can’t use it for analysis as it is not a numerical value, so we remove the dollar symbol and convert the values as numeric values:
pd_listings['price'] = pd_listings['price'].str.replace("[$, ]", "").astype("float")
Then replace those empty values with zero:
pd_listings.at[pd_listings['bathrooms'].isnull(), 'bathrooms'] = 0pd_listings.at[pd_listings['bedrooms'].isnull(), 'bedrooms'] = 0pd_listings.at[pd_listings['beds'].isnull(), 'beds'] = 0pd_listings.at[pd_listings['review_scores_rating'].isnull(), 'review_scores_rating'] = 0pd_listings.at[pd_listings['review_scores_accuracy'].isnull(), 'review_scores_accuracy'] = 0pd_listings.at[pd_listings['review_scores_cleanliness'].isnull(), 'review_scores_cleanliness'] = 0pd_listings.at[pd_listings['review_scores_checkin'].isnull(), 'review_scores_checkin'] = 0pd_listings.at[pd_listings['review_scores_communication'].isnull(), 'review_scores_communication'] = 0pd_listings.at[pd_listings['review_scores_location'].isnull(), 'review_scores_location'] = 0pd_listings.at[pd_listings['review_scores_value'].isnull(), 'review_scores_value'] = 0
Lastly, to rename id to listing_id:
pd_listings.rename(columns={'id':'listing_id'}, inplace=True)
Let us load another CSV file which contains the reviews for each listing. The DataFrame contains the following columns:
id — identification number for review
listing_id — identification number for listing which we can join with the above DataFrame
date — date of the review
I suppose that each review is a successful booking and guests stayed some number of nights. Unfortunately, we do not know the exact number of nights each guest stayed, but we could use the listing’s minimum_nights, to assume each guest stayed at least that minimum number of nights. For each review, price * minimum_nights to get each booking’s revenue:
pd_bookings = pd.merge(pd_reviews, pd_listings, on='listing_id')pd_bookings['estimated_revenue'] = pd_bookings['price'] * pd_bookings['minimum_nights']
Sum up the revenue of every booking for each listing as estimated revenue per listing:
pd_listings_revenue = pd_bookings[['listing_id','estimated_revenue']].groupby(['listing_id']).sum()
And merged the estimated revenue into the existing DataFrame (listing):
pd_listings = pd.merge(pd_listings, pd_listings_revenue, on='listing_id', how='left')pd_listings.at[pd_listings['estimated_revenue'].isnull(), 'estimated_revenue'] = 0
And we have our DataFrame ready for some analysis. Each row represents one listing, its attributes, and its estimated revenue:
This table shows the average revenue of listings in each neighbourhood:
Airbnb properties in Downtown, Capitol Hill and Beacon Hill can fetch the highest revenue. It’s shopping and CBD district.
Downtown, Capitol Hill and Beacon Hill can fetch the highest revenue
It would be useful to know the most popular time of the year to rent in Seattle, so Airbnb hosts are able to decide when to rent and when is the time for maintenance.
July, August and September are the best periods to maximise revenue. Months before May are the best time for maintenance work. From October to December is a good time to take a break and enjoy the holidays if they want to.
July, August and September are the best periods to maximise revenue.
These are the top 5 listings with the highest estimated revenue:
Wow! Looks like our top earners are hosts have minimum nights of 1000. But it might be data anomaly because 1000 nights are kind of extreme, so let’s look at the proportion of listings with different minimum_nights. (Thanks, Nono Umasy for highlighting this!)
Most hosts have minimum nights of up to a month, the host with 1000 nights, gotta filter it away.
These are the top hosts (up to 7 minimum nights) with the highest estimated revenue.
These are the top hosts (up to 4 minimum nights) with the highest estimated revenue.
From these 2 tables, longer minimum nights results in higher revenue. Let's look at the correlation between minimum nights and estimated revenue.
And the correlation between minimum nights and estimated revenue after removing the listing with 1000 minimum nights.
Host with 1000 minimum nights has caused a bais towards higher minimum nights resulted in higher revenue, with a correlation of 87% between minimum nights and revenue. But after removing that host, minimum nights and estimated revenue are not highly correlated, a correlation of 20% between minimum nights and revenue.
Minimum nights and estimated revenue are not highly correlated
As an Airbnb host, it will be good to know if my property is oversaturated in the market. Find out the ratio between the number of listings (supply) to the number of bookings (demand) of different bedroom configurations:
Listings with less than 2 bedrooms are well sought after.
But wait! Properties with no bedrooms, what are kind of properties are these?
And the number of beds in these properties?
All of these properties which no bedrooms are renting the entire apartment, and they do provide at least one bed. Phew~
As an Airbnb host, I would also like to know the common group size of Seattle visitors. So as to find out if my property configuration is oversaturated in the market.
A place which accommodates 14 ranked first (highest supply/demand ratio), but the number of bookings is low (only 83 bookings) as compared to places for 2 or 3 people.
Renting a place for 2 or 3 people will give the host pretty good regular rentals.
So let us focus on renting properties for 2 to 3 people since more than half travel in a group of this size. Do these guests prefer 1 bedroom or 2 separate bedrooms?
Airbnb bedroom configurations for 2 people:
Airbnb bedroom configurations for 3people:
The majority prefers 1 bedroom.
The majority prefers 1 bedroom, less than 1% prefers 2 bedrooms. So for groups of 2s or 3s, they prefer 1 bedroom. But this could be due to the current supply of 2 bedroom properties are low.
Having good ratings is important for Airbnb hosts. Let us compare how different factors affect overall ratings:
Good communication affects the overall rating and check-in rating
Communication has the highest correlation with the overall rating. Host in Seattle (maybe elsewhere too) needs to be responsive and friendly because good communication tends to get a high overall rating. Good communication also directly impacts the check-in rating.
Does having a good overall rating means the listing will bring in good wealth?
Having a good overall rating has a very small positive correlation with estimated revenue. And having a good rating has almost no impact on the price set by the host.
But still, having a good overall rating is highly recommended.
These are the number of Airbnbs in Seattle that provides these amenities:
Internet, heating and kitchen are necessities in Seattle.
Smoke detector? I just learnt that the Washington State Building Code has required smoke detectors in all dwellings since 1973.
So, here is the summary of this article:
Check out the codes used in this article!
towardsdatascience.com
Hi!, I’m Jingles. I enjoy building machine learning projects/products, and I write about them on Towards Data Science. Follow me on Medium or connect with me on LinkedIn. | [
{
"code": null,
"e": 264,
"s": 172,
"text": "For all prospective Airbnb hosts in Seattle, I will answer these questions in this article:"
},
{
"code": null,
"e": 298,
"s": 264,
"text": "when to rent to maximise revenue?"
},
{
"code": null,
"e": 343,
"s": 298,
"text": "when is the off-peak season for maintenance?"
},
{
"code": null,
"e": 418,
"s": 343,
"text": "common group size of Seattle travellers, is it 2 or family or 4 or larger?"
},
{
"code": null,
"e": 468,
"s": 418,
"text": "bedroom configurations to maximise booking rates?"
},
{
"code": null,
"e": 498,
"s": 468,
"text": "how to achieve a good rating?"
},
{
"code": null,
"e": 547,
"s": 498,
"text": "do hosts with higher rating have higher revenue?"
},
{
"code": null,
"e": 569,
"s": 547,
"text": "amenities to include?"
},
{
"code": null,
"e": 676,
"s": 569,
"text": "In this article, I will perform exploratory data analysis on the Airbnb dataset gotten from Inside Airbnb."
},
{
"code": null,
"e": 810,
"s": 676,
"text": "Our data will be loaded in pandas, comma-separated values (CSV) files can be easily loaded into DataFrame with the read_csv function."
},
{
"code": null,
"e": 886,
"s": 810,
"text": "Let us look at what the first 10 rows looks like with pd_listings.head(10):"
},
{
"code": null,
"e": 961,
"s": 886,
"text": "And examine the summary of the numerical data with pd_listings.describe():"
},
{
"code": null,
"e": 975,
"s": 961,
"text": "Observations:"
},
{
"code": null,
"e": 1015,
"s": 975,
"text": "there are 3813 listings in this dataset"
},
{
"code": null,
"e": 1072,
"s": 1015,
"text": "values in the price column contain the dollar symbol ($)"
},
{
"code": null,
"e": 1138,
"s": 1072,
"text": "there are missing values in columns bathrooms, bedrooms, and beds"
},
{
"code": null,
"e": 1360,
"s": 1138,
"text": "there are missing values in reviews rating columns (review_scores_rating, review_scores_accuracy, review_scores_cleanliness, review_scores_checkin, review_scores_communication, review_scores_location, review_scores_value)"
},
{
"code": null,
"e": 1586,
"s": 1360,
"text": "The column price, which is the price of the listing, it contains the dollar sign ($). We still can’t use it for analysis as it is not a numerical value, so we remove the dollar symbol and convert the values as numeric values:"
},
{
"code": null,
"e": 1671,
"s": 1586,
"text": "pd_listings['price'] = pd_listings['price'].str.replace(\"[$, ]\", \"\").astype(\"float\")"
},
{
"code": null,
"e": 1714,
"s": 1671,
"text": "Then replace those empty values with zero:"
},
{
"code": null,
"e": 2549,
"s": 1714,
"text": "pd_listings.at[pd_listings['bathrooms'].isnull(), 'bathrooms'] = 0pd_listings.at[pd_listings['bedrooms'].isnull(), 'bedrooms'] = 0pd_listings.at[pd_listings['beds'].isnull(), 'beds'] = 0pd_listings.at[pd_listings['review_scores_rating'].isnull(), 'review_scores_rating'] = 0pd_listings.at[pd_listings['review_scores_accuracy'].isnull(), 'review_scores_accuracy'] = 0pd_listings.at[pd_listings['review_scores_cleanliness'].isnull(), 'review_scores_cleanliness'] = 0pd_listings.at[pd_listings['review_scores_checkin'].isnull(), 'review_scores_checkin'] = 0pd_listings.at[pd_listings['review_scores_communication'].isnull(), 'review_scores_communication'] = 0pd_listings.at[pd_listings['review_scores_location'].isnull(), 'review_scores_location'] = 0pd_listings.at[pd_listings['review_scores_value'].isnull(), 'review_scores_value'] = 0"
},
{
"code": null,
"e": 2585,
"s": 2549,
"text": "Lastly, to rename id to listing_id:"
},
{
"code": null,
"e": 2647,
"s": 2585,
"text": "pd_listings.rename(columns={'id':'listing_id'}, inplace=True)"
},
{
"code": null,
"e": 2767,
"s": 2647,
"text": "Let us load another CSV file which contains the reviews for each listing. The DataFrame contains the following columns:"
},
{
"code": null,
"e": 2805,
"s": 2767,
"text": "id — identification number for review"
},
{
"code": null,
"e": 2895,
"s": 2805,
"text": "listing_id — identification number for listing which we can join with the above DataFrame"
},
{
"code": null,
"e": 2921,
"s": 2895,
"text": "date — date of the review"
},
{
"code": null,
"e": 3275,
"s": 2921,
"text": "I suppose that each review is a successful booking and guests stayed some number of nights. Unfortunately, we do not know the exact number of nights each guest stayed, but we could use the listing’s minimum_nights, to assume each guest stayed at least that minimum number of nights. For each review, price * minimum_nights to get each booking’s revenue:"
},
{
"code": null,
"e": 3427,
"s": 3275,
"text": "pd_bookings = pd.merge(pd_reviews, pd_listings, on='listing_id')pd_bookings['estimated_revenue'] = pd_bookings['price'] * pd_bookings['minimum_nights']"
},
{
"code": null,
"e": 3514,
"s": 3427,
"text": "Sum up the revenue of every booking for each listing as estimated revenue per listing:"
},
{
"code": null,
"e": 3614,
"s": 3514,
"text": "pd_listings_revenue = pd_bookings[['listing_id','estimated_revenue']].groupby(['listing_id']).sum()"
},
{
"code": null,
"e": 3686,
"s": 3614,
"text": "And merged the estimated revenue into the existing DataFrame (listing):"
},
{
"code": null,
"e": 3854,
"s": 3686,
"text": "pd_listings = pd.merge(pd_listings, pd_listings_revenue, on='listing_id', how='left')pd_listings.at[pd_listings['estimated_revenue'].isnull(), 'estimated_revenue'] = 0"
},
{
"code": null,
"e": 3981,
"s": 3854,
"text": "And we have our DataFrame ready for some analysis. Each row represents one listing, its attributes, and its estimated revenue:"
},
{
"code": null,
"e": 4053,
"s": 3981,
"text": "This table shows the average revenue of listings in each neighbourhood:"
},
{
"code": null,
"e": 4176,
"s": 4053,
"text": "Airbnb properties in Downtown, Capitol Hill and Beacon Hill can fetch the highest revenue. It’s shopping and CBD district."
},
{
"code": null,
"e": 4245,
"s": 4176,
"text": "Downtown, Capitol Hill and Beacon Hill can fetch the highest revenue"
},
{
"code": null,
"e": 4412,
"s": 4245,
"text": "It would be useful to know the most popular time of the year to rent in Seattle, so Airbnb hosts are able to decide when to rent and when is the time for maintenance."
},
{
"code": null,
"e": 4635,
"s": 4412,
"text": "July, August and September are the best periods to maximise revenue. Months before May are the best time for maintenance work. From October to December is a good time to take a break and enjoy the holidays if they want to."
},
{
"code": null,
"e": 4704,
"s": 4635,
"text": "July, August and September are the best periods to maximise revenue."
},
{
"code": null,
"e": 4769,
"s": 4704,
"text": "These are the top 5 listings with the highest estimated revenue:"
},
{
"code": null,
"e": 5029,
"s": 4769,
"text": "Wow! Looks like our top earners are hosts have minimum nights of 1000. But it might be data anomaly because 1000 nights are kind of extreme, so let’s look at the proportion of listings with different minimum_nights. (Thanks, Nono Umasy for highlighting this!)"
},
{
"code": null,
"e": 5127,
"s": 5029,
"text": "Most hosts have minimum nights of up to a month, the host with 1000 nights, gotta filter it away."
},
{
"code": null,
"e": 5212,
"s": 5127,
"text": "These are the top hosts (up to 7 minimum nights) with the highest estimated revenue."
},
{
"code": null,
"e": 5297,
"s": 5212,
"text": "These are the top hosts (up to 4 minimum nights) with the highest estimated revenue."
},
{
"code": null,
"e": 5443,
"s": 5297,
"text": "From these 2 tables, longer minimum nights results in higher revenue. Let's look at the correlation between minimum nights and estimated revenue."
},
{
"code": null,
"e": 5561,
"s": 5443,
"text": "And the correlation between minimum nights and estimated revenue after removing the listing with 1000 minimum nights."
},
{
"code": null,
"e": 5880,
"s": 5561,
"text": "Host with 1000 minimum nights has caused a bais towards higher minimum nights resulted in higher revenue, with a correlation of 87% between minimum nights and revenue. But after removing that host, minimum nights and estimated revenue are not highly correlated, a correlation of 20% between minimum nights and revenue."
},
{
"code": null,
"e": 5943,
"s": 5880,
"text": "Minimum nights and estimated revenue are not highly correlated"
},
{
"code": null,
"e": 6164,
"s": 5943,
"text": "As an Airbnb host, it will be good to know if my property is oversaturated in the market. Find out the ratio between the number of listings (supply) to the number of bookings (demand) of different bedroom configurations:"
},
{
"code": null,
"e": 6222,
"s": 6164,
"text": "Listings with less than 2 bedrooms are well sought after."
},
{
"code": null,
"e": 6300,
"s": 6222,
"text": "But wait! Properties with no bedrooms, what are kind of properties are these?"
},
{
"code": null,
"e": 6344,
"s": 6300,
"text": "And the number of beds in these properties?"
},
{
"code": null,
"e": 6464,
"s": 6344,
"text": "All of these properties which no bedrooms are renting the entire apartment, and they do provide at least one bed. Phew~"
},
{
"code": null,
"e": 6631,
"s": 6464,
"text": "As an Airbnb host, I would also like to know the common group size of Seattle visitors. So as to find out if my property configuration is oversaturated in the market."
},
{
"code": null,
"e": 6799,
"s": 6631,
"text": "A place which accommodates 14 ranked first (highest supply/demand ratio), but the number of bookings is low (only 83 bookings) as compared to places for 2 or 3 people."
},
{
"code": null,
"e": 6881,
"s": 6799,
"text": "Renting a place for 2 or 3 people will give the host pretty good regular rentals."
},
{
"code": null,
"e": 7047,
"s": 6881,
"text": "So let us focus on renting properties for 2 to 3 people since more than half travel in a group of this size. Do these guests prefer 1 bedroom or 2 separate bedrooms?"
},
{
"code": null,
"e": 7091,
"s": 7047,
"text": "Airbnb bedroom configurations for 2 people:"
},
{
"code": null,
"e": 7134,
"s": 7091,
"text": "Airbnb bedroom configurations for 3people:"
},
{
"code": null,
"e": 7166,
"s": 7134,
"text": "The majority prefers 1 bedroom."
},
{
"code": null,
"e": 7358,
"s": 7166,
"text": "The majority prefers 1 bedroom, less than 1% prefers 2 bedrooms. So for groups of 2s or 3s, they prefer 1 bedroom. But this could be due to the current supply of 2 bedroom properties are low."
},
{
"code": null,
"e": 7470,
"s": 7358,
"text": "Having good ratings is important for Airbnb hosts. Let us compare how different factors affect overall ratings:"
},
{
"code": null,
"e": 7536,
"s": 7470,
"text": "Good communication affects the overall rating and check-in rating"
},
{
"code": null,
"e": 7802,
"s": 7536,
"text": "Communication has the highest correlation with the overall rating. Host in Seattle (maybe elsewhere too) needs to be responsive and friendly because good communication tends to get a high overall rating. Good communication also directly impacts the check-in rating."
},
{
"code": null,
"e": 7881,
"s": 7802,
"text": "Does having a good overall rating means the listing will bring in good wealth?"
},
{
"code": null,
"e": 8048,
"s": 7881,
"text": "Having a good overall rating has a very small positive correlation with estimated revenue. And having a good rating has almost no impact on the price set by the host."
},
{
"code": null,
"e": 8111,
"s": 8048,
"text": "But still, having a good overall rating is highly recommended."
},
{
"code": null,
"e": 8185,
"s": 8111,
"text": "These are the number of Airbnbs in Seattle that provides these amenities:"
},
{
"code": null,
"e": 8243,
"s": 8185,
"text": "Internet, heating and kitchen are necessities in Seattle."
},
{
"code": null,
"e": 8371,
"s": 8243,
"text": "Smoke detector? I just learnt that the Washington State Building Code has required smoke detectors in all dwellings since 1973."
},
{
"code": null,
"e": 8412,
"s": 8371,
"text": "So, here is the summary of this article:"
},
{
"code": null,
"e": 8454,
"s": 8412,
"text": "Check out the codes used in this article!"
},
{
"code": null,
"e": 8477,
"s": 8454,
"text": "towardsdatascience.com"
}
] |
Node Jimp | resize - GeeksforGeeks | 19 Feb, 2021
Introduction The resize() function is an inbuilt function in Nodejs | Jimp which resizes the image to a set width and height using a 2-pass bilinear algorithm. Syntax:
resize(w, h, mode, cb)
Parameter:
w – This parameter stores the width of the image.
h – This parameter stores the height of the image.
mode – This is optional parameter which stores the scaling method.
cb – This is optional parameter which is invoked when compilation is complete.
Input Images:
npm init -y
npm install jimp --save
Example 1:
javascript
// npm install --save jimp// import jimp library to the environmentvar Jimp = require('jimp'); // User-Defined Function to read the imagesasync function main() { const image = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png');// rotate Function having rotation as 55 image.resize(323, 421) .write('resize1.png');} main(); console.log("Image Processing Completed");
Output:
Example 2: With cb (optional parameters)
javascript
//npm install --save jimp//import jimp library to the environmentvar Jimp = require('jimp'); //User-Defined Function to read the imagesasync function main() { const image = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185333/gfg111.png');//rotate Function having rotation angle as 99, mode and callback function image.resize(1024, 768, Jimp.RESIZE_BEZIER, function(err){ if (err) throw err; }) .write('resize2.png');} main(); console.log("Image Processing Completed");
Output:
Reference: https://www.npmjs.com/package/jimp
mridulmanochagfg
Image-Processing
Node-Jimp
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Express.js express.Router() Function
How to read and write Excel file in Node.js ?
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24426,
"s": 24398,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 24596,
"s": 24426,
"text": "Introduction The resize() function is an inbuilt function in Nodejs | Jimp which resizes the image to a set width and height using a 2-pass bilinear algorithm. Syntax: "
},
{
"code": null,
"e": 24619,
"s": 24596,
"text": "resize(w, h, mode, cb)"
},
{
"code": null,
"e": 24632,
"s": 24619,
"text": "Parameter: "
},
{
"code": null,
"e": 24682,
"s": 24632,
"text": "w – This parameter stores the width of the image."
},
{
"code": null,
"e": 24733,
"s": 24682,
"text": "h – This parameter stores the height of the image."
},
{
"code": null,
"e": 24800,
"s": 24733,
"text": "mode – This is optional parameter which stores the scaling method."
},
{
"code": null,
"e": 24879,
"s": 24800,
"text": "cb – This is optional parameter which is invoked when compilation is complete."
},
{
"code": null,
"e": 24895,
"s": 24879,
"text": "Input Images: "
},
{
"code": null,
"e": 24909,
"s": 24897,
"text": "npm init -y"
},
{
"code": null,
"e": 24933,
"s": 24909,
"text": "npm install jimp --save"
},
{
"code": null,
"e": 24946,
"s": 24933,
"text": "Example 1: "
},
{
"code": null,
"e": 24957,
"s": 24946,
"text": "javascript"
},
{
"code": "// npm install --save jimp// import jimp library to the environmentvar Jimp = require('jimp'); // User-Defined Function to read the imagesasync function main() { const image = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png');// rotate Function having rotation as 55 image.resize(323, 421) .write('resize1.png');} main(); console.log(\"Image Processing Completed\");",
"e": 25379,
"s": 24957,
"text": null
},
{
"code": null,
"e": 25389,
"s": 25379,
"text": "Output: "
},
{
"code": null,
"e": 25432,
"s": 25389,
"text": "Example 2: With cb (optional parameters) "
},
{
"code": null,
"e": 25443,
"s": 25432,
"text": "javascript"
},
{
"code": "//npm install --save jimp//import jimp library to the environmentvar Jimp = require('jimp'); //User-Defined Function to read the imagesasync function main() { const image = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185333/gfg111.png');//rotate Function having rotation angle as 99, mode and callback function image.resize(1024, 768, Jimp.RESIZE_BEZIER, function(err){ if (err) throw err; }) .write('resize2.png');} main(); console.log(\"Image Processing Completed\");",
"e": 25959,
"s": 25443,
"text": null
},
{
"code": null,
"e": 25969,
"s": 25959,
"text": "Output: "
},
{
"code": null,
"e": 26016,
"s": 25969,
"text": "Reference: https://www.npmjs.com/package/jimp "
},
{
"code": null,
"e": 26033,
"s": 26016,
"text": "mridulmanochagfg"
},
{
"code": null,
"e": 26050,
"s": 26033,
"text": "Image-Processing"
},
{
"code": null,
"e": 26060,
"s": 26050,
"text": "Node-Jimp"
},
{
"code": null,
"e": 26068,
"s": 26060,
"text": "Node.js"
},
{
"code": null,
"e": 26085,
"s": 26068,
"text": "Web Technologies"
},
{
"code": null,
"e": 26183,
"s": 26085,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26192,
"s": 26183,
"text": "Comments"
},
{
"code": null,
"e": 26205,
"s": 26192,
"text": "Old Comments"
},
{
"code": null,
"e": 26235,
"s": 26205,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 26292,
"s": 26235,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 26346,
"s": 26292,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 26383,
"s": 26346,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26429,
"s": 26383,
"text": "How to read and write Excel file in Node.js ?"
},
{
"code": null,
"e": 26471,
"s": 26429,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26514,
"s": 26471,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26576,
"s": 26514,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26626,
"s": 26576,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python Pandas - Create a DataFrame with the levels of the MultiIndex as columns | To create a DataFrame with the levels of the MultiIndex as columns, use the to_frame() method in Pandas.
At first, import the required libraries −
import pandas as pd
MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
The "names" parameter sets the names for each of the index levels. The from_arrays() is used to create a MultiIndex −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
Create a DataFrame with the levels of the MultiIndex as columns using to_frame() −
dataFrame = multiIndex.to_frame()
Following is the code −
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
# display the MultiIndex
print("The Multi-index...\n",multiIndex)
# get the levels in MultiIndex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
# Create a DataFrame with the levels of the MultiIndex as columns using to_frame()
dataFrame = multiIndex.to_frame()
# Display the DataFrame
print("\nThe DataFrame...\n",dataFrame)
This will produce the following output −
The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris')],
names=['ranks', 'student'])
The levels in Multi-index...
[[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']]
The DataFrame...
ranks student
ranks student
1 John 1 John
2 Tim 2 Tim
3 Jacob 3 Jacob
4 Chris 4 Chris | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "To create a DataFrame with the levels of the MultiIndex as columns, use the to_frame() method in Pandas."
},
{
"code": null,
"e": 1209,
"s": 1167,
"text": "At first, import the required libraries −"
},
{
"code": null,
"e": 1229,
"s": 1209,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1324,
"s": 1229,
"text": "MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −"
},
{
"code": null,
"e": 1384,
"s": 1324,
"text": "arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]\n"
},
{
"code": null,
"e": 1502,
"s": 1384,
"text": "The \"names\" parameter sets the names for each of the index levels. The from_arrays() is used to create a MultiIndex −"
},
{
"code": null,
"e": 1577,
"s": 1502,
"text": "multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))"
},
{
"code": null,
"e": 1660,
"s": 1577,
"text": "Create a DataFrame with the levels of the MultiIndex as columns using to_frame() −"
},
{
"code": null,
"e": 1695,
"s": 1660,
"text": "dataFrame = multiIndex.to_frame()\n"
},
{
"code": null,
"e": 1719,
"s": 1695,
"text": "Following is the code −"
},
{
"code": null,
"e": 2432,
"s": 1719,
"text": "import pandas as pd\n\n# MultiIndex is a multi-level, or hierarchical, index object for pandas objects\n# Create arrays\narrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]\n\n# The \"names\" parameter sets the names for each of the index levels\n# The from_arrays() is used to create a MultiIndex\nmultiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))\n\n# display the MultiIndex\nprint(\"The Multi-index...\\n\",multiIndex)\n\n# get the levels in MultiIndex\nprint(\"\\nThe levels in Multi-index...\\n\",multiIndex.levels)\n\n# Create a DataFrame with the levels of the MultiIndex as columns using to_frame()\ndataFrame = multiIndex.to_frame()\n\n# Display the DataFrame\nprint(\"\\nThe DataFrame...\\n\",dataFrame)"
},
{
"code": null,
"e": 2473,
"s": 2432,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2897,
"s": 2473,
"text": "The Multi-index...\nMultiIndex([(1, 'John'),\n (2, 'Tim'),\n (3, 'Jacob'),\n (4, 'Chris')],\n names=['ranks', 'student'])\n\nThe levels in Multi-index...\n [[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']]\n\nThe DataFrame...\n ranks student\nranks student\n1 John 1 John\n2 Tim 2 Tim\n3 Jacob 3 Jacob\n4 Chris 4 Chris"
}
] |
Count prime numbers that can be expressed as sum of consecutive prime numbers - GeeksforGeeks | 26 Apr, 2021
Given an integer N, the task is to find the number of prime numbers up to N that can be expressed as a sum of consecutive primes.
Examples:
Input: N = 45Output: 3Explanation:Below are the prime numbers up to 45 that can be expressed as sum of consecutive prime numbers:
5 = 2 + 3
17 = 2 + 3 + 5 + 7
41 = 2 + 3 + 5 + 7 + 11 + 13
Therefore, the count is 3.
Input: N = 4Output: 0
Approach: The idea is to use the Primality Test Algorithm. Using this, all primes not exceeding N can be found. After that, each number that can be expressed as consecutive primes can be found. Follow the steps below to solve the problem:
Traverse through each number from 1 to N, checking if it is a prime, and stored it in a vector.Sort all the stored prime numbers in the vector.Let there be X primes present in the vector. Initialize sum as the smallest prime found i.e., element at index 0 in the vector.Iterate over the range [1, X – 1] and add each element to the sum.After adding, check if the sum is a prime or not and the sum is less than N or not. If it found to be true, then increment the counter. Otherwise, if the sum becomes greater than N, break the loop.After all the above steps, print the count of prime numbers stored on the counter.
Traverse through each number from 1 to N, checking if it is a prime, and stored it in a vector.
Sort all the stored prime numbers in the vector.
Let there be X primes present in the vector. Initialize sum as the smallest prime found i.e., element at index 0 in the vector.
Iterate over the range [1, X – 1] and add each element to the sum.
After adding, check if the sum is a prime or not and the sum is less than N or not. If it found to be true, then increment the counter. Otherwise, if the sum becomes greater than N, break the loop.
After all the above steps, print the count of prime numbers stored on the counter.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if a// number is prime or notint isprm(int n){ // Base Case if (n <= 1) return 0; if (n <= 3) return 1; if (n % 2 == 0 || n % 3 == 0) return 0; // Iterate till [5, sqrt(N)] to // detect primality of numbers for (int i = 5; i * i <= n; i = i + 6) { // If N is divisible by i // or i + 2 if (n % i == 0 || n % (i + 2) == 0) return 0; } // Return 1 if N is prime return 1;} // Function to count the prime numbers// which can be expressed as sum of// consecutive prime numbersint countprime(int n){ // Initialize count as 0 int count = 0; // Stores prime numbers vector<int> primevector; for (int i = 2; i <= n; i++) { // If i is prime if (isprm(i) == 1) { primevector.push_back(i); } } // Initialize the sum int sum = primevector[0]; // Find all required primes upto N for (int i = 1; i < primevector.size(); i++) { // Add it to the sum sum += primevector[i]; if (sum > n) break; if (isprm(sum) == 1) { count++; } } // Return the final count return count;} // Driver Codeint main(){ // Given number N int N = 45; // Function Call cout << countprime(N); return 0;}
// Java program for// the above approachimport java.util.*;class GFG{ // Function to check if a// number is prime or notstatic int isprm(int n){ // Base Case if (n <= 1) return 0; if (n <= 3) return 1; if (n % 2 == 0 || n % 3 == 0) return 0; // Iterate till [5, Math.sqrt(N)] // to detect primality of numbers for (int i = 5; i * i <= n; i = i + 6) { // If N is divisible by i // or i + 2 if (n % i == 0 || n % (i + 2) == 0) return 0; } // Return 1 if N is prime return 1;} // Function to count the prime numbers// which can be expressed as sum of// consecutive prime numbersstatic int countprime(int n){ // Initialize count as 0 int count = 0; // Stores prime numbers Vector<Integer> primevector = new Vector<>(); for (int i = 2; i <= n; i++) { // If i is prime if (isprm(i) == 1) { primevector.add(i); } } // Initialize the sum int sum = primevector.elementAt(0); // Find all required primes upto N for (int i = 1; i < primevector.size(); i++) { // Add it to the sum sum += primevector.elementAt(i); if (sum > n) break; if (isprm(sum) == 1) { count++; } } // Return the final count return count;} // Driver Codepublic static void main(String[] args){ // Given number N int N = 45; // Function Call System.out.print(countprime(N));}} // This code is contributed by gauravrajput1
# Python3 program for the above approach # Function to check if a# number is prime or notdef isprm(n): # Base Case if (n <= 1): return 0 if (n <= 3): return 1 if (n % 2 == 0 or n % 3 == 0): return 0 # Iterate till [5, sqrt(N)] to # detect primality of numbers i = 5 while (i * i <= n): # If N is divisible by i # or i + 2 if (n % i == 0 or n % (i + 2) == 0): return 0 i = i + 6 # Return 1 if N is prime return 1 # Function to count the prime numbers# which can be expressed as sum of# consecutive prime numbersdef countprime(n): # Initialize count as 0 count = 0 # Stores prime numbers primevector = [] for i in range(2, n + 1): # If i is prime if (isprm(i) == 1): primevector.append(i) # Initialize the sum sum = primevector[0] # Find all required primes upto N for i in range(1, len(primevector)): # Add it to the sum sum += primevector[i] if (sum > n): break if (isprm(sum) == 1): count += 1 # Return the final count return count # Driver Code # Given number NN = 45 # Function callprint(countprime(N)) # This code is contributed by code_hunt
// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to check if a// number is prime or notstatic int isprm(int n){ // Base Case if (n <= 1) return 0; if (n <= 3) return 1; if (n % 2 == 0 || n % 3 == 0) return 0; // Iterate till [5, Math.Sqrt(N)] // to detect primality of numbers for (int i = 5; i * i <= n; i = i + 6) { // If N is divisible by i // or i + 2 if (n % i == 0 || n % (i + 2) == 0) return 0; } // Return 1 if N is prime return 1;} // Function to count the prime numbers// which can be expressed as sum of// consecutive prime numbersstatic int countprime(int n){ // Initialize count as 0 int count = 0; // Stores prime numbers List<int> primevector = new List<int>(); for (int i = 2; i <= n; i++) { // If i is prime if (isprm(i) == 1) { primevector.Add(i); } } // Initialize the sum int sum = primevector[0]; // Find all required primes upto N for (int i = 1; i < primevector.Count; i++) { // Add it to the sum sum += primevector[i]; if (sum > n) break; if (isprm(sum) == 1) { count++; } } // Return the readonly count return count;} // Driver Codepublic static void Main(String[] args){ // Given number N int N = 45; // Function Call Console.Write(countprime(N));}} // This code is contributed by shikhasingrajput
<script> // Javascript program for the above approach // Function to check if a// number is prime or notfunction isprm(n){ // Base Case if (n <= 1) return 0; if (n <= 3) return 1; if (n % 2 == 0 || n % 3 == 0) return 0; // Iterate till [5, sqrt(N)] to // detect primality of numbers for (var i = 5; i * i <= n; i = i + 6) { // If N is divisible by i // or i + 2 if (n % i == 0 || n % (i + 2) == 0) return 0; } // Return 1 if N is prime return 1;} // Function to count the prime numbers// which can be expressed as sum of// consecutive prime numbersfunction countprime(n){ // Initialize count as 0 var count = 0; // Stores prime numbers var primevector = []; for (var i = 2; i <= n; i++) { // If i is prime if (isprm(i) == 1) { primevector.push(i); } } // Initialize the sum var sum = primevector[0]; // Find all required primes upto N for (var i = 1; i < primevector.length; i++) { // Add it to the sum sum += primevector[i]; if (sum > n) break; if (isprm(sum) == 1) { count++; } } // Return the final count return count;} // Driver Code// Given number Nvar N = 45;// Function Calldocument.write( countprime(N)); </script>
3
Time Complexity: O(N3/2)Auxiliary Space: O(√N)
Efficient Approach: The above approach can be optimized by precomputing the prime numbers up to N using the Sieve of Eratosthenes.
Time Complexity: O(N*log(logN))Auxiliary Space: O(log(logN))
GauravRajput1
shikhasingrajput
code_hunt
rrrtnx
number-theory
Prime Number
sieve
Mathematical
Searching
Searching
number-theory
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
Binary Search
Linear Search
Program to find largest element in an array
k largest(or smallest) elements in an array
Find the index of an array element in Java | [
{
"code": null,
"e": 24269,
"s": 24241,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 24399,
"s": 24269,
"text": "Given an integer N, the task is to find the number of prime numbers up to N that can be expressed as a sum of consecutive primes."
},
{
"code": null,
"e": 24409,
"s": 24399,
"text": "Examples:"
},
{
"code": null,
"e": 24539,
"s": 24409,
"text": "Input: N = 45Output: 3Explanation:Below are the prime numbers up to 45 that can be expressed as sum of consecutive prime numbers:"
},
{
"code": null,
"e": 24549,
"s": 24539,
"text": "5 = 2 + 3"
},
{
"code": null,
"e": 24568,
"s": 24549,
"text": "17 = 2 + 3 + 5 + 7"
},
{
"code": null,
"e": 24597,
"s": 24568,
"text": "41 = 2 + 3 + 5 + 7 + 11 + 13"
},
{
"code": null,
"e": 24625,
"s": 24597,
"text": "Therefore, the count is 3. "
},
{
"code": null,
"e": 24648,
"s": 24625,
"text": "Input: N = 4Output: 0 "
},
{
"code": null,
"e": 24887,
"s": 24648,
"text": "Approach: The idea is to use the Primality Test Algorithm. Using this, all primes not exceeding N can be found. After that, each number that can be expressed as consecutive primes can be found. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25503,
"s": 24887,
"text": "Traverse through each number from 1 to N, checking if it is a prime, and stored it in a vector.Sort all the stored prime numbers in the vector.Let there be X primes present in the vector. Initialize sum as the smallest prime found i.e., element at index 0 in the vector.Iterate over the range [1, X – 1] and add each element to the sum.After adding, check if the sum is a prime or not and the sum is less than N or not. If it found to be true, then increment the counter. Otherwise, if the sum becomes greater than N, break the loop.After all the above steps, print the count of prime numbers stored on the counter."
},
{
"code": null,
"e": 25599,
"s": 25503,
"text": "Traverse through each number from 1 to N, checking if it is a prime, and stored it in a vector."
},
{
"code": null,
"e": 25648,
"s": 25599,
"text": "Sort all the stored prime numbers in the vector."
},
{
"code": null,
"e": 25776,
"s": 25648,
"text": "Let there be X primes present in the vector. Initialize sum as the smallest prime found i.e., element at index 0 in the vector."
},
{
"code": null,
"e": 25843,
"s": 25776,
"text": "Iterate over the range [1, X – 1] and add each element to the sum."
},
{
"code": null,
"e": 26041,
"s": 25843,
"text": "After adding, check if the sum is a prime or not and the sum is less than N or not. If it found to be true, then increment the counter. Otherwise, if the sum becomes greater than N, break the loop."
},
{
"code": null,
"e": 26124,
"s": 26041,
"text": "After all the above steps, print the count of prime numbers stored on the counter."
},
{
"code": null,
"e": 26175,
"s": 26124,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26179,
"s": 26175,
"text": "C++"
},
{
"code": null,
"e": 26184,
"s": 26179,
"text": "Java"
},
{
"code": null,
"e": 26192,
"s": 26184,
"text": "Python3"
},
{
"code": null,
"e": 26195,
"s": 26192,
"text": "C#"
},
{
"code": null,
"e": 26206,
"s": 26195,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if a// number is prime or notint isprm(int n){ // Base Case if (n <= 1) return 0; if (n <= 3) return 1; if (n % 2 == 0 || n % 3 == 0) return 0; // Iterate till [5, sqrt(N)] to // detect primality of numbers for (int i = 5; i * i <= n; i = i + 6) { // If N is divisible by i // or i + 2 if (n % i == 0 || n % (i + 2) == 0) return 0; } // Return 1 if N is prime return 1;} // Function to count the prime numbers// which can be expressed as sum of// consecutive prime numbersint countprime(int n){ // Initialize count as 0 int count = 0; // Stores prime numbers vector<int> primevector; for (int i = 2; i <= n; i++) { // If i is prime if (isprm(i) == 1) { primevector.push_back(i); } } // Initialize the sum int sum = primevector[0]; // Find all required primes upto N for (int i = 1; i < primevector.size(); i++) { // Add it to the sum sum += primevector[i]; if (sum > n) break; if (isprm(sum) == 1) { count++; } } // Return the final count return count;} // Driver Codeint main(){ // Given number N int N = 45; // Function Call cout << countprime(N); return 0;}",
"e": 27625,
"s": 26206,
"text": null
},
{
"code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function to check if a// number is prime or notstatic int isprm(int n){ // Base Case if (n <= 1) return 0; if (n <= 3) return 1; if (n % 2 == 0 || n % 3 == 0) return 0; // Iterate till [5, Math.sqrt(N)] // to detect primality of numbers for (int i = 5; i * i <= n; i = i + 6) { // If N is divisible by i // or i + 2 if (n % i == 0 || n % (i + 2) == 0) return 0; } // Return 1 if N is prime return 1;} // Function to count the prime numbers// which can be expressed as sum of// consecutive prime numbersstatic int countprime(int n){ // Initialize count as 0 int count = 0; // Stores prime numbers Vector<Integer> primevector = new Vector<>(); for (int i = 2; i <= n; i++) { // If i is prime if (isprm(i) == 1) { primevector.add(i); } } // Initialize the sum int sum = primevector.elementAt(0); // Find all required primes upto N for (int i = 1; i < primevector.size(); i++) { // Add it to the sum sum += primevector.elementAt(i); if (sum > n) break; if (isprm(sum) == 1) { count++; } } // Return the final count return count;} // Driver Codepublic static void main(String[] args){ // Given number N int N = 45; // Function Call System.out.print(countprime(N));}} // This code is contributed by gauravrajput1",
"e": 29061,
"s": 27625,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check if a# number is prime or notdef isprm(n): # Base Case if (n <= 1): return 0 if (n <= 3): return 1 if (n % 2 == 0 or n % 3 == 0): return 0 # Iterate till [5, sqrt(N)] to # detect primality of numbers i = 5 while (i * i <= n): # If N is divisible by i # or i + 2 if (n % i == 0 or n % (i + 2) == 0): return 0 i = i + 6 # Return 1 if N is prime return 1 # Function to count the prime numbers# which can be expressed as sum of# consecutive prime numbersdef countprime(n): # Initialize count as 0 count = 0 # Stores prime numbers primevector = [] for i in range(2, n + 1): # If i is prime if (isprm(i) == 1): primevector.append(i) # Initialize the sum sum = primevector[0] # Find all required primes upto N for i in range(1, len(primevector)): # Add it to the sum sum += primevector[i] if (sum > n): break if (isprm(sum) == 1): count += 1 # Return the final count return count # Driver Code # Given number NN = 45 # Function callprint(countprime(N)) # This code is contributed by code_hunt",
"e": 30357,
"s": 29061,
"text": null
},
{
"code": "// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to check if a// number is prime or notstatic int isprm(int n){ // Base Case if (n <= 1) return 0; if (n <= 3) return 1; if (n % 2 == 0 || n % 3 == 0) return 0; // Iterate till [5, Math.Sqrt(N)] // to detect primality of numbers for (int i = 5; i * i <= n; i = i + 6) { // If N is divisible by i // or i + 2 if (n % i == 0 || n % (i + 2) == 0) return 0; } // Return 1 if N is prime return 1;} // Function to count the prime numbers// which can be expressed as sum of// consecutive prime numbersstatic int countprime(int n){ // Initialize count as 0 int count = 0; // Stores prime numbers List<int> primevector = new List<int>(); for (int i = 2; i <= n; i++) { // If i is prime if (isprm(i) == 1) { primevector.Add(i); } } // Initialize the sum int sum = primevector[0]; // Find all required primes upto N for (int i = 1; i < primevector.Count; i++) { // Add it to the sum sum += primevector[i]; if (sum > n) break; if (isprm(sum) == 1) { count++; } } // Return the readonly count return count;} // Driver Codepublic static void Main(String[] args){ // Given number N int N = 45; // Function Call Console.Write(countprime(N));}} // This code is contributed by shikhasingrajput",
"e": 31768,
"s": 30357,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to check if a// number is prime or notfunction isprm(n){ // Base Case if (n <= 1) return 0; if (n <= 3) return 1; if (n % 2 == 0 || n % 3 == 0) return 0; // Iterate till [5, sqrt(N)] to // detect primality of numbers for (var i = 5; i * i <= n; i = i + 6) { // If N is divisible by i // or i + 2 if (n % i == 0 || n % (i + 2) == 0) return 0; } // Return 1 if N is prime return 1;} // Function to count the prime numbers// which can be expressed as sum of// consecutive prime numbersfunction countprime(n){ // Initialize count as 0 var count = 0; // Stores prime numbers var primevector = []; for (var i = 2; i <= n; i++) { // If i is prime if (isprm(i) == 1) { primevector.push(i); } } // Initialize the sum var sum = primevector[0]; // Find all required primes upto N for (var i = 1; i < primevector.length; i++) { // Add it to the sum sum += primevector[i]; if (sum > n) break; if (isprm(sum) == 1) { count++; } } // Return the final count return count;} // Driver Code// Given number Nvar N = 45;// Function Calldocument.write( countprime(N)); </script>",
"e": 33128,
"s": 31768,
"text": null
},
{
"code": null,
"e": 33130,
"s": 33128,
"text": "3"
},
{
"code": null,
"e": 33177,
"s": 33130,
"text": "Time Complexity: O(N3/2)Auxiliary Space: O(√N)"
},
{
"code": null,
"e": 33308,
"s": 33177,
"text": "Efficient Approach: The above approach can be optimized by precomputing the prime numbers up to N using the Sieve of Eratosthenes."
},
{
"code": null,
"e": 33369,
"s": 33308,
"text": "Time Complexity: O(N*log(logN))Auxiliary Space: O(log(logN))"
},
{
"code": null,
"e": 33383,
"s": 33369,
"text": "GauravRajput1"
},
{
"code": null,
"e": 33400,
"s": 33383,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 33410,
"s": 33400,
"text": "code_hunt"
},
{
"code": null,
"e": 33417,
"s": 33410,
"text": "rrrtnx"
},
{
"code": null,
"e": 33431,
"s": 33417,
"text": "number-theory"
},
{
"code": null,
"e": 33444,
"s": 33431,
"text": "Prime Number"
},
{
"code": null,
"e": 33450,
"s": 33444,
"text": "sieve"
},
{
"code": null,
"e": 33463,
"s": 33450,
"text": "Mathematical"
},
{
"code": null,
"e": 33473,
"s": 33463,
"text": "Searching"
},
{
"code": null,
"e": 33483,
"s": 33473,
"text": "Searching"
},
{
"code": null,
"e": 33497,
"s": 33483,
"text": "number-theory"
},
{
"code": null,
"e": 33510,
"s": 33497,
"text": "Mathematical"
},
{
"code": null,
"e": 33523,
"s": 33510,
"text": "Prime Number"
},
{
"code": null,
"e": 33529,
"s": 33523,
"text": "sieve"
},
{
"code": null,
"e": 33627,
"s": 33529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33636,
"s": 33627,
"text": "Comments"
},
{
"code": null,
"e": 33649,
"s": 33636,
"text": "Old Comments"
},
{
"code": null,
"e": 33673,
"s": 33649,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33716,
"s": 33673,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33743,
"s": 33716,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 33788,
"s": 33743,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 33837,
"s": 33788,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33851,
"s": 33837,
"text": "Binary Search"
},
{
"code": null,
"e": 33865,
"s": 33851,
"text": "Linear Search"
},
{
"code": null,
"e": 33909,
"s": 33865,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 33953,
"s": 33909,
"text": "k largest(or smallest) elements in an array"
}
] |
How to filter data frame by categorical variable in R? | To filter data frame by categorical variable in R, we can follow the below steps −
Use inbuilt data sets or create a new data set and look at top few rows in the data set.
Use inbuilt data sets or create a new data set and look at top few rows in the data set.
Then, look at the bottom few rows in the data set.
Then, look at the bottom few rows in the data set.
Check the data structure.
Check the data structure.
Filter the data by categorical column using split function.
Filter the data by categorical column using split function.
Let’s consider CO2 data set in base R −
Live Demo
data(CO2)
head(CO2,10)
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
Grouped Data: uptake ~ conc | Plant
Plant Type Treatment conc uptake
1 Qn1 Quebec nonchilled 95 16.0
2 Qn1 Quebec nonchilled 175 30.4
3 Qn1 Quebec nonchilled 250 34.8
4 Qn1 Quebec nonchilled 350 37.2
5 Qn1 Quebec nonchilled 500 35.3
6 Qn1 Quebec nonchilled 675 39.2
7 Qn1 Quebec nonchilled 1000 39.7
8 Qn2 Quebec nonchilled 95 13.6
9 Qn2 Quebec nonchilled 175 27.3
10 Qn2 Quebec nonchilled 250 37.1
Use tail function to look at some bottom rows in CO2 data −
Live Demo
data(CO2)
tail(CO2,10)
Grouped Data: uptake ~ conc | Plant
Plant Type Treatment conc uptake
75 Mc2 Mississippi chilled 500 12.5
76 Mc2 Mississippi chilled 675 13.7
77 Mc2 Mississippi chilled 1000 14.4
78 Mc3 Mississippi chilled 95 10.6
79 Mc3 Mississippi chilled 175 18.0
80 Mc3 Mississippi chilled 250 17.9
81 Mc3 Mississippi chilled 350 17.9
82 Mc3 Mississippi chilled 500 17.9
83 Mc3 Mississippi chilled 675 18.9
84 Mc3 Mississippi chilled 1000 19.9
Use str function to check the data structure of data in CO2 −
Live Demo
data(CO2)
str(CO2)
Classes ‘nfnGroupedData’, ‘nfGroupedData’, ‘groupedData’ and 'data.frame': 84 obs.
of 5 variables:
$ Plant : Ord.factor w/ 12 levels "Qn1"<"Qn2"<"Qn3"<..: 1 1 1 1 1 1 1 2 2 2 ...
$ Type : Factor w/ 2 levels "Quebec","Mississippi": 1 1 1 1 1 1 1 1 1 1 ...
$ Treatment: Factor w/ 2 levels "nonchilled","chilled": 1 1 1 1 1 1 1 1 1 1 ...
$ conc : num 95 175 250 350 500 675 1000 95 175 250 ...
$ uptake : num 16 30.4 34.8 37.2 35.3 39.2 39.7 13.6 27.3 37.1 ...
- attr(*, "formula")=Class 'formula' language uptake ~ conc | Plant
.. ..- attr(*, ".Environment")=<environment: R_EmptyEnv>
- attr(*, "outer")=Class 'formula' language ~Treatment * Type
.. ..- attr(*, ".Environment")=<environment: R_EmptyEnv>
- attr(*, "labels")=List of 2
..$ x: chr "Ambient carbon dioxide concentration"
..$ y: chr "CO2 uptake rate"
- attr(*, "units")=List of 2
..$ x: chr "(uL/L)"
..$ y: chr "(umol/m^2 s)"
Using split function to filter the data frame CO2 based on Type column −
Live Demo
data(CO2)
split(CO2,CO2$Type)
$Quebec
Grouped Data: uptake ~ conc | Plant
Plant Type Treatment conc uptake
1 Qn1 Quebec nonchilled 95 16.0
2 Qn1 Quebec nonchilled 175 30.4
3 Qn1 Quebec nonchilled 250 34.8
4 Qn1 Quebec nonchilled 350 37.2
5 Qn1 Quebec nonchilled 500 35.3
6 Qn1 Quebec nonchilled 675 39.2
7 Qn1 Quebec nonchilled 1000 39.7
8 Qn2 Quebec nonchilled 95 13.6
9 Qn2 Quebec nonchilled 175 27.3
10 Qn2 Quebec nonchilled 250 37.1
11 Qn2 Quebec nonchilled 350 41.8
12 Qn2 Quebec nonchilled 500 40.6
13 Qn2 Quebec nonchilled 675 41.4
14 Qn2 Quebec nonchilled 1000 44.3
15 Qn3 Quebec nonchilled 95 16.2
16 Qn3 Quebec nonchilled 175 32.4
17 Qn3 Quebec nonchilled 250 40.3
18 Qn3 Quebec nonchilled 350 42.1
19 Qn3 Quebec nonchilled 500 42.9
20 Qn3 Quebec nonchilled 675 43.9
21 Qn3 Quebec nonchilled 1000 45.5
22 Qc1 Quebec chilled 95 14.2
23 Qc1 Quebec chilled 175 24.1
24 Qc1 Quebec chilled 250 30.3
25 Qc1 Quebec chilled 350 34.6
26 Qc1 Quebec chilled 500 32.5
27 Qc1 Quebec chilled 675 35.4
28 Qc1 Quebec chilled 1000 38.7
29 Qc2 Quebec chilled 95 9.3
30 Qc2 Quebec chilled 175 27.3
31 Qc2 Quebec chilled 250 35.0
32 Qc2 Quebec chilled 350 38.8
33 Qc2 Quebec chilled 500 38.6
34 Qc2 Quebec chilled 675 37.5
35 Qc2 Quebec chilled 1000 42.4
36 Qc3 Quebec chilled 95 15.1
37 Qc3 Quebec chilled 175 21.0
38 Qc3 Quebec chilled 250 38.1
39 Qc3 Quebec chilled 350 34.0
40 Qc3 Quebec chilled 500 38.9
41 Qc3 Quebec chilled 675 39.6
42 Qc3 Quebec chilled 1000 41.4
$Mississippi
Grouped Data: uptake ~ conc | Plant
Plant Type Treatment conc uptake
43 Mn1 Mississippi nonchilled 95 10.6
44 Mn1 Mississippi nonchilled 175 19.2
45 Mn1 Mississippi nonchilled 250 26.2
46 Mn1 Mississippi nonchilled 350 30.0
47 Mn1 Mississippi nonchilled 500 30.9
48 Mn1 Mississippi nonchilled 675 32.4
49 Mn1 Mississippi nonchilled 1000 35.5
50 Mn2 Mississippi nonchilled 95 12.0
51 Mn2 Mississippi nonchilled 175 22.0
52 Mn2 Mississippi nonchilled 250 30.6
53 Mn2 Mississippi nonchilled 350 31.8
54 Mn2 Mississippi nonchilled 500 32.4
55 Mn2 Mississippi nonchilled 675 31.1
56 Mn2 Mississippi nonchilled 1000 31.5
57 Mn3 Mississippi nonchilled 95 11.3
58 Mn3 Mississippi nonchilled 175 19.4
59 Mn3 Mississippi nonchilled 250 25.8
60 Mn3 Mississippi nonchilled 350 27.9
61 Mn3 Mississippi nonchilled 500 28.5
62 Mn3 Mississippi nonchilled 675 28.1
63 Mn3 Mississippi nonchilled 1000 27.8
64 Mc1 Mississippi chilled 95 10.5
65 Mc1 Mississippi chilled 175 14.9
66 Mc1 Mississippi chilled 250 18.1
67 Mc1 Mississippi chilled 350 18.9
68 Mc1 Mississippi chilled 500 19.5
69 Mc1 Mississippi chilled 675 22.2
70 Mc1 Mississippi chilled 1000 21.9
71 Mc2 Mississippi chilled 95 7.7
72 Mc2 Mississippi chilled 175 11.4
73 Mc2 Mississippi chilled 250 12.3
74 Mc2 Mississippi chilled 350 13.0
75 Mc2 Mississippi chilled 500 12.5
76 Mc2 Mississippi chilled 675 13.7
77 Mc2 Mississippi chilled 1000 14.4
78 Mc3 Mississippi chilled 95 10.6
79 Mc3 Mississippi chilled 175 18.0
80 Mc3 Mississippi chilled 250 17.9
81 Mc3 Mississippi chilled 350 17.9
82 Mc3 Mississippi chilled 500 17.9
83 Mc3 Mississippi chilled 675 18.9
84 Mc3 Mississippi chilled 1000 19.9 | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To filter data frame by categorical variable in R, we can follow the below steps −"
},
{
"code": null,
"e": 1234,
"s": 1145,
"text": "Use inbuilt data sets or create a new data set and look at top few rows in the data set."
},
{
"code": null,
"e": 1323,
"s": 1234,
"text": "Use inbuilt data sets or create a new data set and look at top few rows in the data set."
},
{
"code": null,
"e": 1374,
"s": 1323,
"text": "Then, look at the bottom few rows in the data set."
},
{
"code": null,
"e": 1425,
"s": 1374,
"text": "Then, look at the bottom few rows in the data set."
},
{
"code": null,
"e": 1451,
"s": 1425,
"text": "Check the data structure."
},
{
"code": null,
"e": 1477,
"s": 1451,
"text": "Check the data structure."
},
{
"code": null,
"e": 1537,
"s": 1477,
"text": "Filter the data by categorical column using split function."
},
{
"code": null,
"e": 1597,
"s": 1537,
"text": "Filter the data by categorical column using split function."
},
{
"code": null,
"e": 1637,
"s": 1597,
"text": "Let’s consider CO2 data set in base R −"
},
{
"code": null,
"e": 1648,
"s": 1637,
"text": " Live Demo"
},
{
"code": null,
"e": 1671,
"s": 1648,
"text": "data(CO2)\nhead(CO2,10)"
},
{
"code": null,
"e": 1790,
"s": 1671,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 2191,
"s": 1790,
"text": "Grouped Data: uptake ~ conc | Plant\n Plant Type Treatment conc uptake\n1 Qn1 Quebec nonchilled 95 16.0\n2 Qn1 Quebec nonchilled 175 30.4\n3 Qn1 Quebec nonchilled 250 34.8\n4 Qn1 Quebec nonchilled 350 37.2\n5 Qn1 Quebec nonchilled 500 35.3\n6 Qn1 Quebec nonchilled 675 39.2\n7 Qn1 Quebec nonchilled 1000 39.7\n8 Qn2 Quebec nonchilled 95 13.6\n9 Qn2 Quebec nonchilled 175 27.3\n10 Qn2 Quebec nonchilled 250 37.1"
},
{
"code": null,
"e": 2251,
"s": 2191,
"text": "Use tail function to look at some bottom rows in CO2 data −"
},
{
"code": null,
"e": 2262,
"s": 2251,
"text": " Live Demo"
},
{
"code": null,
"e": 2285,
"s": 2262,
"text": "data(CO2)\ntail(CO2,10)"
},
{
"code": null,
"e": 2784,
"s": 2285,
"text": "Grouped Data: uptake ~ conc | Plant\n Plant Type Treatment conc uptake\n75 Mc2 Mississippi chilled 500 12.5\n76 Mc2 Mississippi chilled 675 13.7\n77 Mc2 Mississippi chilled 1000 14.4\n78 Mc3 Mississippi chilled 95 10.6\n79 Mc3 Mississippi chilled 175 18.0\n80 Mc3 Mississippi chilled 250 17.9\n81 Mc3 Mississippi chilled 350 17.9\n82 Mc3 Mississippi chilled 500 17.9\n83 Mc3 Mississippi chilled 675 18.9\n84 Mc3 Mississippi chilled 1000 19.9"
},
{
"code": null,
"e": 2846,
"s": 2784,
"text": "Use str function to check the data structure of data in CO2 −"
},
{
"code": null,
"e": 2857,
"s": 2846,
"text": " Live Demo"
},
{
"code": null,
"e": 2876,
"s": 2857,
"text": "data(CO2)\nstr(CO2)"
},
{
"code": null,
"e": 3775,
"s": 2876,
"text": "Classes ‘nfnGroupedData’, ‘nfGroupedData’, ‘groupedData’ and 'data.frame': 84 obs.\nof 5 variables:\n$ Plant : Ord.factor w/ 12 levels \"Qn1\"<\"Qn2\"<\"Qn3\"<..: 1 1 1 1 1 1 1 2 2 2 ...\n$ Type : Factor w/ 2 levels \"Quebec\",\"Mississippi\": 1 1 1 1 1 1 1 1 1 1 ...\n$ Treatment: Factor w/ 2 levels \"nonchilled\",\"chilled\": 1 1 1 1 1 1 1 1 1 1 ...\n$ conc : num 95 175 250 350 500 675 1000 95 175 250 ...\n$ uptake : num 16 30.4 34.8 37.2 35.3 39.2 39.7 13.6 27.3 37.1 ...\n- attr(*, \"formula\")=Class 'formula' language uptake ~ conc | Plant\n.. ..- attr(*, \".Environment\")=<environment: R_EmptyEnv>\n- attr(*, \"outer\")=Class 'formula' language ~Treatment * Type\n.. ..- attr(*, \".Environment\")=<environment: R_EmptyEnv>\n- attr(*, \"labels\")=List of 2\n..$ x: chr \"Ambient carbon dioxide concentration\"\n..$ y: chr \"CO2 uptake rate\"\n- attr(*, \"units\")=List of 2\n..$ x: chr \"(uL/L)\"\n..$ y: chr \"(umol/m^2 s)\""
},
{
"code": null,
"e": 3848,
"s": 3775,
"text": "Using split function to filter the data frame CO2 based on Type column −"
},
{
"code": null,
"e": 3859,
"s": 3848,
"text": " Live Demo"
},
{
"code": null,
"e": 3889,
"s": 3859,
"text": "data(CO2)\nsplit(CO2,CO2$Type)"
},
{
"code": null,
"e": 7357,
"s": 3889,
"text": "$Quebec\nGrouped Data: uptake ~ conc | Plant\n Plant Type Treatment conc uptake\n1 Qn1 Quebec nonchilled 95 16.0\n2 Qn1 Quebec nonchilled 175 30.4\n3 Qn1 Quebec nonchilled 250 34.8\n4 Qn1 Quebec nonchilled 350 37.2\n5 Qn1 Quebec nonchilled 500 35.3\n6 Qn1 Quebec nonchilled 675 39.2\n7 Qn1 Quebec nonchilled 1000 39.7\n8 Qn2 Quebec nonchilled 95 13.6\n9 Qn2 Quebec nonchilled 175 27.3\n10 Qn2 Quebec nonchilled 250 37.1\n11 Qn2 Quebec nonchilled 350 41.8\n12 Qn2 Quebec nonchilled 500 40.6\n13 Qn2 Quebec nonchilled 675 41.4\n14 Qn2 Quebec nonchilled 1000 44.3\n15 Qn3 Quebec nonchilled 95 16.2\n16 Qn3 Quebec nonchilled 175 32.4\n17 Qn3 Quebec nonchilled 250 40.3\n18 Qn3 Quebec nonchilled 350 42.1\n19 Qn3 Quebec nonchilled 500 42.9\n20 Qn3 Quebec nonchilled 675 43.9\n21 Qn3 Quebec nonchilled 1000 45.5\n22 Qc1 Quebec chilled 95 14.2\n23 Qc1 Quebec chilled 175 24.1\n24 Qc1 Quebec chilled 250 30.3\n25 Qc1 Quebec chilled 350 34.6\n26 Qc1 Quebec chilled 500 32.5\n27 Qc1 Quebec chilled 675 35.4\n28 Qc1 Quebec chilled 1000 38.7\n29 Qc2 Quebec chilled 95 9.3\n30 Qc2 Quebec chilled 175 27.3\n31 Qc2 Quebec chilled 250 35.0\n32 Qc2 Quebec chilled 350 38.8\n33 Qc2 Quebec chilled 500 38.6\n34 Qc2 Quebec chilled 675 37.5\n35 Qc2 Quebec chilled 1000 42.4\n36 Qc3 Quebec chilled 95 15.1\n37 Qc3 Quebec chilled 175 21.0\n38 Qc3 Quebec chilled 250 38.1\n39 Qc3 Quebec chilled 350 34.0\n40 Qc3 Quebec chilled 500 38.9\n41 Qc3 Quebec chilled 675 39.6\n42 Qc3 Quebec chilled 1000 41.4\n\n$Mississippi\nGrouped Data: uptake ~ conc | Plant\n Plant Type Treatment conc uptake\n43 Mn1 Mississippi nonchilled 95 10.6\n44 Mn1 Mississippi nonchilled 175 19.2\n45 Mn1 Mississippi nonchilled 250 26.2\n46 Mn1 Mississippi nonchilled 350 30.0\n47 Mn1 Mississippi nonchilled 500 30.9\n48 Mn1 Mississippi nonchilled 675 32.4\n49 Mn1 Mississippi nonchilled 1000 35.5\n50 Mn2 Mississippi nonchilled 95 12.0\n51 Mn2 Mississippi nonchilled 175 22.0\n52 Mn2 Mississippi nonchilled 250 30.6\n53 Mn2 Mississippi nonchilled 350 31.8\n54 Mn2 Mississippi nonchilled 500 32.4\n55 Mn2 Mississippi nonchilled 675 31.1\n56 Mn2 Mississippi nonchilled 1000 31.5\n57 Mn3 Mississippi nonchilled 95 11.3\n58 Mn3 Mississippi nonchilled 175 19.4\n59 Mn3 Mississippi nonchilled 250 25.8\n60 Mn3 Mississippi nonchilled 350 27.9\n61 Mn3 Mississippi nonchilled 500 28.5\n62 Mn3 Mississippi nonchilled 675 28.1\n63 Mn3 Mississippi nonchilled 1000 27.8\n64 Mc1 Mississippi chilled 95 10.5\n65 Mc1 Mississippi chilled 175 14.9\n66 Mc1 Mississippi chilled 250 18.1\n67 Mc1 Mississippi chilled 350 18.9\n68 Mc1 Mississippi chilled 500 19.5\n69 Mc1 Mississippi chilled 675 22.2\n70 Mc1 Mississippi chilled 1000 21.9\n71 Mc2 Mississippi chilled 95 7.7\n72 Mc2 Mississippi chilled 175 11.4\n73 Mc2 Mississippi chilled 250 12.3\n74 Mc2 Mississippi chilled 350 13.0\n75 Mc2 Mississippi chilled 500 12.5\n76 Mc2 Mississippi chilled 675 13.7\n77 Mc2 Mississippi chilled 1000 14.4\n78 Mc3 Mississippi chilled 95 10.6\n79 Mc3 Mississippi chilled 175 18.0\n80 Mc3 Mississippi chilled 250 17.9\n81 Mc3 Mississippi chilled 350 17.9\n82 Mc3 Mississippi chilled 500 17.9\n83 Mc3 Mississippi chilled 675 18.9\n84 Mc3 Mississippi chilled 1000 19.9"
}
] |
ASP.NET - HTML Server | The HTML server controls are basically the standard HTML controls enhanced to enable server side processing. The HTML controls such as the header tags, anchor tags, and input elements are not processed by the server but are sent to the browser for display.
They are specifically converted to a server control by adding the attribute runat="server" and adding an id attribute to make them available for server-side processing.
For example, consider the HTML input control:
<input type="text" size="40">
It could be converted to a server control, by adding the runat and id attribute:
<input type="text" id="testtext" size="40" runat="server">
Although ASP.NET server controls can perform every job accomplished by the HTML server controls, the later controls are useful in the following cases:
Using static tables for layout purposes.
Converting a HTML page to run under ASP.NET
The following table describes the HTML server controls:
The following example uses a basic HTML table for layout. It uses some boxes for getting input from the users such as name, address, city, state etc. It also has a button control, which is clicked to get the user data displayed in the last row of the table.
The page should look like this in the design view:
The code for the content page shows the use of the HTML table element for layout.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="htmlserver._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.style1
{
width: 156px;
}
.style2
{
width: 332px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 54%;">
<tr>
<td class="style1">Name:</td>
<td class="style2">
<asp:TextBox ID="txtname" runat="server" style="width:230px">
</asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">Street</td>
<td class="style2">
<asp:TextBox ID="txtstreet" runat="server" style="width:230px">
</asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">City</td>
<td class="style2">
<asp:TextBox ID="txtcity" runat="server" style="width:230px">
</asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">State</td>
<td class="style2">
<asp:TextBox ID="txtstate" runat="server" style="width:230px">
</asp:TextBox>
</td>
</tr>
<tr>
<td class="style1"> </td>
<td class="style2"></td>
</tr>
<tr>
<td class="style1"></td>
<td ID="displayrow" runat ="server" class="style2">
</td>
</tr>
</table>
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click" />
</form>
</body>
</html>
The code behind the button control:
protected void Button1_Click(object sender, EventArgs e)
{
string str = "";
str += txtname.Text + "<br />";
str += txtstreet.Text + "<br />";
str += txtcity.Text + "<br />";
str += txtstate.Text + "<br />";
displayrow.InnerHtml = str;
}
Observe the following:
The standard HTML tags have been used for the page layout.
The standard HTML tags have been used for the page layout.
The last row of the HTML table is used for data display. It needed server side processing, so an ID attribute and the runat attribute has been added to it.
The last row of the HTML table is used for data display. It needed server side processing, so an ID attribute and the runat attribute has been added to it.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2604,
"s": 2347,
"text": "The HTML server controls are basically the standard HTML controls enhanced to enable server side processing. The HTML controls such as the header tags, anchor tags, and input elements are not processed by the server but are sent to the browser for display."
},
{
"code": null,
"e": 2773,
"s": 2604,
"text": "They are specifically converted to a server control by adding the attribute runat=\"server\" and adding an id attribute to make them available for server-side processing."
},
{
"code": null,
"e": 2819,
"s": 2773,
"text": "For example, consider the HTML input control:"
},
{
"code": null,
"e": 2849,
"s": 2819,
"text": "<input type=\"text\" size=\"40\">"
},
{
"code": null,
"e": 2930,
"s": 2849,
"text": "It could be converted to a server control, by adding the runat and id attribute:"
},
{
"code": null,
"e": 2989,
"s": 2930,
"text": "<input type=\"text\" id=\"testtext\" size=\"40\" runat=\"server\">"
},
{
"code": null,
"e": 3140,
"s": 2989,
"text": "Although ASP.NET server controls can perform every job accomplished by the HTML server controls, the later controls are useful in the following cases:"
},
{
"code": null,
"e": 3181,
"s": 3140,
"text": "Using static tables for layout purposes."
},
{
"code": null,
"e": 3225,
"s": 3181,
"text": "Converting a HTML page to run under ASP.NET"
},
{
"code": null,
"e": 3281,
"s": 3225,
"text": "The following table describes the HTML server controls:"
},
{
"code": null,
"e": 3539,
"s": 3281,
"text": "The following example uses a basic HTML table for layout. It uses some boxes for getting input from the users such as name, address, city, state etc. It also has a button control, which is clicked to get the user data displayed in the last row of the table."
},
{
"code": null,
"e": 3590,
"s": 3539,
"text": "The page should look like this in the design view:"
},
{
"code": null,
"e": 3672,
"s": 3590,
"text": "The code for the content page shows the use of the HTML table element for layout."
},
{
"code": null,
"e": 5910,
"s": 3672,
"text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"htmlserver._Default\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n\n <head runat=\"server\">\n <title>Untitled Page</title>\n \n <style type=\"text/css\">\n .style1\n { \n width: 156px;\n }\n .style2\n {\n width: 332px;\n }\n </style>\n \n </head>\n \n <body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <table style=\"width: 54%;\">\n <tr>\n <td class=\"style1\">Name:</td>\n <td class=\"style2\">\n <asp:TextBox ID=\"txtname\" runat=\"server\" style=\"width:230px\">\n </asp:TextBox>\n </td>\n </tr>\n\t\t\t\t\n <tr>\n <td class=\"style1\">Street</td>\n <td class=\"style2\">\n <asp:TextBox ID=\"txtstreet\" runat=\"server\" style=\"width:230px\">\n </asp:TextBox>\n </td>\n </tr>\n\t\t\t\t\n <tr>\n <td class=\"style1\">City</td>\n <td class=\"style2\">\n <asp:TextBox ID=\"txtcity\" runat=\"server\" style=\"width:230px\">\n </asp:TextBox>\n </td>\n </tr>\n\t\t\t\t\n <tr>\n <td class=\"style1\">State</td>\n <td class=\"style2\">\n <asp:TextBox ID=\"txtstate\" runat=\"server\" style=\"width:230px\">\n </asp:TextBox>\n </td>\n </tr>\n\t\t\t\t\n <tr>\n <td class=\"style1\"> </td>\n <td class=\"style2\"></td>\n </tr>\n\t\t\t\t\n <tr>\n <td class=\"style1\"></td>\n <td ID=\"displayrow\" runat =\"server\" class=\"style2\">\n </td>\n </tr>\n </table>\n \n </div>\n <asp:Button ID=\"Button1\" runat=\"server\" onclick=\"Button1_Click\" Text=\"Click\" />\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 5946,
"s": 5910,
"text": "The code behind the button control:"
},
{
"code": null,
"e": 6201,
"s": 5946,
"text": "protected void Button1_Click(object sender, EventArgs e)\n{\n string str = \"\";\n str += txtname.Text + \"<br />\";\n str += txtstreet.Text + \"<br />\";\n str += txtcity.Text + \"<br />\";\n str += txtstate.Text + \"<br />\";\n displayrow.InnerHtml = str;\n}"
},
{
"code": null,
"e": 6224,
"s": 6201,
"text": "Observe the following:"
},
{
"code": null,
"e": 6283,
"s": 6224,
"text": "The standard HTML tags have been used for the page layout."
},
{
"code": null,
"e": 6342,
"s": 6283,
"text": "The standard HTML tags have been used for the page layout."
},
{
"code": null,
"e": 6498,
"s": 6342,
"text": "The last row of the HTML table is used for data display. It needed server side processing, so an ID attribute and the runat attribute has been added to it."
},
{
"code": null,
"e": 6654,
"s": 6498,
"text": "The last row of the HTML table is used for data display. It needed server side processing, so an ID attribute and the runat attribute has been added to it."
},
{
"code": null,
"e": 6689,
"s": 6654,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6703,
"s": 6689,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6738,
"s": 6703,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6761,
"s": 6738,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6795,
"s": 6761,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 6815,
"s": 6795,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6850,
"s": 6815,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6867,
"s": 6850,
"text": " University Code"
},
{
"code": null,
"e": 6902,
"s": 6867,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6919,
"s": 6902,
"text": " University Code"
},
{
"code": null,
"e": 6953,
"s": 6919,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6968,
"s": 6953,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 6975,
"s": 6968,
"text": " Print"
},
{
"code": null,
"e": 6986,
"s": 6975,
"text": " Add Notes"
}
] |
Forward List and List of Tuples in C++ with Examples - GeeksforGeeks | 24 Dec, 2021
What is Forward List?
Forward list in STL is used to implement a singly linked list. It was introduced from C++11 onwards, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next element while the list keeps track of both the next and previous elements, thus increasing the storage space required to store each element. The drawback of a forward list is that it cannot be iterated backward and its individual elements cannot be accessed directly. Forward List is preferred over the list when only forward traversal is required (same as singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of the graph, etc.
Functions associated with forward list:
push_front(): This function is used to insert the element at the first position in a forward list. The value from this function is copied to the space before the first element in the container. The size of the forward list increases by 1.
pop_front(): This function is used to delete the first element of the list.
empty(): Returns whether the list is empty(1) or not(0).
What is List?
Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list.
Functions associated with a list:
front(): Returns the value of the first element in the list.
back(): Returns the value of the last element in the list.
push_front(x): Adds a new element ‘x’ at the beginning of the list.
push_back(x): Adds a new element ‘x’ at the end of the list.
empty(): Returns whether the list is empty(1) or not(0).
What is Tuple?
A tuple in C++ is an object that has the ability to group a number of elements. The elements can be of the same type as well as different data types. The order in which tuple elements are initialized can be accessed in the same order.
Functions associated with a tuple:
1. make_tuple(): It is used to assign tuples with values. The values passed should be in order with the values declared in the tuple.2. get(): It is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element.
Forward list of tuples
In C++, A forward list of tuples is a forward list in which each element is a tuple itself. Although, a tuple can contain more or fewer elements, for simplicity we have used tuples having three elements only.
Syntax:
forward_list<tuple<dataType1, dataType2, dataType3> myForwardList;
Here,
dataType1, dataType2, and dataType3 are similar or dissimilar data types.
Example 1: Below is the C++ program to demonstrate the working of forward list of tuples.
C++
// C++ program to demonstrate // the working of forward list// of tuples#include <bits/stdc++.h>using namespace std; // Function to print forward // list elementsvoid print(forward_list<tuple<int, int, int>> &forwardListOftuples){ for (auto currentTuple : forwardListOftuples) { // Each element of the forward list is // a tuple itself tuple<int, int, int> tuple = currentTuple; cout << "[ "; // Printing tuple elements cout << get<0>(currentTuple) << ' ' << get<1>(currentTuple) << ' ' << get<2>(currentTuple); cout << ']'; cout << '\n'; }} // Driver codeint main(){ // Declaring a forward list of tuples // having integer values only forward_list<tuple<int, int, int> > forwardListOftuples; // Declaring a tuple tuple<int, int, int> tuple1; // Initializing the // tuple tuple1 = make_tuple(11, 22, 33); // Push the tuple at the back // in the forward list forwardListOftuples.push_front(tuple1); // Declaring another tuple tuple<int, int, int> tuple2; // Initializing the // tuple tuple2 = make_tuple(33, 44, 55); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple2); // Declaring another tuple tuple<int, int, int> tuple3; // Initializing the tuple tuple3 = make_tuple(55, 66, 77); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple3); // Declaring another tuple tuple<int, int, int> tuple4; // Initializing the tuple tuple4 = make_tuple(77, 88, 99); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple4); // Calling print function print(forwardListOftuples); return 0;}
Output:
[ 77 88 99][ 55 66 77][ 33 44 55][ 11 22 33]
Example 2: Below is the C++ program to demonstrate the working of forward list of tuples.
C++
// C++ program to demonstrate // the working of forward list// of tuples#include <bits/stdc++.h>using namespace std; // Function to print forward // list elementsvoid print(forward_list<tuple<string, string, bool>> &forwardListOftuples){ for (auto currentTuple : forwardListOftuples) { // Each element of the forward list is // a tuple itself tuple<string, string, bool> tuple = currentTuple; cout << "[ "; // Printing tuple elements cout << get<0>(currentTuple) << ' ' << get<1>(currentTuple) << ' ' << get<2>(currentTuple); cout << ']'; cout << '\n'; }} // Driver codeint main(){ // Declaring a forward list of tuples // having first two values of string // type and third value as bool type forward_list<tuple<string, string, bool>> forwardListOftuples; // Declaring a tuple tuple<string, string, bool> tuple1; // Initializing the // tuple tuple1 = make_tuple("GeeksforGeeks", "Computer Science", 0); // Push the tuple at the back // in the forward list forwardListOftuples.push_front(tuple1); // Declaring another tuple tuple<string, string, bool> tuple2; // Initializing the // tuple tuple2 = make_tuple("Java", "C++", 1); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple2); // Declaring another tuple tuple<string, string, bool> tuple3; // Initializing the tuple tuple3 = make_tuple("GFG", "C", 1); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple3); // Declaring another tuple tuple<string, string, bool> tuple4; // Initializing the tuple tuple4 = make_tuple("Swift", "Python", 0); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple4); // Calling print function print(forwardListOftuples); return 0;}
Output:
[ Swift Python 0][ GFG C 1][ Java C++ 1][ GeeksforGeeks Computer Science 0]
List of tuples
In C++, a list of tuples is a list in which each element is a tuple itself. Although, a tuple can contain more or fewer elements, for simplicity we have used tuples having three elements only.
Syntax:
list<tuple<dataType1, dataType2, dataType3> myList;
Here,
dataType1, dataType2, and dataType3 are similar or dissimilar data types.
Example 1: Below is the C++ program to demonstrate the working of list of tuples.
C++
// C++ program to demonstrate // the working of list of tuples#include <bits/stdc++.h>using namespace std; // Function to print// list elementsvoid print(list<tuple<int, int, int>> &listOftuples){ for (auto currentTuple : listOftuples) { // Each element of the List is // a tuple itself tuple<int, int, int> tuple = currentTuple; cout << "[ "; // Printing tuple elements cout << get<0>(currentTuple) << ' ' << get<1>(currentTuple) << ' ' << get<2>(currentTuple); cout << ']'; cout << '\n'; }} // Driver codeint main(){ // Declaring a List of tuples // having all values of integer type list<tuple<int, int, int>> listOftuples; // Declaring a tuple tuple<int, int, int> tuple1; // Initializing the // tuple tuple1 = make_tuple(11, 22, 33); // Push the tuple at the back // in the List listOftuples.push_front(tuple1); // Declaring another tuple tuple<int, int, int> tuple2; // Initializing the // tuple tuple2 = make_tuple(33, 44, 55); // Push the tuple at the front // in the List listOftuples.push_front(tuple2); // Declaring another tuple tuple<int, int, int> tuple3; // Initializing the tuple tuple3 = make_tuple(55, 66, 77); // Push the tuple at the front // in the List listOftuples.push_front(tuple3); // Declaring another tuple tuple<int, int, int> tuple4; // Initializing the tuple tuple4 = make_tuple(77, 88, 99); // Push the tuple at the front // in the List listOftuples.push_front(tuple4); // Calling print function print(listOftuples); return 0;}
Output:
[ 77 88 99][ 55 66 77][ 33 44 55][ 11 22 33]
Example 2: Below is the C++ program to demonstrate the working of list of tuples.
C++
// C++ program to demonstrate // the working of list of tuples#include <bits/stdc++.h>using namespace std; // Function to print// list elementsvoid print(list<tuple<string, string, bool>> &listOftuples){ for (auto currentTuple : listOftuples) { // Each element of the List is // a tuple itself tuple<string, string, bool> tuple = currentTuple; cout << "[ "; // Printing tuple elements cout << get<0>(currentTuple) << ' ' << get<1>(currentTuple) << ' ' << get<2>(currentTuple); cout << ']'; cout << '\n'; }} // Driver codeint main(){ // Declaring a List of tuples // having first two values as string type // and third value is of bool type list<tuple<string, string, bool>> listOftuples; // Declaring a tuple tuple<string, string, bool> tuple1; // Initializing the // tuple tuple1 = make_tuple("GeeksforGeeks", "Computer Science", 0); // Push the tuple at the back // in the List listOftuples.push_front(tuple1); // Declaring another tuple tuple<string, string, bool> tuple2; // Initializing the // tuple tuple2 = make_tuple("Java", "C++", 1); // Push the tuple at the front // in the List listOftuples.push_front(tuple2); // Declaring another tuple tuple<string, string, bool> tuple3; // Initializing the tuple tuple3 = make_tuple("GFG", "C", 1); // Push the tuple at the front // in the List listOftuples.push_front(tuple3); // Declaring another tuple tuple<string, string, bool> tuple4; // Initializing the tuple tuple4 = make_tuple("Swift", "Python", 0); // Push the tuple at the front // in the List listOftuples.push_front(tuple4); // Calling print function print(listOftuples); return 0;}
Output:
[ Swift Python 0][ GFG C 1][ Java C++ 1][ GeeksforGeeks Computer Science 0]
simranarora5sos
CPP-forward-list
cpp-list
cpp-tuple
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Friend class and function in C++
Polymorphism in C++
List in C++ Standard Template Library (STL)
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Queue in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 23707,
"s": 23679,
"text": "\n24 Dec, 2021"
},
{
"code": null,
"e": 23729,
"s": 23707,
"text": "What is Forward List?"
},
{
"code": null,
"e": 24632,
"s": 23729,
"text": "Forward list in STL is used to implement a singly linked list. It was introduced from C++11 onwards, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next element while the list keeps track of both the next and previous elements, thus increasing the storage space required to store each element. The drawback of a forward list is that it cannot be iterated backward and its individual elements cannot be accessed directly. Forward List is preferred over the list when only forward traversal is required (same as singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of the graph, etc."
},
{
"code": null,
"e": 24672,
"s": 24632,
"text": "Functions associated with forward list:"
},
{
"code": null,
"e": 24911,
"s": 24672,
"text": "push_front(): This function is used to insert the element at the first position in a forward list. The value from this function is copied to the space before the first element in the container. The size of the forward list increases by 1."
},
{
"code": null,
"e": 24987,
"s": 24911,
"text": "pop_front(): This function is used to delete the first element of the list."
},
{
"code": null,
"e": 25044,
"s": 24987,
"text": "empty(): Returns whether the list is empty(1) or not(0)."
},
{
"code": null,
"e": 25058,
"s": 25044,
"text": "What is List?"
},
{
"code": null,
"e": 25384,
"s": 25058,
"text": "Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list. "
},
{
"code": null,
"e": 25418,
"s": 25384,
"text": "Functions associated with a list:"
},
{
"code": null,
"e": 25479,
"s": 25418,
"text": "front(): Returns the value of the first element in the list."
},
{
"code": null,
"e": 25538,
"s": 25479,
"text": "back(): Returns the value of the last element in the list."
},
{
"code": null,
"e": 25606,
"s": 25538,
"text": "push_front(x): Adds a new element ‘x’ at the beginning of the list."
},
{
"code": null,
"e": 25667,
"s": 25606,
"text": "push_back(x): Adds a new element ‘x’ at the end of the list."
},
{
"code": null,
"e": 25724,
"s": 25667,
"text": "empty(): Returns whether the list is empty(1) or not(0)."
},
{
"code": null,
"e": 25739,
"s": 25724,
"text": "What is Tuple?"
},
{
"code": null,
"e": 25974,
"s": 25739,
"text": "A tuple in C++ is an object that has the ability to group a number of elements. The elements can be of the same type as well as different data types. The order in which tuple elements are initialized can be accessed in the same order."
},
{
"code": null,
"e": 26009,
"s": 25974,
"text": "Functions associated with a tuple:"
},
{
"code": null,
"e": 26294,
"s": 26009,
"text": "1. make_tuple(): It is used to assign tuples with values. The values passed should be in order with the values declared in the tuple.2. get(): It is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element."
},
{
"code": null,
"e": 26317,
"s": 26294,
"text": "Forward list of tuples"
},
{
"code": null,
"e": 26527,
"s": 26317,
"text": "In C++, A forward list of tuples is a forward list in which each element is a tuple itself. Although, a tuple can contain more or fewer elements, for simplicity we have used tuples having three elements only. "
},
{
"code": null,
"e": 26535,
"s": 26527,
"text": "Syntax:"
},
{
"code": null,
"e": 26603,
"s": 26535,
"text": " forward_list<tuple<dataType1, dataType2, dataType3> myForwardList;"
},
{
"code": null,
"e": 26610,
"s": 26603,
"text": "Here, "
},
{
"code": null,
"e": 26684,
"s": 26610,
"text": "dataType1, dataType2, and dataType3 are similar or dissimilar data types."
},
{
"code": null,
"e": 26775,
"s": 26684,
"text": "Example 1: Below is the C++ program to demonstrate the working of forward list of tuples. "
},
{
"code": null,
"e": 26779,
"s": 26775,
"text": "C++"
},
{
"code": "// C++ program to demonstrate // the working of forward list// of tuples#include <bits/stdc++.h>using namespace std; // Function to print forward // list elementsvoid print(forward_list<tuple<int, int, int>> &forwardListOftuples){ for (auto currentTuple : forwardListOftuples) { // Each element of the forward list is // a tuple itself tuple<int, int, int> tuple = currentTuple; cout << \"[ \"; // Printing tuple elements cout << get<0>(currentTuple) << ' ' << get<1>(currentTuple) << ' ' << get<2>(currentTuple); cout << ']'; cout << '\\n'; }} // Driver codeint main(){ // Declaring a forward list of tuples // having integer values only forward_list<tuple<int, int, int> > forwardListOftuples; // Declaring a tuple tuple<int, int, int> tuple1; // Initializing the // tuple tuple1 = make_tuple(11, 22, 33); // Push the tuple at the back // in the forward list forwardListOftuples.push_front(tuple1); // Declaring another tuple tuple<int, int, int> tuple2; // Initializing the // tuple tuple2 = make_tuple(33, 44, 55); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple2); // Declaring another tuple tuple<int, int, int> tuple3; // Initializing the tuple tuple3 = make_tuple(55, 66, 77); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple3); // Declaring another tuple tuple<int, int, int> tuple4; // Initializing the tuple tuple4 = make_tuple(77, 88, 99); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple4); // Calling print function print(forwardListOftuples); return 0;}",
"e": 28507,
"s": 26779,
"text": null
},
{
"code": null,
"e": 28515,
"s": 28507,
"text": "Output:"
},
{
"code": null,
"e": 28560,
"s": 28515,
"text": "[ 77 88 99][ 55 66 77][ 33 44 55][ 11 22 33]"
},
{
"code": null,
"e": 28650,
"s": 28560,
"text": "Example 2: Below is the C++ program to demonstrate the working of forward list of tuples."
},
{
"code": null,
"e": 28654,
"s": 28650,
"text": "C++"
},
{
"code": "// C++ program to demonstrate // the working of forward list// of tuples#include <bits/stdc++.h>using namespace std; // Function to print forward // list elementsvoid print(forward_list<tuple<string, string, bool>> &forwardListOftuples){ for (auto currentTuple : forwardListOftuples) { // Each element of the forward list is // a tuple itself tuple<string, string, bool> tuple = currentTuple; cout << \"[ \"; // Printing tuple elements cout << get<0>(currentTuple) << ' ' << get<1>(currentTuple) << ' ' << get<2>(currentTuple); cout << ']'; cout << '\\n'; }} // Driver codeint main(){ // Declaring a forward list of tuples // having first two values of string // type and third value as bool type forward_list<tuple<string, string, bool>> forwardListOftuples; // Declaring a tuple tuple<string, string, bool> tuple1; // Initializing the // tuple tuple1 = make_tuple(\"GeeksforGeeks\", \"Computer Science\", 0); // Push the tuple at the back // in the forward list forwardListOftuples.push_front(tuple1); // Declaring another tuple tuple<string, string, bool> tuple2; // Initializing the // tuple tuple2 = make_tuple(\"Java\", \"C++\", 1); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple2); // Declaring another tuple tuple<string, string, bool> tuple3; // Initializing the tuple tuple3 = make_tuple(\"GFG\", \"C\", 1); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple3); // Declaring another tuple tuple<string, string, bool> tuple4; // Initializing the tuple tuple4 = make_tuple(\"Swift\", \"Python\", 0); // Push the tuple at the front // in the forward list forwardListOftuples.push_front(tuple4); // Calling print function print(forwardListOftuples); return 0;}",
"e": 30571,
"s": 28654,
"text": null
},
{
"code": null,
"e": 30579,
"s": 30571,
"text": "Output:"
},
{
"code": null,
"e": 30655,
"s": 30579,
"text": "[ Swift Python 0][ GFG C 1][ Java C++ 1][ GeeksforGeeks Computer Science 0]"
},
{
"code": null,
"e": 30670,
"s": 30655,
"text": "List of tuples"
},
{
"code": null,
"e": 30864,
"s": 30670,
"text": "In C++, a list of tuples is a list in which each element is a tuple itself. Although, a tuple can contain more or fewer elements, for simplicity we have used tuples having three elements only. "
},
{
"code": null,
"e": 30872,
"s": 30864,
"text": "Syntax:"
},
{
"code": null,
"e": 30924,
"s": 30872,
"text": "list<tuple<dataType1, dataType2, dataType3> myList;"
},
{
"code": null,
"e": 30930,
"s": 30924,
"text": "Here,"
},
{
"code": null,
"e": 31004,
"s": 30930,
"text": "dataType1, dataType2, and dataType3 are similar or dissimilar data types."
},
{
"code": null,
"e": 31086,
"s": 31004,
"text": "Example 1: Below is the C++ program to demonstrate the working of list of tuples."
},
{
"code": null,
"e": 31090,
"s": 31086,
"text": "C++"
},
{
"code": "// C++ program to demonstrate // the working of list of tuples#include <bits/stdc++.h>using namespace std; // Function to print// list elementsvoid print(list<tuple<int, int, int>> &listOftuples){ for (auto currentTuple : listOftuples) { // Each element of the List is // a tuple itself tuple<int, int, int> tuple = currentTuple; cout << \"[ \"; // Printing tuple elements cout << get<0>(currentTuple) << ' ' << get<1>(currentTuple) << ' ' << get<2>(currentTuple); cout << ']'; cout << '\\n'; }} // Driver codeint main(){ // Declaring a List of tuples // having all values of integer type list<tuple<int, int, int>> listOftuples; // Declaring a tuple tuple<int, int, int> tuple1; // Initializing the // tuple tuple1 = make_tuple(11, 22, 33); // Push the tuple at the back // in the List listOftuples.push_front(tuple1); // Declaring another tuple tuple<int, int, int> tuple2; // Initializing the // tuple tuple2 = make_tuple(33, 44, 55); // Push the tuple at the front // in the List listOftuples.push_front(tuple2); // Declaring another tuple tuple<int, int, int> tuple3; // Initializing the tuple tuple3 = make_tuple(55, 66, 77); // Push the tuple at the front // in the List listOftuples.push_front(tuple3); // Declaring another tuple tuple<int, int, int> tuple4; // Initializing the tuple tuple4 = make_tuple(77, 88, 99); // Push the tuple at the front // in the List listOftuples.push_front(tuple4); // Calling print function print(listOftuples); return 0;}",
"e": 32683,
"s": 31090,
"text": null
},
{
"code": null,
"e": 32691,
"s": 32683,
"text": "Output:"
},
{
"code": null,
"e": 32736,
"s": 32691,
"text": "[ 77 88 99][ 55 66 77][ 33 44 55][ 11 22 33]"
},
{
"code": null,
"e": 32818,
"s": 32736,
"text": "Example 2: Below is the C++ program to demonstrate the working of list of tuples."
},
{
"code": null,
"e": 32822,
"s": 32818,
"text": "C++"
},
{
"code": "// C++ program to demonstrate // the working of list of tuples#include <bits/stdc++.h>using namespace std; // Function to print// list elementsvoid print(list<tuple<string, string, bool>> &listOftuples){ for (auto currentTuple : listOftuples) { // Each element of the List is // a tuple itself tuple<string, string, bool> tuple = currentTuple; cout << \"[ \"; // Printing tuple elements cout << get<0>(currentTuple) << ' ' << get<1>(currentTuple) << ' ' << get<2>(currentTuple); cout << ']'; cout << '\\n'; }} // Driver codeint main(){ // Declaring a List of tuples // having first two values as string type // and third value is of bool type list<tuple<string, string, bool>> listOftuples; // Declaring a tuple tuple<string, string, bool> tuple1; // Initializing the // tuple tuple1 = make_tuple(\"GeeksforGeeks\", \"Computer Science\", 0); // Push the tuple at the back // in the List listOftuples.push_front(tuple1); // Declaring another tuple tuple<string, string, bool> tuple2; // Initializing the // tuple tuple2 = make_tuple(\"Java\", \"C++\", 1); // Push the tuple at the front // in the List listOftuples.push_front(tuple2); // Declaring another tuple tuple<string, string, bool> tuple3; // Initializing the tuple tuple3 = make_tuple(\"GFG\", \"C\", 1); // Push the tuple at the front // in the List listOftuples.push_front(tuple3); // Declaring another tuple tuple<string, string, bool> tuple4; // Initializing the tuple tuple4 = make_tuple(\"Swift\", \"Python\", 0); // Push the tuple at the front // in the List listOftuples.push_front(tuple4); // Calling print function print(listOftuples); return 0;}",
"e": 34600,
"s": 32822,
"text": null
},
{
"code": null,
"e": 34608,
"s": 34600,
"text": "Output:"
},
{
"code": null,
"e": 34684,
"s": 34608,
"text": "[ Swift Python 0][ GFG C 1][ Java C++ 1][ GeeksforGeeks Computer Science 0]"
},
{
"code": null,
"e": 34700,
"s": 34684,
"text": "simranarora5sos"
},
{
"code": null,
"e": 34717,
"s": 34700,
"text": "CPP-forward-list"
},
{
"code": null,
"e": 34726,
"s": 34717,
"text": "cpp-list"
},
{
"code": null,
"e": 34736,
"s": 34726,
"text": "cpp-tuple"
},
{
"code": null,
"e": 34740,
"s": 34736,
"text": "STL"
},
{
"code": null,
"e": 34744,
"s": 34740,
"text": "C++"
},
{
"code": null,
"e": 34748,
"s": 34744,
"text": "STL"
},
{
"code": null,
"e": 34752,
"s": 34748,
"text": "CPP"
},
{
"code": null,
"e": 34850,
"s": 34752,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34859,
"s": 34850,
"text": "Comments"
},
{
"code": null,
"e": 34872,
"s": 34859,
"text": "Old Comments"
},
{
"code": null,
"e": 34900,
"s": 34872,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 34924,
"s": 34900,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 34957,
"s": 34924,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 34977,
"s": 34957,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 35021,
"s": 34977,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 35065,
"s": 35021,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 35101,
"s": 35065,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 35152,
"s": 35101,
"text": "new and delete operators in C++ for dynamic memory"
},
{
"code": null,
"e": 35171,
"s": 35152,
"text": "Destructors in C++"
}
] |
Miscellaneous Classification Methods | Here we will discuss other classification methods such as Genetic Algorithms, Rough Set Approach, and Fuzzy Set Approach.
The idea of genetic algorithm is derived from natural evolution. In genetic algorithm, first of all, the initial population is created. This initial population consists of randomly generated rules. We can represent each rule by a string of bits.
For example, in a given training set, the samples are described by two Boolean attributes such as A1 and A2. And this given training set contains two classes such as C1 and C2.
We can encode the rule IF A1 AND NOT A2 THEN C2 into a bit string 100. In this bit representation, the two leftmost bits represent the attribute A1 and A2, respectively.
Likewise, the rule IF NOT A1 AND NOT A2 THEN C1 can be encoded as 001.
Note − If the attribute has K values where K>2, then we can use the K bits to encode the attribute values. The classes are also encoded in the same manner.
Points to remember −
Based on the notion of the survival of the fittest, a new population is formed that consists of the fittest rules in the current population and offspring values of these rules as well.
Based on the notion of the survival of the fittest, a new population is formed that consists of the fittest rules in the current population and offspring values of these rules as well.
The fitness of a rule is assessed by its classification accuracy on a set of training samples.
The fitness of a rule is assessed by its classification accuracy on a set of training samples.
The genetic operators such as crossover and mutation are applied to create offspring.
The genetic operators such as crossover and mutation are applied to create offspring.
In crossover, the substring from pair of rules are swapped to form a new pair of rules.
In crossover, the substring from pair of rules are swapped to form a new pair of rules.
In mutation, randomly selected bits in a rule's string are inverted.
In mutation, randomly selected bits in a rule's string are inverted.
We can use the rough set approach to discover structural relationship within imprecise and noisy data.
Note − This approach can only be applied on discrete-valued attributes. Therefore, continuous-valued attributes must be discretized before its use.
The Rough Set Theory is based on the establishment of equivalence classes within the given training data. The tuples that forms the equivalence class are indiscernible. It means the samples are identical with respect to the attributes describing the data.
There are some classes in the given real world data, which cannot be distinguished in terms of available attributes. We can use the rough sets to roughly define such classes.
For a given class C, the rough set definition is approximated by two sets as follows −
Lower Approximation of C − The lower approximation of C consists of all the data tuples, that based on the knowledge of the attribute, are certain to belong to class C.
Lower Approximation of C − The lower approximation of C consists of all the data tuples, that based on the knowledge of the attribute, are certain to belong to class C.
Upper Approximation of C − The upper approximation of C consists of all the tuples, that based on the knowledge of attributes, cannot be described as not belonging to C.
Upper Approximation of C − The upper approximation of C consists of all the tuples, that based on the knowledge of attributes, cannot be described as not belonging to C.
The following diagram shows the Upper and Lower Approximation of class C −
Fuzzy Set Theory is also called Possibility Theory. This theory was proposed by Lotfi Zadeh in 1965 as an alternative the two-value logic and probability theory. This theory allows us to work at a high level of abstraction. It also provides us the means for dealing with imprecise measurement of data.
The fuzzy set theory also allows us to deal with vague or inexact facts. For example, being a member of a set of high incomes is in exact (e.g. if $50,000 is high then what about $49,000 and $48,000). Unlike the traditional CRISP set where the element either belong to S or its complement but in fuzzy set theory the element can belong to more than one fuzzy set.
For example, the income value $49,000 belongs to both the medium and high fuzzy sets but to differing degrees. Fuzzy set notation for this income value is as follows −
mmedium_income($49k)=0.15 and mhigh_income($49k)=0.96
where ‘m’ is the membership function that operates on the fuzzy sets of medium_income and high_income respectively. This notation can be shown diagrammatically as follows −
42 Lectures
1.5 hours
Ravi Kiran
141 Lectures
13 hours
Arnab Chakraborty
26 Lectures
8.5 hours
Parth Panjabi
65 Lectures
6 hours
Arnab Chakraborty
75 Lectures
13 hours
Eduonix Learning Solutions
64 Lectures
10.5 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2232,
"s": 2110,
"text": "Here we will discuss other classification methods such as Genetic Algorithms, Rough Set Approach, and Fuzzy Set Approach."
},
{
"code": null,
"e": 2478,
"s": 2232,
"text": "The idea of genetic algorithm is derived from natural evolution. In genetic algorithm, first of all, the initial population is created. This initial population consists of randomly generated rules. We can represent each rule by a string of bits."
},
{
"code": null,
"e": 2655,
"s": 2478,
"text": "For example, in a given training set, the samples are described by two Boolean attributes such as A1 and A2. And this given training set contains two classes such as C1 and C2."
},
{
"code": null,
"e": 2825,
"s": 2655,
"text": "We can encode the rule IF A1 AND NOT A2 THEN C2 into a bit string 100. In this bit representation, the two leftmost bits represent the attribute A1 and A2, respectively."
},
{
"code": null,
"e": 2896,
"s": 2825,
"text": "Likewise, the rule IF NOT A1 AND NOT A2 THEN C1 can be encoded as 001."
},
{
"code": null,
"e": 3052,
"s": 2896,
"text": "Note − If the attribute has K values where K>2, then we can use the K bits to encode the attribute values. The classes are also encoded in the same manner."
},
{
"code": null,
"e": 3073,
"s": 3052,
"text": "Points to remember −"
},
{
"code": null,
"e": 3258,
"s": 3073,
"text": "Based on the notion of the survival of the fittest, a new population is formed that consists of the fittest rules in the current population and offspring values of these rules as well."
},
{
"code": null,
"e": 3443,
"s": 3258,
"text": "Based on the notion of the survival of the fittest, a new population is formed that consists of the fittest rules in the current population and offspring values of these rules as well."
},
{
"code": null,
"e": 3538,
"s": 3443,
"text": "The fitness of a rule is assessed by its classification accuracy on a set of training samples."
},
{
"code": null,
"e": 3633,
"s": 3538,
"text": "The fitness of a rule is assessed by its classification accuracy on a set of training samples."
},
{
"code": null,
"e": 3719,
"s": 3633,
"text": "The genetic operators such as crossover and mutation are applied to create offspring."
},
{
"code": null,
"e": 3805,
"s": 3719,
"text": "The genetic operators such as crossover and mutation are applied to create offspring."
},
{
"code": null,
"e": 3893,
"s": 3805,
"text": "In crossover, the substring from pair of rules are swapped to form a new pair of rules."
},
{
"code": null,
"e": 3981,
"s": 3893,
"text": "In crossover, the substring from pair of rules are swapped to form a new pair of rules."
},
{
"code": null,
"e": 4050,
"s": 3981,
"text": "In mutation, randomly selected bits in a rule's string are inverted."
},
{
"code": null,
"e": 4119,
"s": 4050,
"text": "In mutation, randomly selected bits in a rule's string are inverted."
},
{
"code": null,
"e": 4222,
"s": 4119,
"text": "We can use the rough set approach to discover structural relationship within imprecise and noisy data."
},
{
"code": null,
"e": 4370,
"s": 4222,
"text": "Note − This approach can only be applied on discrete-valued attributes. Therefore, continuous-valued attributes must be discretized before its use."
},
{
"code": null,
"e": 4626,
"s": 4370,
"text": "The Rough Set Theory is based on the establishment of equivalence classes within the given training data. The tuples that forms the equivalence class are indiscernible. It means the samples are identical with respect to the attributes describing the data."
},
{
"code": null,
"e": 4801,
"s": 4626,
"text": "There are some classes in the given real world data, which cannot be distinguished in terms of available attributes. We can use the rough sets to roughly define such classes."
},
{
"code": null,
"e": 4888,
"s": 4801,
"text": "For a given class C, the rough set definition is approximated by two sets as follows −"
},
{
"code": null,
"e": 5057,
"s": 4888,
"text": "Lower Approximation of C − The lower approximation of C consists of all the data tuples, that based on the knowledge of the attribute, are certain to belong to class C."
},
{
"code": null,
"e": 5226,
"s": 5057,
"text": "Lower Approximation of C − The lower approximation of C consists of all the data tuples, that based on the knowledge of the attribute, are certain to belong to class C."
},
{
"code": null,
"e": 5396,
"s": 5226,
"text": "Upper Approximation of C − The upper approximation of C consists of all the tuples, that based on the knowledge of attributes, cannot be described as not belonging to C."
},
{
"code": null,
"e": 5566,
"s": 5396,
"text": "Upper Approximation of C − The upper approximation of C consists of all the tuples, that based on the knowledge of attributes, cannot be described as not belonging to C."
},
{
"code": null,
"e": 5641,
"s": 5566,
"text": "The following diagram shows the Upper and Lower Approximation of class C −"
},
{
"code": null,
"e": 5943,
"s": 5641,
"text": "Fuzzy Set Theory is also called Possibility Theory. This theory was proposed by Lotfi Zadeh in 1965 as an alternative the two-value logic and probability theory. This theory allows us to work at a high level of abstraction. It also provides us the means for dealing with imprecise measurement of data."
},
{
"code": null,
"e": 6307,
"s": 5943,
"text": "The fuzzy set theory also allows us to deal with vague or inexact facts. For example, being a member of a set of high incomes is in exact (e.g. if $50,000 is high then what about $49,000 and $48,000). Unlike the traditional CRISP set where the element either belong to S or its complement but in fuzzy set theory the element can belong to more than one fuzzy set."
},
{
"code": null,
"e": 6475,
"s": 6307,
"text": "For example, the income value $49,000 belongs to both the medium and high fuzzy sets but to differing degrees. Fuzzy set notation for this income value is as follows −"
},
{
"code": null,
"e": 6530,
"s": 6475,
"text": "mmedium_income($49k)=0.15 and mhigh_income($49k)=0.96\n"
},
{
"code": null,
"e": 6703,
"s": 6530,
"text": "where ‘m’ is the membership function that operates on the fuzzy sets of medium_income and high_income respectively. This notation can be shown diagrammatically as follows −"
},
{
"code": null,
"e": 6738,
"s": 6703,
"text": "\n 42 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6750,
"s": 6738,
"text": " Ravi Kiran"
},
{
"code": null,
"e": 6785,
"s": 6750,
"text": "\n 141 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6804,
"s": 6785,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6839,
"s": 6804,
"text": "\n 26 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6854,
"s": 6839,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 6887,
"s": 6854,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6906,
"s": 6887,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6940,
"s": 6906,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6968,
"s": 6940,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7004,
"s": 6968,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 7032,
"s": 7004,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7039,
"s": 7032,
"text": " Print"
},
{
"code": null,
"e": 7050,
"s": 7039,
"text": " Add Notes"
}
] |
Shortest path in a Binary Maze - GeeksforGeeks | 09 Jun, 2021
Given a MxN matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.Expected time complexity is O(MN).For example –
Input:
mat[ROW][COL] = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
{1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }};
Source = {0, 0};
Destination = {3, 4};
Output:
Shortest Path is 11
The idea is inspired from Lee algorithm and uses BFS.
We start from the source cell and calls BFS procedure.We maintain a queue to store the coordinates of the matrix and initialize it with the source cell.We also maintain a Boolean array visited of same size as our input matrix and initialize all its elements to false.We LOOP till queue is not emptyDequeue front cell from the queueReturn if the destination coordinates have reached.For each of its four adjacent cells, if the value is 1 and they are not visited yet, we enqueue it in the queue and also mark them as visited.
We start from the source cell and calls BFS procedure.
We maintain a queue to store the coordinates of the matrix and initialize it with the source cell.
We also maintain a Boolean array visited of same size as our input matrix and initialize all its elements to false.We LOOP till queue is not emptyDequeue front cell from the queueReturn if the destination coordinates have reached.For each of its four adjacent cells, if the value is 1 and they are not visited yet, we enqueue it in the queue and also mark them as visited.
We LOOP till queue is not emptyDequeue front cell from the queueReturn if the destination coordinates have reached.For each of its four adjacent cells, if the value is 1 and they are not visited yet, we enqueue it in the queue and also mark them as visited.
We LOOP till queue is not empty
Dequeue front cell from the queue
Return if the destination coordinates have reached.
For each of its four adjacent cells, if the value is 1 and they are not visited yet, we enqueue it in the queue and also mark them as visited.
Note that BFS works here because it doesn’t consider a single path at once. It considers all the paths starting from the source and moves ahead one unit in all those paths at the same time which makes sure that the first time when the destination is visited, it is the shortest path.Below is the implementation of the idea –
C++
Java
Python
C#
// C++ program to find the shortest path between// a given source cell to a destination cell.#include <bits/stdc++.h>using namespace std;#define ROW 9#define COL 10 //To store matrix cell coordinatesstruct Point{ int x; int y;}; // A Data Structure for queue used in BFSstruct queueNode{ Point pt; // The coordinates of a cell int dist; // cell's distance of from the source}; // check whether given cell (row, col) is a valid// cell or not.bool isValid(int row, int col){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL);} // These arrays are used to get row and column// numbers of 4 neighbours of a given cellint rowNum[] = {-1, 0, 0, 1};int colNum[] = {0, -1, 1, 0}; // function to find the shortest path between// a given source cell to a destination cell.int BFS(int mat[][COL], Point src, Point dest){ // check source and destination cell // of the matrix have value 1 if (!mat[src.x][src.y] || !mat[dest.x][dest.y]) return -1; bool visited[ROW][COL]; memset(visited, false, sizeof visited); // Mark the source cell as visited visited[src.x][src.y] = true; // Create a queue for BFS queue<queueNode> q; // Distance of source cell is 0 queueNode s = {src, 0}; q.push(s); // Enqueue source cell // Do a BFS starting from source cell while (!q.empty()) { queueNode curr = q.front(); Point pt = curr.pt; // If we have reached the destination cell, // we are done if (pt.x == dest.x && pt.y == dest.y) return curr.dist; // Otherwise dequeue the front // cell in the queue // and enqueue its adjacent cells q.pop(); for (int i = 0; i < 4; i++) { int row = pt.x + rowNum[i]; int col = pt.y + colNum[i]; // if adjacent cell is valid, has path and // not visited yet, enqueue it. if (isValid(row, col) && mat[row][col] && !visited[row][col]) { // mark cell as visited and enqueue it visited[row][col] = true; queueNode Adjcell = { {row, col}, curr.dist + 1 }; q.push(Adjcell); } } } // Return -1 if destination cannot be reached return -1;} // Driver program to test above functionint main(){ int mat[ROW][COL] = { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 } }; Point source = {0, 0}; Point dest = {3, 4}; int dist = BFS(mat, source, dest); if (dist != -1) cout << "Shortest Path is " << dist ; else cout << "Shortest Path doesn't exist"; return 0;}
// Java program to find the shortest// path between a given source cell// to a destination cell.import java.util.*; class GFG{static int ROW = 9;static int COL = 10; // To store matrix cell coordinatesstatic class Point{ int x; int y; public Point(int x, int y) { this.x = x; this.y = y; }}; // A Data Structure for queue used in BFSstatic class queueNode{ Point pt; // The coordinates of a cell int dist; // cell's distance of from the source public queueNode(Point pt, int dist) { this.pt = pt; this.dist = dist; }}; // check whether given cell (row, col)// is a valid cell or not.static boolean isValid(int row, int col){ // return true if row number and // column number is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL);} // These arrays are used to get row and column// numbers of 4 neighbours of a given cellstatic int rowNum[] = {-1, 0, 0, 1};static int colNum[] = {0, -1, 1, 0}; // function to find the shortest path between// a given source cell to a destination cell.static int BFS(int mat[][], Point src, Point dest){ // check source and destination cell // of the matrix have value 1 if (mat[src.x][src.y] != 1 || mat[dest.x][dest.y] != 1) return -1; boolean [][]visited = new boolean[ROW][COL]; // Mark the source cell as visited visited[src.x][src.y] = true; // Create a queue for BFS Queue<queueNode> q = new LinkedList<>(); // Distance of source cell is 0 queueNode s = new queueNode(src, 0); q.add(s); // Enqueue source cell // Do a BFS starting from source cell while (!q.isEmpty()) { queueNode curr = q.peek(); Point pt = curr.pt; // If we have reached the destination cell, // we are done if (pt.x == dest.x && pt.y == dest.y) return curr.dist; // Otherwise dequeue the front cell // in the queue and enqueue // its adjacent cells q.remove(); for (int i = 0; i < 4; i++) { int row = pt.x + rowNum[i]; int col = pt.y + colNum[i]; // if adjacent cell is valid, has path // and not visited yet, enqueue it. if (isValid(row, col) && mat[row][col] == 1 && !visited[row][col]) { // mark cell as visited and enqueue it visited[row][col] = true; queueNode Adjcell = new queueNode (new Point(row, col), curr.dist + 1 ); q.add(Adjcell); } } } // Return -1 if destination cannot be reached return -1;} // Driver Codepublic static void main(String[] args){ int mat[][] = {{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }}; Point source = new Point(0, 0); Point dest = new Point(3, 4); int dist = BFS(mat, source, dest); if (dist != -1) System.out.println("Shortest Path is " + dist); else System.out.println("Shortest Path doesn't exist"); }} // This code is contributed by PrinciRaj1992
# Python program to find the shortest# path between a given source cell# to a destination cell. from collections import dequeROW = 9COL = 10 # To store matrix cell coordinatesclass Point: def __init__(self,x: int, y: int): self.x = x self.y = y # A data structure for queue used in BFSclass queueNode: def __init__(self,pt: Point, dist: int): self.pt = pt # The coordinates of the cell self.dist = dist # Cell's distance from the source # Check whether given cell(row,col)# is a valid cell or notdef isValid(row: int, col: int): return (row >= 0) and (row < ROW) and (col >= 0) and (col < COL) # These arrays are used to get row and column# numbers of 4 neighbours of a given cellrowNum = [-1, 0, 0, 1]colNum = [0, -1, 1, 0] # Function to find the shortest path between# a given source cell to a destination cell.def BFS(mat, src: Point, dest: Point): # check source and destination cell # of the matrix have value 1 if mat[src.x][src.y]!=1 or mat[dest.x][dest.y]!=1: return -1 visited = [[False for i in range(COL)] for j in range(ROW)] # Mark the source cell as visited visited[src.x][src.y] = True # Create a queue for BFS q = deque() # Distance of source cell is 0 s = queueNode(src,0) q.append(s) # Enqueue source cell # Do a BFS starting from source cell while q: curr = q.popleft() # Dequeue the front cell # If we have reached the destination cell, # we are done pt = curr.pt if pt.x == dest.x and pt.y == dest.y: return curr.dist # Otherwise enqueue its adjacent cells for i in range(4): row = pt.x + rowNum[i] col = pt.y + colNum[i] # if adjacent cell is valid, has path # and not visited yet, enqueue it. if (isValid(row,col) and mat[row][col] == 1 and not visited[row][col]): visited[row][col] = True Adjcell = queueNode(Point(row,col), curr.dist+1) q.append(Adjcell) # Return -1 if destination cannot be reached return -1 # Driver codedef main(): mat = [[ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 ], [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]] source = Point(0,0) dest = Point(3,4) dist = BFS(mat,source,dest) if dist!=-1: print("Shortest Path is",dist) else: print("Shortest Path doesn't exist")main() # This code is contributed by stutipathak31jan
// C# program to find the shortest// path between a given source cell// to a destination cell.using System;using System.Collections.Generic; class GFG{static int ROW = 9;static int COL = 10; // To store matrix cell coordinatespublic class Point{ public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; }}; // A Data Structure for queue used in BFSpublic class queueNode{ // The coordinates of a cell public Point pt; // cell's distance of from the source public int dist; public queueNode(Point pt, int dist) { this.pt = pt; this.dist = dist; }}; // check whether given cell (row, col)// is a valid cell or not.static bool isValid(int row, int col){ // return true if row number and // column number is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL);} // These arrays are used to get row and column// numbers of 4 neighbours of a given cellstatic int []rowNum = {-1, 0, 0, 1};static int []colNum = {0, -1, 1, 0}; // function to find the shortest path between// a given source cell to a destination cell.static int BFS(int [,]mat, Point src, Point dest){ // check source and destination cell // of the matrix have value 1 if (mat[src.x, src.y] != 1 || mat[dest.x, dest.y] != 1) return -1; bool [,]visited = new bool[ROW, COL]; // Mark the source cell as visited visited[src.x, src.y] = true; // Create a queue for BFS Queue<queueNode> q = new Queue<queueNode>(); // Distance of source cell is 0 queueNode s = new queueNode(src, 0); q.Enqueue(s); // Enqueue source cell // Do a BFS starting from source cell while (q.Count != 0) { queueNode curr = q.Peek(); Point pt = curr.pt; // If we have reached the destination cell, // we are done if (pt.x == dest.x && pt.y == dest.y) return curr.dist; // Otherwise dequeue the front cell // in the queue and enqueue // its adjacent cells q.Dequeue(); for (int i = 0; i < 4; i++) { int row = pt.x + rowNum[i]; int col = pt.y + colNum[i]; // if adjacent cell is valid, has path // and not visited yet, enqueue it. if (isValid(row, col) && mat[row, col] == 1 && !visited[row, col]) { // mark cell as visited and enqueue it visited[row, col] = true; queueNode Adjcell = new queueNode (new Point(row, col), curr.dist + 1 ); q.Enqueue(Adjcell); } } } // Return -1 if destination cannot be reached return -1;} // Driver Codepublic static void Main(String[] args){ int [,]mat = {{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }}; Point source = new Point(0, 0); Point dest = new Point(3, 4); int dist = BFS(mat, source, dest); if (dist != -1) Console.WriteLine("Shortest Path is " + dist); else Console.WriteLine("Shortest Path doesn't exist"); }} // This code is contributed by PrinciRaj1992
Output :
Shortest Path is 11
This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Chinmay Singh
dgr8akki
princiraj1992
stutipathak31jan
ishitaaggarwal8
varshagumber28
Amazon
BFS
DFS
Google
Samsung
Shortest Path
Zoho
Graph
Mathematical
Matrix
Zoho
Amazon
Samsung
Google
Mathematical
DFS
Matrix
Graph
Shortest Path
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Detect Cycle in a Directed Graph
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 24493,
"s": 24465,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 24748,
"s": 24493,
"text": "Given a MxN matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.Expected time complexity is O(MN).For example – "
},
{
"code": null,
"e": 25284,
"s": 24748,
"text": "Input:\nmat[ROW][COL] = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },\n {1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },\n {1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },\n {0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },\n {1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },\n {1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },\n {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },\n {1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },\n {1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }};\nSource = {0, 0};\nDestination = {3, 4};\n\nOutput:\nShortest Path is 11 "
},
{
"code": null,
"e": 25340,
"s": 25284,
"text": "The idea is inspired from Lee algorithm and uses BFS. "
},
{
"code": null,
"e": 25865,
"s": 25340,
"text": "We start from the source cell and calls BFS procedure.We maintain a queue to store the coordinates of the matrix and initialize it with the source cell.We also maintain a Boolean array visited of same size as our input matrix and initialize all its elements to false.We LOOP till queue is not emptyDequeue front cell from the queueReturn if the destination coordinates have reached.For each of its four adjacent cells, if the value is 1 and they are not visited yet, we enqueue it in the queue and also mark them as visited."
},
{
"code": null,
"e": 25920,
"s": 25865,
"text": "We start from the source cell and calls BFS procedure."
},
{
"code": null,
"e": 26019,
"s": 25920,
"text": "We maintain a queue to store the coordinates of the matrix and initialize it with the source cell."
},
{
"code": null,
"e": 26392,
"s": 26019,
"text": "We also maintain a Boolean array visited of same size as our input matrix and initialize all its elements to false.We LOOP till queue is not emptyDequeue front cell from the queueReturn if the destination coordinates have reached.For each of its four adjacent cells, if the value is 1 and they are not visited yet, we enqueue it in the queue and also mark them as visited."
},
{
"code": null,
"e": 26650,
"s": 26392,
"text": "We LOOP till queue is not emptyDequeue front cell from the queueReturn if the destination coordinates have reached.For each of its four adjacent cells, if the value is 1 and they are not visited yet, we enqueue it in the queue and also mark them as visited."
},
{
"code": null,
"e": 26682,
"s": 26650,
"text": "We LOOP till queue is not empty"
},
{
"code": null,
"e": 26716,
"s": 26682,
"text": "Dequeue front cell from the queue"
},
{
"code": null,
"e": 26768,
"s": 26716,
"text": "Return if the destination coordinates have reached."
},
{
"code": null,
"e": 26911,
"s": 26768,
"text": "For each of its four adjacent cells, if the value is 1 and they are not visited yet, we enqueue it in the queue and also mark them as visited."
},
{
"code": null,
"e": 27238,
"s": 26911,
"text": "Note that BFS works here because it doesn’t consider a single path at once. It considers all the paths starting from the source and moves ahead one unit in all those paths at the same time which makes sure that the first time when the destination is visited, it is the shortest path.Below is the implementation of the idea – "
},
{
"code": null,
"e": 27242,
"s": 27238,
"text": "C++"
},
{
"code": null,
"e": 27247,
"s": 27242,
"text": "Java"
},
{
"code": null,
"e": 27254,
"s": 27247,
"text": "Python"
},
{
"code": null,
"e": 27257,
"s": 27254,
"text": "C#"
},
{
"code": "// C++ program to find the shortest path between// a given source cell to a destination cell.#include <bits/stdc++.h>using namespace std;#define ROW 9#define COL 10 //To store matrix cell coordinatesstruct Point{ int x; int y;}; // A Data Structure for queue used in BFSstruct queueNode{ Point pt; // The coordinates of a cell int dist; // cell's distance of from the source}; // check whether given cell (row, col) is a valid// cell or not.bool isValid(int row, int col){ // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL);} // These arrays are used to get row and column// numbers of 4 neighbours of a given cellint rowNum[] = {-1, 0, 0, 1};int colNum[] = {0, -1, 1, 0}; // function to find the shortest path between// a given source cell to a destination cell.int BFS(int mat[][COL], Point src, Point dest){ // check source and destination cell // of the matrix have value 1 if (!mat[src.x][src.y] || !mat[dest.x][dest.y]) return -1; bool visited[ROW][COL]; memset(visited, false, sizeof visited); // Mark the source cell as visited visited[src.x][src.y] = true; // Create a queue for BFS queue<queueNode> q; // Distance of source cell is 0 queueNode s = {src, 0}; q.push(s); // Enqueue source cell // Do a BFS starting from source cell while (!q.empty()) { queueNode curr = q.front(); Point pt = curr.pt; // If we have reached the destination cell, // we are done if (pt.x == dest.x && pt.y == dest.y) return curr.dist; // Otherwise dequeue the front // cell in the queue // and enqueue its adjacent cells q.pop(); for (int i = 0; i < 4; i++) { int row = pt.x + rowNum[i]; int col = pt.y + colNum[i]; // if adjacent cell is valid, has path and // not visited yet, enqueue it. if (isValid(row, col) && mat[row][col] && !visited[row][col]) { // mark cell as visited and enqueue it visited[row][col] = true; queueNode Adjcell = { {row, col}, curr.dist + 1 }; q.push(Adjcell); } } } // Return -1 if destination cannot be reached return -1;} // Driver program to test above functionint main(){ int mat[ROW][COL] = { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 } }; Point source = {0, 0}; Point dest = {3, 4}; int dist = BFS(mat, source, dest); if (dist != -1) cout << \"Shortest Path is \" << dist ; else cout << \"Shortest Path doesn't exist\"; return 0;}",
"e": 30357,
"s": 27257,
"text": null
},
{
"code": "// Java program to find the shortest// path between a given source cell// to a destination cell.import java.util.*; class GFG{static int ROW = 9;static int COL = 10; // To store matrix cell coordinatesstatic class Point{ int x; int y; public Point(int x, int y) { this.x = x; this.y = y; }}; // A Data Structure for queue used in BFSstatic class queueNode{ Point pt; // The coordinates of a cell int dist; // cell's distance of from the source public queueNode(Point pt, int dist) { this.pt = pt; this.dist = dist; }}; // check whether given cell (row, col)// is a valid cell or not.static boolean isValid(int row, int col){ // return true if row number and // column number is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL);} // These arrays are used to get row and column// numbers of 4 neighbours of a given cellstatic int rowNum[] = {-1, 0, 0, 1};static int colNum[] = {0, -1, 1, 0}; // function to find the shortest path between// a given source cell to a destination cell.static int BFS(int mat[][], Point src, Point dest){ // check source and destination cell // of the matrix have value 1 if (mat[src.x][src.y] != 1 || mat[dest.x][dest.y] != 1) return -1; boolean [][]visited = new boolean[ROW][COL]; // Mark the source cell as visited visited[src.x][src.y] = true; // Create a queue for BFS Queue<queueNode> q = new LinkedList<>(); // Distance of source cell is 0 queueNode s = new queueNode(src, 0); q.add(s); // Enqueue source cell // Do a BFS starting from source cell while (!q.isEmpty()) { queueNode curr = q.peek(); Point pt = curr.pt; // If we have reached the destination cell, // we are done if (pt.x == dest.x && pt.y == dest.y) return curr.dist; // Otherwise dequeue the front cell // in the queue and enqueue // its adjacent cells q.remove(); for (int i = 0; i < 4; i++) { int row = pt.x + rowNum[i]; int col = pt.y + colNum[i]; // if adjacent cell is valid, has path // and not visited yet, enqueue it. if (isValid(row, col) && mat[row][col] == 1 && !visited[row][col]) { // mark cell as visited and enqueue it visited[row][col] = true; queueNode Adjcell = new queueNode (new Point(row, col), curr.dist + 1 ); q.add(Adjcell); } } } // Return -1 if destination cannot be reached return -1;} // Driver Codepublic static void main(String[] args){ int mat[][] = {{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }}; Point source = new Point(0, 0); Point dest = new Point(3, 4); int dist = BFS(mat, source, dest); if (dist != -1) System.out.println(\"Shortest Path is \" + dist); else System.out.println(\"Shortest Path doesn't exist\"); }} // This code is contributed by PrinciRaj1992",
"e": 33949,
"s": 30357,
"text": null
},
{
"code": "# Python program to find the shortest# path between a given source cell# to a destination cell. from collections import dequeROW = 9COL = 10 # To store matrix cell coordinatesclass Point: def __init__(self,x: int, y: int): self.x = x self.y = y # A data structure for queue used in BFSclass queueNode: def __init__(self,pt: Point, dist: int): self.pt = pt # The coordinates of the cell self.dist = dist # Cell's distance from the source # Check whether given cell(row,col)# is a valid cell or notdef isValid(row: int, col: int): return (row >= 0) and (row < ROW) and (col >= 0) and (col < COL) # These arrays are used to get row and column# numbers of 4 neighbours of a given cellrowNum = [-1, 0, 0, 1]colNum = [0, -1, 1, 0] # Function to find the shortest path between# a given source cell to a destination cell.def BFS(mat, src: Point, dest: Point): # check source and destination cell # of the matrix have value 1 if mat[src.x][src.y]!=1 or mat[dest.x][dest.y]!=1: return -1 visited = [[False for i in range(COL)] for j in range(ROW)] # Mark the source cell as visited visited[src.x][src.y] = True # Create a queue for BFS q = deque() # Distance of source cell is 0 s = queueNode(src,0) q.append(s) # Enqueue source cell # Do a BFS starting from source cell while q: curr = q.popleft() # Dequeue the front cell # If we have reached the destination cell, # we are done pt = curr.pt if pt.x == dest.x and pt.y == dest.y: return curr.dist # Otherwise enqueue its adjacent cells for i in range(4): row = pt.x + rowNum[i] col = pt.y + colNum[i] # if adjacent cell is valid, has path # and not visited yet, enqueue it. if (isValid(row,col) and mat[row][col] == 1 and not visited[row][col]): visited[row][col] = True Adjcell = queueNode(Point(row,col), curr.dist+1) q.append(Adjcell) # Return -1 if destination cannot be reached return -1 # Driver codedef main(): mat = [[ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ], [ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 ], [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ], [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]] source = Point(0,0) dest = Point(3,4) dist = BFS(mat,source,dest) if dist!=-1: print(\"Shortest Path is\",dist) else: print(\"Shortest Path doesn't exist\")main() # This code is contributed by stutipathak31jan",
"e": 36874,
"s": 33949,
"text": null
},
{
"code": "// C# program to find the shortest// path between a given source cell// to a destination cell.using System;using System.Collections.Generic; class GFG{static int ROW = 9;static int COL = 10; // To store matrix cell coordinatespublic class Point{ public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; }}; // A Data Structure for queue used in BFSpublic class queueNode{ // The coordinates of a cell public Point pt; // cell's distance of from the source public int dist; public queueNode(Point pt, int dist) { this.pt = pt; this.dist = dist; }}; // check whether given cell (row, col)// is a valid cell or not.static bool isValid(int row, int col){ // return true if row number and // column number is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL);} // These arrays are used to get row and column// numbers of 4 neighbours of a given cellstatic int []rowNum = {-1, 0, 0, 1};static int []colNum = {0, -1, 1, 0}; // function to find the shortest path between// a given source cell to a destination cell.static int BFS(int [,]mat, Point src, Point dest){ // check source and destination cell // of the matrix have value 1 if (mat[src.x, src.y] != 1 || mat[dest.x, dest.y] != 1) return -1; bool [,]visited = new bool[ROW, COL]; // Mark the source cell as visited visited[src.x, src.y] = true; // Create a queue for BFS Queue<queueNode> q = new Queue<queueNode>(); // Distance of source cell is 0 queueNode s = new queueNode(src, 0); q.Enqueue(s); // Enqueue source cell // Do a BFS starting from source cell while (q.Count != 0) { queueNode curr = q.Peek(); Point pt = curr.pt; // If we have reached the destination cell, // we are done if (pt.x == dest.x && pt.y == dest.y) return curr.dist; // Otherwise dequeue the front cell // in the queue and enqueue // its adjacent cells q.Dequeue(); for (int i = 0; i < 4; i++) { int row = pt.x + rowNum[i]; int col = pt.y + colNum[i]; // if adjacent cell is valid, has path // and not visited yet, enqueue it. if (isValid(row, col) && mat[row, col] == 1 && !visited[row, col]) { // mark cell as visited and enqueue it visited[row, col] = true; queueNode Adjcell = new queueNode (new Point(row, col), curr.dist + 1 ); q.Enqueue(Adjcell); } } } // Return -1 if destination cannot be reached return -1;} // Driver Codepublic static void Main(String[] args){ int [,]mat = {{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }}; Point source = new Point(0, 0); Point dest = new Point(3, 4); int dist = BFS(mat, source, dest); if (dist != -1) Console.WriteLine(\"Shortest Path is \" + dist); else Console.WriteLine(\"Shortest Path doesn't exist\"); }} // This code is contributed by PrinciRaj1992",
"e": 40511,
"s": 36874,
"text": null
},
{
"code": null,
"e": 40521,
"s": 40511,
"text": "Output : "
},
{
"code": null,
"e": 40541,
"s": 40521,
"text": "Shortest Path is 11"
},
{
"code": null,
"e": 40709,
"s": 40541,
"text": "This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 40723,
"s": 40709,
"text": "Chinmay Singh"
},
{
"code": null,
"e": 40732,
"s": 40723,
"text": "dgr8akki"
},
{
"code": null,
"e": 40746,
"s": 40732,
"text": "princiraj1992"
},
{
"code": null,
"e": 40763,
"s": 40746,
"text": "stutipathak31jan"
},
{
"code": null,
"e": 40779,
"s": 40763,
"text": "ishitaaggarwal8"
},
{
"code": null,
"e": 40794,
"s": 40779,
"text": "varshagumber28"
},
{
"code": null,
"e": 40801,
"s": 40794,
"text": "Amazon"
},
{
"code": null,
"e": 40805,
"s": 40801,
"text": "BFS"
},
{
"code": null,
"e": 40809,
"s": 40805,
"text": "DFS"
},
{
"code": null,
"e": 40816,
"s": 40809,
"text": "Google"
},
{
"code": null,
"e": 40824,
"s": 40816,
"text": "Samsung"
},
{
"code": null,
"e": 40838,
"s": 40824,
"text": "Shortest Path"
},
{
"code": null,
"e": 40843,
"s": 40838,
"text": "Zoho"
},
{
"code": null,
"e": 40849,
"s": 40843,
"text": "Graph"
},
{
"code": null,
"e": 40862,
"s": 40849,
"text": "Mathematical"
},
{
"code": null,
"e": 40869,
"s": 40862,
"text": "Matrix"
},
{
"code": null,
"e": 40874,
"s": 40869,
"text": "Zoho"
},
{
"code": null,
"e": 40881,
"s": 40874,
"text": "Amazon"
},
{
"code": null,
"e": 40889,
"s": 40881,
"text": "Samsung"
},
{
"code": null,
"e": 40896,
"s": 40889,
"text": "Google"
},
{
"code": null,
"e": 40909,
"s": 40896,
"text": "Mathematical"
},
{
"code": null,
"e": 40913,
"s": 40909,
"text": "DFS"
},
{
"code": null,
"e": 40920,
"s": 40913,
"text": "Matrix"
},
{
"code": null,
"e": 40926,
"s": 40920,
"text": "Graph"
},
{
"code": null,
"e": 40940,
"s": 40926,
"text": "Shortest Path"
},
{
"code": null,
"e": 40944,
"s": 40940,
"text": "BFS"
},
{
"code": null,
"e": 41042,
"s": 40944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41051,
"s": 41042,
"text": "Comments"
},
{
"code": null,
"e": 41064,
"s": 41051,
"text": "Old Comments"
},
{
"code": null,
"e": 41122,
"s": 41064,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 41142,
"s": 41122,
"text": "Topological Sorting"
},
{
"code": null,
"e": 41175,
"s": 41142,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 41206,
"s": 41175,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 41239,
"s": 41206,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 41299,
"s": 41239,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 41314,
"s": 41299,
"text": "C++ Data Types"
},
{
"code": null,
"e": 41357,
"s": 41314,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 41381,
"s": 41357,
"text": "Merge two sorted arrays"
}
] |
How can we add/insert a JRadioButton to a JTable cell in Java?
| A JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface. We can add or insert a radio button to a JTable cell by customizing the TableCellRenderer interface and the DefaultCellEditor class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class JTableRadioButtonTest extends JFrame {
private DefaultTableModel dtm;
private ButtonGroup bg;
private JTable table;
private JScrollPane jsp;
public JTableRadioButtonTest() {
setTitle("JTableRadioButton Test");
dtm = new DefaultTableModel();
dtm.setDataVector(new Object[][] {{"Course 1",new JRadioButton("Java")},{"Course 1",new JRadioButton("Python")}, {"Course 1",new JRadioButton("Scala")}, {"Course 2",new RadioButton("Selenium")}, {"Course 2",new JRadioButton("Java Script")}},new Object[] {"Course","Technology"});
table = new JTable(dtm) {
public void tableChanged(TableModelEvent tme) {
super.tableChanged(tme);
repaint();
}
};
bg = new ButtonGroup();
bg.add((JRadioButton)dtm.getValueAt(0,1));
bg.add((JRadioButton)dtm.getValueAt(1,1));
bg.add((JRadioButton)dtm.getValueAt(2,1));
bg.add((JRadioButton)dtm.getValueAt(3,1));
bg.add((JRadioButton)dtm.getValueAt(4,1));
table.getColumn("Technology").setCellRenderer(new RadioButtonRenderer());
table.getColumn("Technology").setCellEditor(new RadioButtonEditor(new JCheckBox()));
jsp = new JScrollPane(table);
add(jsp, BorderLayout.NORTH);
setSize(400, 275);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JTableRadioButtonTest();
}
}
class RadioButtonRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value==null) return null;
return (Component)value;
}
}
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
private JRadioButton button;
public RadioButtonEditor(JCheckBox checkBox) {
super(checkBox);
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value==null) return null;
button = (JRadioButton)value;
button.addItemListener(this);
return (Component)value;
}
public Object getCellEditorValue() {
button.removeItemListener(this);
return button;
}
public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
}
} | [
{
"code": null,
"e": 1469,
"s": 1062,
"text": "A JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface. We can add or insert a radio button to a JTable cell by customizing the TableCellRenderer interface and the DefaultCellEditor class."
},
{
"code": null,
"e": 4046,
"s": 1469,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.event.*;\nimport javax.swing.table.*;\npublic class JTableRadioButtonTest extends JFrame {\n private DefaultTableModel dtm;\n private ButtonGroup bg;\n private JTable table;\n private JScrollPane jsp;\n public JTableRadioButtonTest() {\n setTitle(\"JTableRadioButton Test\");\n dtm = new DefaultTableModel();\n dtm.setDataVector(new Object[][] {{\"Course 1\",new JRadioButton(\"Java\")},{\"Course 1\",new JRadioButton(\"Python\")}, {\"Course 1\",new JRadioButton(\"Scala\")}, {\"Course 2\",new RadioButton(\"Selenium\")}, {\"Course 2\",new JRadioButton(\"Java Script\")}},new Object[] {\"Course\",\"Technology\"});\n table = new JTable(dtm) {\n public void tableChanged(TableModelEvent tme) {\n super.tableChanged(tme);\n repaint();\n }\n };\n bg = new ButtonGroup();\n bg.add((JRadioButton)dtm.getValueAt(0,1));\n bg.add((JRadioButton)dtm.getValueAt(1,1));\n bg.add((JRadioButton)dtm.getValueAt(2,1));\n bg.add((JRadioButton)dtm.getValueAt(3,1));\n bg.add((JRadioButton)dtm.getValueAt(4,1));\n table.getColumn(\"Technology\").setCellRenderer(new RadioButtonRenderer());\n table.getColumn(\"Technology\").setCellEditor(new RadioButtonEditor(new JCheckBox()));\n jsp = new JScrollPane(table);\n add(jsp, BorderLayout.NORTH);\n setSize(400, 275);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JTableRadioButtonTest();\n }\n}\nclass RadioButtonRenderer implements TableCellRenderer {\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n if (value==null) return null;\n return (Component)value;\n }\n}\nclass RadioButtonEditor extends DefaultCellEditor implements ItemListener {\n private JRadioButton button;\n public RadioButtonEditor(JCheckBox checkBox) {\n super(checkBox);\n }\n public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {\n if (value==null) return null;\n button = (JRadioButton)value;\n button.addItemListener(this);\n return (Component)value;\n }\n public Object getCellEditorValue() {\n button.removeItemListener(this);\n return button;\n }\n public void itemStateChanged(ItemEvent e) {\n super.fireEditingStopped();\n }\n}"
}
] |
Generate Pencil Sketch from Photo in Python | by Abhijith Chandradas | Towards Data Science | OpenCV is the only library which is needed for the project. We will also be using matplotlib library for some visualizations which is discussed later.
import cv2import matplotlib.pyplot as plt
The following command can be used to read image using OpenCV.
img=cv2.imread("photo.jpg")
This command reads the file photo.jpg located in the current folder and stores in memory as img.
Displaying image using OpenCV is not very straight forward. The following command can be used to display the photo.
cv2.imshow(‘original image’,img)cv2.waitKey(0)cv2.destroyAllWindows()
When this command is executed, the below photo will open in a new window with title as ‘original image.’
It is not very convenient when new window opens up every time image has to be displayed and also the new window has to be deleted for further execution of code.To avoid these hassles, we can use pyplot module of matplotlib library to display the image in the Jupyter notebook itself.
The following command can be used to display cv2 image using matplotlib.
plt.imshow(img)plt.axis(False)plt.show()
We can observe that the image displayed using matplotlib is not consistent with the original image. This is because OpenCV uses BGR color scheme whereas matplotlib uses RGB colors scheme.We can convert BGR image to RGB by using any of the following methods.
plt.imshow(img[:,:,::-1])plt.axis(False)plt.show()
Using cvtColor method of OpenCV.
RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)plt.imshow(RGB_img)plt.axis(False)plt.show()
Converting a photo to pencil sketch involves the following steps:
Using cvtColor function of OpenCV.
grey_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Inverting the image can be done by either of the following methods
invert_img=cv2.bitwise_not(grey_img)#invert_img=255-grey_img
Apply Gaussian blur to the image. The second argument to the function is the kernel size, if should be a pair of odd numbers.Larger the kernel size, more blurred the image will be and it will lose its subtle features. For creating sketch, we require only the prominent features (contrasting edges) from the image. For small images, kernel size of (3,3), (5,5) etc. will be sufficient, whereas for larger images, small kernel size do not create any impact. Appropriate kernel size can be selected by trial and error method.
blur_img=cv2.GaussianBlur(invert_img, (111,111),0)
Repeat step 2
invblur_img=cv2.bitwise_not(blur_img)#invblur_img=255-blur_img
The sketch can be obtained by performing bit-wise division between the grayscale image and the inverted-blurred image.
sketch_img=cv2.divide(grey_img,invblur_img, scale=256.0)
Explaining bit-wise division in detail is beyond the scope of this article. You can access more information on image arithmetic here .
cv2.imwrite(‘sketch.png’, sketch_img)
cv2.imshow(‘sketch image’,sketch_img)cv2.waitKey(0)cv2.destroyAllWindows()
We can display the original image and sketch side by side for comparison.
plt.figure(figsize=(14,8))plt.subplot(1,2,1)plt.title('Original image', size=18)plt.imshow(RGB_img)plt.axis('off')plt.subplot(1,2,2)plt.title('Sketch', size=18)rgb_sketch=cv2.cvtColor(sketch_img, cv2.COLOR_BGR2RGB)plt.imshow(rgb_sketch)plt.axis('off')plt.show()
We can put everything together to create a sketch function:
Code for this tutorial can be accessed from my GitHub Repo.
If you prefer content in video format, you can check out this YouTube tutorial.
I hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other authors on variety of topics. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium. | [
{
"code": null,
"e": 323,
"s": 172,
"text": "OpenCV is the only library which is needed for the project. We will also be using matplotlib library for some visualizations which is discussed later."
},
{
"code": null,
"e": 365,
"s": 323,
"text": "import cv2import matplotlib.pyplot as plt"
},
{
"code": null,
"e": 427,
"s": 365,
"text": "The following command can be used to read image using OpenCV."
},
{
"code": null,
"e": 455,
"s": 427,
"text": "img=cv2.imread(\"photo.jpg\")"
},
{
"code": null,
"e": 552,
"s": 455,
"text": "This command reads the file photo.jpg located in the current folder and stores in memory as img."
},
{
"code": null,
"e": 668,
"s": 552,
"text": "Displaying image using OpenCV is not very straight forward. The following command can be used to display the photo."
},
{
"code": null,
"e": 738,
"s": 668,
"text": "cv2.imshow(‘original image’,img)cv2.waitKey(0)cv2.destroyAllWindows()"
},
{
"code": null,
"e": 843,
"s": 738,
"text": "When this command is executed, the below photo will open in a new window with title as ‘original image.’"
},
{
"code": null,
"e": 1127,
"s": 843,
"text": "It is not very convenient when new window opens up every time image has to be displayed and also the new window has to be deleted for further execution of code.To avoid these hassles, we can use pyplot module of matplotlib library to display the image in the Jupyter notebook itself."
},
{
"code": null,
"e": 1200,
"s": 1127,
"text": "The following command can be used to display cv2 image using matplotlib."
},
{
"code": null,
"e": 1241,
"s": 1200,
"text": "plt.imshow(img)plt.axis(False)plt.show()"
},
{
"code": null,
"e": 1499,
"s": 1241,
"text": "We can observe that the image displayed using matplotlib is not consistent with the original image. This is because OpenCV uses BGR color scheme whereas matplotlib uses RGB colors scheme.We can convert BGR image to RGB by using any of the following methods."
},
{
"code": null,
"e": 1550,
"s": 1499,
"text": "plt.imshow(img[:,:,::-1])plt.axis(False)plt.show()"
},
{
"code": null,
"e": 1583,
"s": 1550,
"text": "Using cvtColor method of OpenCV."
},
{
"code": null,
"e": 1674,
"s": 1583,
"text": "RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)plt.imshow(RGB_img)plt.axis(False)plt.show()"
},
{
"code": null,
"e": 1740,
"s": 1674,
"text": "Converting a photo to pencil sketch involves the following steps:"
},
{
"code": null,
"e": 1775,
"s": 1740,
"text": "Using cvtColor function of OpenCV."
},
{
"code": null,
"e": 1822,
"s": 1775,
"text": "grey_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)"
},
{
"code": null,
"e": 1889,
"s": 1822,
"text": "Inverting the image can be done by either of the following methods"
},
{
"code": null,
"e": 1950,
"s": 1889,
"text": "invert_img=cv2.bitwise_not(grey_img)#invert_img=255-grey_img"
},
{
"code": null,
"e": 2473,
"s": 1950,
"text": "Apply Gaussian blur to the image. The second argument to the function is the kernel size, if should be a pair of odd numbers.Larger the kernel size, more blurred the image will be and it will lose its subtle features. For creating sketch, we require only the prominent features (contrasting edges) from the image. For small images, kernel size of (3,3), (5,5) etc. will be sufficient, whereas for larger images, small kernel size do not create any impact. Appropriate kernel size can be selected by trial and error method."
},
{
"code": null,
"e": 2524,
"s": 2473,
"text": "blur_img=cv2.GaussianBlur(invert_img, (111,111),0)"
},
{
"code": null,
"e": 2538,
"s": 2524,
"text": "Repeat step 2"
},
{
"code": null,
"e": 2601,
"s": 2538,
"text": "invblur_img=cv2.bitwise_not(blur_img)#invblur_img=255-blur_img"
},
{
"code": null,
"e": 2720,
"s": 2601,
"text": "The sketch can be obtained by performing bit-wise division between the grayscale image and the inverted-blurred image."
},
{
"code": null,
"e": 2777,
"s": 2720,
"text": "sketch_img=cv2.divide(grey_img,invblur_img, scale=256.0)"
},
{
"code": null,
"e": 2912,
"s": 2777,
"text": "Explaining bit-wise division in detail is beyond the scope of this article. You can access more information on image arithmetic here ."
},
{
"code": null,
"e": 2951,
"s": 2912,
"text": " cv2.imwrite(‘sketch.png’, sketch_img)"
},
{
"code": null,
"e": 3026,
"s": 2951,
"text": "cv2.imshow(‘sketch image’,sketch_img)cv2.waitKey(0)cv2.destroyAllWindows()"
},
{
"code": null,
"e": 3100,
"s": 3026,
"text": "We can display the original image and sketch side by side for comparison."
},
{
"code": null,
"e": 3362,
"s": 3100,
"text": "plt.figure(figsize=(14,8))plt.subplot(1,2,1)plt.title('Original image', size=18)plt.imshow(RGB_img)plt.axis('off')plt.subplot(1,2,2)plt.title('Sketch', size=18)rgb_sketch=cv2.cvtColor(sketch_img, cv2.COLOR_BGR2RGB)plt.imshow(rgb_sketch)plt.axis('off')plt.show()"
},
{
"code": null,
"e": 3422,
"s": 3362,
"text": "We can put everything together to create a sketch function:"
},
{
"code": null,
"e": 3482,
"s": 3422,
"text": "Code for this tutorial can be accessed from my GitHub Repo."
},
{
"code": null,
"e": 3562,
"s": 3482,
"text": "If you prefer content in video format, you can check out this YouTube tutorial."
}
] |
Design and Analysis Binary Search | In this chapter, we will discuss another algorithm based on divide and conquer method.
Binary search can be performed on a sorted array. In this approach, the index of an element x is determined if the element belongs to the list of elements. If the array is unsorted, linear search is used to determine the position.
In this algorithm, we want to find whether element x belongs to a set of numbers stored in an array numbers[]. Where l and r represent the left and right index of a sub-array in which searching operation should be performed.
Algorithm: Binary-Search(numbers[], x, l, r)
if l = r then
return l
else
m := ⌊(l + r) / 2⌋
if x ≤ numbers[m] then
return Binary-Search(numbers[], x, l, m)
else
return Binary-Search(numbers[], x, m+1, r)
Linear search runs in O(n) time. Whereas binary search produces the result in O(log n) time
Let T(n) be the number of comparisons in worst-case in an array of n elements.
Hence,
T(n)={0ifn=1T(n2)+1otherwise
Using this recurrence relation T(n)=logn.
Therefore, binary search uses O(logn) time.
In this example, we are going to search element 63.
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2686,
"s": 2599,
"text": "In this chapter, we will discuss another algorithm based on divide and conquer method."
},
{
"code": null,
"e": 2917,
"s": 2686,
"text": "Binary search can be performed on a sorted array. In this approach, the index of an element x is determined if the element belongs to the list of elements. If the array is unsorted, linear search is used to determine the position."
},
{
"code": null,
"e": 3142,
"s": 2917,
"text": "In this algorithm, we want to find whether element x belongs to a set of numbers stored in an array numbers[]. Where l and r represent the left and right index of a sub-array in which searching operation should be performed."
},
{
"code": null,
"e": 3382,
"s": 3142,
"text": "Algorithm: Binary-Search(numbers[], x, l, r)\nif l = r then \n return l \nelse \n m := ⌊(l + r) / 2⌋ \n if x ≤ numbers[m] then \n return Binary-Search(numbers[], x, l, m) \n else \n return Binary-Search(numbers[], x, m+1, r) \n"
},
{
"code": null,
"e": 3474,
"s": 3382,
"text": "Linear search runs in O(n) time. Whereas binary search produces the result in O(log n) time"
},
{
"code": null,
"e": 3553,
"s": 3474,
"text": "Let T(n) be the number of comparisons in worst-case in an array of n elements."
},
{
"code": null,
"e": 3560,
"s": 3553,
"text": "Hence,"
},
{
"code": null,
"e": 3589,
"s": 3560,
"text": "T(n)={0ifn=1T(n2)+1otherwise"
},
{
"code": null,
"e": 3631,
"s": 3589,
"text": "Using this recurrence relation T(n)=logn."
},
{
"code": null,
"e": 3675,
"s": 3631,
"text": "Therefore, binary search uses O(logn) time."
},
{
"code": null,
"e": 3727,
"s": 3675,
"text": "In this example, we are going to search element 63."
},
{
"code": null,
"e": 3762,
"s": 3727,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3781,
"s": 3762,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3814,
"s": 3781,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3833,
"s": 3814,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3866,
"s": 3833,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3885,
"s": 3866,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3920,
"s": 3885,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3933,
"s": 3920,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 3965,
"s": 3933,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3978,
"s": 3965,
"text": " Zach Miller"
},
{
"code": null,
"e": 4011,
"s": 3978,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4025,
"s": 4011,
"text": " Sasha Miller"
},
{
"code": null,
"e": 4032,
"s": 4025,
"text": " Print"
},
{
"code": null,
"e": 4043,
"s": 4032,
"text": " Add Notes"
}
] |
Find Numbers with Even Number of Digits in Python | Suppose we have a list of numbers. We have to count the numbers that has even number of digit count. So if the array is like [12,345,2,6,7896], the output will be 2, as 12 and 7896 has even number of digits
To solve this, we will follow these steps −
Take the list and convert each integer into string
if the length of string is even, then increase count and finally return the count value
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def findNumbers(self, nums):
str_num = map(str, nums)
count = 0
for s in str_num:
if len(s) % 2 == 0:
count += 1
return count
ob1 = Solution()
print(ob1.findNumbers([12,345,2,6,7897]))
[12,345,2,6,7897]
2 | [
{
"code": null,
"e": 1269,
"s": 1062,
"text": "Suppose we have a list of numbers. We have to count the numbers that has even number of digit count. So if the array is like [12,345,2,6,7896], the output will be 2, as 12 and 7896 has even number of digits"
},
{
"code": null,
"e": 1313,
"s": 1269,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1364,
"s": 1313,
"text": "Take the list and convert each integer into string"
},
{
"code": null,
"e": 1452,
"s": 1364,
"text": "if the length of string is even, then increase count and finally return the count value"
},
{
"code": null,
"e": 1522,
"s": 1452,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1533,
"s": 1522,
"text": " Live Demo"
},
{
"code": null,
"e": 1790,
"s": 1533,
"text": "class Solution(object):\n def findNumbers(self, nums):\n str_num = map(str, nums)\n count = 0\n for s in str_num:\n if len(s) % 2 == 0:\n count += 1\n return count\nob1 = Solution()\nprint(ob1.findNumbers([12,345,2,6,7897]))"
},
{
"code": null,
"e": 1808,
"s": 1790,
"text": "[12,345,2,6,7897]"
},
{
"code": null,
"e": 1810,
"s": 1808,
"text": "2"
}
] |
Time Series - Auto Regression | For a stationary time series, an auto regression models sees the value of a variable at time ‘t’ as a linear function of values ‘p’ time steps preceding it. Mathematically it can be written as −
yt=C+φ1yt−1+φ2Yt−2+...+φpyt−p+εt
Where,‘p’ is the auto-regressive trend parameter
εt is white noise, and
yt−1,yt−2...yt−p denote the value of variable at previous time periods.
The value of p can be calibrated using various methods. One way of finding the apt value of ‘p’ is plotting the auto-correlation plot.
Note − We should separate the data into train and test at 8:2 ratio of total data available prior to doing any analysis on the data because test data is only to find out the accuracy of our model and assumption is, it is not available to us until after predictions have been made. In case of time series, sequence of data points is very essential so one should keep in mind not to lose the order during splitting of data.
An auto-correlation plot or a correlogram shows the relation of a variable with itself at prior time steps. It makes use of Pearson’s correlation and shows the correlations within 95% confidence interval. Let’s see how it looks like for ‘temperature’ variable of our data.
In [141]:
split = len(df) - int(0.2*len(df))
train, test = df['T'][0:split], df['T'][split:]
In [142]:
from statsmodels.graphics.tsaplots import plot_acf
plot_acf(train, lags = 100)
plt.show()
All the lag values lying outside the shaded blue region are assumed to have a csorrelation.
16 Lectures
2 hours
Malhar Lathkar
21 Lectures
2.5 hours
Sasha Miller
19 Lectures
1 hours
Sasha Miller
94 Lectures
13 hours
Abhishek And Pukhraj
12 Lectures
2 hours
Prof. Paul Cline, Ed.D
11 Lectures
1 hours
Prof. Paul Cline, Ed.D
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2336,
"s": 2141,
"text": "For a stationary time series, an auto regression models sees the value of a variable at time ‘t’ as a linear function of values ‘p’ time steps preceding it. Mathematically it can be written as −"
},
{
"code": null,
"e": 2369,
"s": 2336,
"text": "yt=C+φ1yt−1+φ2Yt−2+...+φpyt−p+εt"
},
{
"code": null,
"e": 2420,
"s": 2371,
"text": "Where,‘p’ is the auto-regressive trend parameter"
},
{
"code": null,
"e": 2443,
"s": 2420,
"text": "εt is white noise, and"
},
{
"code": null,
"e": 2515,
"s": 2443,
"text": "yt−1,yt−2...yt−p denote the value of variable at previous time periods."
},
{
"code": null,
"e": 2650,
"s": 2515,
"text": "The value of p can be calibrated using various methods. One way of finding the apt value of ‘p’ is plotting the auto-correlation plot."
},
{
"code": null,
"e": 3072,
"s": 2650,
"text": "Note − We should separate the data into train and test at 8:2 ratio of total data available prior to doing any analysis on the data because test data is only to find out the accuracy of our model and assumption is, it is not available to us until after predictions have been made. In case of time series, sequence of data points is very essential so one should keep in mind not to lose the order during splitting of data."
},
{
"code": null,
"e": 3345,
"s": 3072,
"text": "An auto-correlation plot or a correlogram shows the relation of a variable with itself at prior time steps. It makes use of Pearson’s correlation and shows the correlations within 95% confidence interval. Let’s see how it looks like for ‘temperature’ variable of our data."
},
{
"code": null,
"e": 3355,
"s": 3345,
"text": "In [141]:"
},
{
"code": null,
"e": 3439,
"s": 3355,
"text": "split = len(df) - int(0.2*len(df))\ntrain, test = df['T'][0:split], df['T'][split:]\n"
},
{
"code": null,
"e": 3449,
"s": 3439,
"text": "In [142]:"
},
{
"code": null,
"e": 3541,
"s": 3449,
"text": "from statsmodels.graphics.tsaplots import plot_acf\n\nplot_acf(train, lags = 100)\nplt.show()\n"
},
{
"code": null,
"e": 3633,
"s": 3541,
"text": "All the lag values lying outside the shaded blue region are assumed to have a csorrelation."
},
{
"code": null,
"e": 3666,
"s": 3633,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3682,
"s": 3666,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3717,
"s": 3682,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3731,
"s": 3717,
"text": " Sasha Miller"
},
{
"code": null,
"e": 3764,
"s": 3731,
"text": "\n 19 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3778,
"s": 3764,
"text": " Sasha Miller"
},
{
"code": null,
"e": 3812,
"s": 3778,
"text": "\n 94 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3834,
"s": 3812,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3867,
"s": 3834,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3891,
"s": 3867,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 3924,
"s": 3891,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3948,
"s": 3924,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 3955,
"s": 3948,
"text": " Print"
},
{
"code": null,
"e": 3966,
"s": 3955,
"text": " Add Notes"
}
] |
GATE | GATE-CS-2016 (Set 1) | Question 11 - GeeksforGeeks | 11 Oct, 2021
Let p, q, r, s represent the following propositions.
p: {8, 9, 10, 11, 12}
q: x is a composite number
r: x is a perfect square
s: x is a prime number
Note : This question was asked as Numerical Answer Type.(A) 8(B) 9(C) 11(D) 12Answer: (C)Explanation: (p ⇒ q) will give {8, 9, 10, 12}¬r will give {8, 10, 11, 12}¬s will give {8, 9, 10, 12}(¬r ∨ ¬s) will give {8, 9, 10, 11, 12}(p ⇒ q) ∧ (¬r ∨ ¬s) will give {8, 9, 10, 12}¬((p ⇒ q) ∧ (¬r ∨ ¬s)) will give 11.
Thus, C is the correct option.
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGate PYQ's on Propositional and First order Logic with Sakshi Singhal | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0033:10 / 41:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ID4_2ewAGE0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>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 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | Gate IT 2007 | Question 30
GATE | GATE CS 2021 | Set 1 | Question 47 | [
{
"code": null,
"e": 24610,
"s": 24582,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 24663,
"s": 24610,
"text": "Let p, q, r, s represent the following propositions."
},
{
"code": null,
"e": 24760,
"s": 24663,
"text": "p: {8, 9, 10, 11, 12}\nq: x is a composite number\nr: x is a perfect square\ns: x is a prime number"
},
{
"code": null,
"e": 25069,
"s": 24760,
"text": " Note : This question was asked as Numerical Answer Type.(A) 8(B) 9(C) 11(D) 12Answer: (C)Explanation: (p ⇒ q) will give {8, 9, 10, 12}¬r will give {8, 10, 11, 12}¬s will give {8, 9, 10, 12}(¬r ∨ ¬s) will give {8, 9, 10, 11, 12}(p ⇒ q) ∧ (¬r ∨ ¬s) will give {8, 9, 10, 12}¬((p ⇒ q) ∧ (¬r ∨ ¬s)) will give 11."
},
{
"code": null,
"e": 25100,
"s": 25069,
"text": "Thus, C is the correct option."
},
{
"code": null,
"e": 26019,
"s": 25100,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGate PYQ's on Propositional and First order Logic with Sakshi Singhal | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0033:10 / 41:23•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ID4_2ewAGE0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 26040,
"s": 26019,
"text": "GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 26066,
"s": 26040,
"text": "GATE-GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 26071,
"s": 26066,
"text": "GATE"
},
{
"code": null,
"e": 26169,
"s": 26071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26203,
"s": 26169,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 26237,
"s": 26203,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 26279,
"s": 26237,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26313,
"s": 26279,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 26346,
"s": 26313,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 26380,
"s": 26346,
"text": "GATE | GATE-CS-2000 | Question 43"
},
{
"code": null,
"e": 26422,
"s": 26380,
"text": "GATE | GATE-CS-2017 (Set 2) | Question 42"
},
{
"code": null,
"e": 26456,
"s": 26422,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 26490,
"s": 26456,
"text": "GATE | Gate IT 2007 | Question 30"
}
] |
File Searching using Python | Python can search for file names in a specified path of the OS. This can be done using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.
In the below example we are searching for a file named smpl.htm starting at the root directory named “D:\”. The os.walk() function searches the entire directory and each of its subdirectories to locate this file. As the result we see that the file is present in both the main directory and also in a subdirectory. We are running this program in a windows OS.
import os
def find_files(filename, search_path):
result = []
# Wlaking top-down from the root
for root, dir, files in os.walk(search_path):
if filename in files:
result.append(os.path.join(root, filename))
return result
print(find_files("smpl.htm","D:"))
Running the above code gives us the following result −
['D:TP\\smpl.htm', 'D:TP\\spyder_pythons\\smpl.htm'] | [
{
"code": null,
"e": 1297,
"s": 1062,
"text": "Python can search for file names in a specified path of the OS. This can be done using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames."
},
{
"code": null,
"e": 1656,
"s": 1297,
"text": "In the below example we are searching for a file named smpl.htm starting at the root directory named “D:\\”. The os.walk() function searches the entire directory and each of its subdirectories to locate this file. As the result we see that the file is present in both the main directory and also in a subdirectory. We are running this program in a windows OS."
},
{
"code": null,
"e": 1938,
"s": 1656,
"text": "import os\n\ndef find_files(filename, search_path):\n result = []\n\n# Wlaking top-down from the root\n for root, dir, files in os.walk(search_path):\n if filename in files:\n result.append(os.path.join(root, filename))\n return result\n\nprint(find_files(\"smpl.htm\",\"D:\"))"
},
{
"code": null,
"e": 1993,
"s": 1938,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2046,
"s": 1993,
"text": "['D:TP\\\\smpl.htm', 'D:TP\\\\spyder_pythons\\\\smpl.htm']"
}
] |
MongoDB query to remove a specific document | To remove a specific document, use remove() in MongoDB. Let us create a collection with documents −
> db.demo56.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e272e0bcfb11e5c34d89917")
}
> db.demo56.insertOne({"Name":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e272e10cfb11e5c34d89918")
}
> db.demo56.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e272e13cfb11e5c34d89919")
}
Display all documents from a collection with the help of find() method −
> db.demo56.find();
This will produce the following output −
{ "_id" : ObjectId("5e272e0bcfb11e5c34d89917"), "Name" : "Chris" }
{ "_id" : ObjectId("5e272e10cfb11e5c34d89918"), "Name" : "David" }
{ "_id" : ObjectId("5e272e13cfb11e5c34d89919"), "Name" : "Bob" }
Following is the query to remove a specific document −
> db.demo56.remove({_id:ObjectId("5e272e10cfb11e5c34d89918")});
WriteResult({ "nRemoved" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo56.find();
This will produce the following output −
{ "_id" : ObjectId("5e272e0bcfb11e5c34d89917"), "Name" : "Chris" }
{ "_id" : ObjectId("5e272e13cfb11e5c34d89919"), "Name" : "Bob" } | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "To remove a specific document, use remove() in MongoDB. Let us create a collection with documents −"
},
{
"code": null,
"e": 1538,
"s": 1162,
"text": "> db.demo56.insertOne({\"Name\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e272e0bcfb11e5c34d89917\")\n}\n> db.demo56.insertOne({\"Name\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e272e10cfb11e5c34d89918\")\n}\n> db.demo56.insertOne({\"Name\":\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e272e13cfb11e5c34d89919\")\n}"
},
{
"code": null,
"e": 1611,
"s": 1538,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1631,
"s": 1611,
"text": "> db.demo56.find();"
},
{
"code": null,
"e": 1672,
"s": 1631,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1871,
"s": 1672,
"text": "{ \"_id\" : ObjectId(\"5e272e0bcfb11e5c34d89917\"), \"Name\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e272e10cfb11e5c34d89918\"), \"Name\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e272e13cfb11e5c34d89919\"), \"Name\" : \"Bob\" }"
},
{
"code": null,
"e": 1926,
"s": 1871,
"text": "Following is the query to remove a specific document −"
},
{
"code": null,
"e": 2022,
"s": 1926,
"text": "> db.demo56.remove({_id:ObjectId(\"5e272e10cfb11e5c34d89918\")});\nWriteResult({ \"nRemoved\" : 1 })"
},
{
"code": null,
"e": 2095,
"s": 2022,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2115,
"s": 2095,
"text": "> db.demo56.find();"
},
{
"code": null,
"e": 2156,
"s": 2115,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2288,
"s": 2156,
"text": "{ \"_id\" : ObjectId(\"5e272e0bcfb11e5c34d89917\"), \"Name\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e272e13cfb11e5c34d89919\"), \"Name\" : \"Bob\" }"
}
] |
How to Resize an image in Android using Picasso on Kotlin? | This example demonstrates how to Resize an image in Android using Picasso on 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.
<LinearLayout 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"
android:orientation="vertical"
android:paddingStart="16dp"
android:paddingTop="16dp"
android:paddingEnd="16dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Step 3 − Add the following dependency to build.gradle(Module:app)
implementation 'com.squareup.picasso:picasso:2.5.2'
Step 4 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.squareup.picasso.Picasso
class MainActivity : AppCompatActivity() {
private lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
imageView = findViewById(R.id.imageView)
val url = "https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg"
Picasso.with(this).load(url).resize(600, 500).into(imageView)
}
}
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="app.com.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<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": 1147,
"s": 1062,
"text": "This example demonstrates how to Resize an image in Android using Picasso on Kotlin."
},
{
"code": null,
"e": 1275,
"s": 1147,
"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": 1340,
"s": 1275,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1851,
"s": 1340,
"text": "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:paddingStart=\"16dp\"\n android:paddingTop=\"16dp\"\n android:paddingEnd=\"16dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1917,
"s": 1851,
"text": "Step 3 − Add the following dependency to build.gradle(Module:app)"
},
{
"code": null,
"e": 1969,
"s": 1917,
"text": "implementation 'com.squareup.picasso:picasso:2.5.2'"
},
{
"code": null,
"e": 2024,
"s": 1969,
"text": "Step 4 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2626,
"s": 2024,
"text": "import android.os.Bundle\nimport android.widget.ImageView\nimport androidx.appcompat.app.AppCompatActivity\nimport com.squareup.picasso.Picasso\nclass MainActivity : AppCompatActivity() {\n private lateinit var imageView: ImageView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n imageView = findViewById(R.id.imageView)\n val url = \"https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg\"\n Picasso.with(this).load(url).resize(600, 500).into(imageView)\n }\n}"
},
{
"code": null,
"e": 2681,
"s": 2626,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3421,
"s": 2681,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.myapplication\">\n<uses-permission android:name=\"android.permission.INTERNET\" />\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": 3769,
"s": 3421,
"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"
}
] |
POJO vs Java Beans | As we know that in Java POJO refers to the Plain old Java object.POJO and Bean class in Java shares some common features which are as follows −
Both classes must be public i.e accessible to all.
Both classes must be public i.e accessible to all.
Properties or variables defined in both classes must be private i.e. can't be accessed directly.
Properties or variables defined in both classes must be private i.e. can't be accessed directly.
Both classes must have default constructor i.e no argument constructor.
Both classes must have default constructor i.e no argument constructor.
Public Getter and Setter must be present in both the classes in order to access the variables/properties.
Public Getter and Setter must be present in both the classes in order to access the variables/properties.
The only difference between both the classes is Java make java beans objects serialized so that the state of a bean class could be preserved in case required.So due to this a Java Bean class must either implements Serializable or Externalizable interface.
Due to this it is stated that all JavaBeans are POJOs but not all POJOs are JavaBeans.
public class Employee implements java.io.Serializable {
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
public class Employee {
String name;
public String id;
private double salary;
public Employee(String name, String id,double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public Double getSalary() {
return salary;
}
} | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "As we know that in Java POJO refers to the Plain old Java object.POJO and Bean class in Java shares some common features which are as follows −"
},
{
"code": null,
"e": 1257,
"s": 1206,
"text": "Both classes must be public i.e accessible to all."
},
{
"code": null,
"e": 1308,
"s": 1257,
"text": "Both classes must be public i.e accessible to all."
},
{
"code": null,
"e": 1405,
"s": 1308,
"text": "Properties or variables defined in both classes must be private i.e. can't be accessed directly."
},
{
"code": null,
"e": 1502,
"s": 1405,
"text": "Properties or variables defined in both classes must be private i.e. can't be accessed directly."
},
{
"code": null,
"e": 1574,
"s": 1502,
"text": "Both classes must have default constructor i.e no argument constructor."
},
{
"code": null,
"e": 1646,
"s": 1574,
"text": "Both classes must have default constructor i.e no argument constructor."
},
{
"code": null,
"e": 1752,
"s": 1646,
"text": "Public Getter and Setter must be present in both the classes in order to access the variables/properties."
},
{
"code": null,
"e": 1858,
"s": 1752,
"text": "Public Getter and Setter must be present in both the classes in order to access the variables/properties."
},
{
"code": null,
"e": 2114,
"s": 1858,
"text": "The only difference between both the classes is Java make java beans objects serialized so that the state of a bean class could be preserved in case required.So due to this a Java Bean class must either implements Serializable or Externalizable interface."
},
{
"code": null,
"e": 2201,
"s": 2114,
"text": "Due to this it is stated that all JavaBeans are POJOs but not all POJOs are JavaBeans."
},
{
"code": null,
"e": 2495,
"s": 2201,
"text": "public class Employee implements java.io.Serializable {\n private int id;\n private String name;\n public Employee(){}\n public void setId(int id){this.id=id;}\n public int getId(){return id;}\n public void setName(String name){this.name=name;}\n public String getName(){return name;}\n}"
},
{
"code": null,
"e": 2879,
"s": 2495,
"text": "public class Employee {\n String name;\n public String id;\n private double salary;\n public Employee(String name, String id,double salary) {\n this.name = name;\n this.id = id;\n this.salary = salary;\n }\n public String getName() {\n return name;\n }\n public String getId() {\n return id;\n }\n public Double getSalary() {\n return salary;\n }\n}"
}
] |
C# | String.IndexOf( ) Method | Set - 1 - GeeksforGeeks | 31 Jan, 2019
In C#, IndexOf() method is a string method. This method is used to find the zero based index of the first occurrence of a specified character or string within current instance of the string. The method returns -1 if the character or string is not found. This method can be overloaded by passing different parameters to it.
String.IndexOf(char x)
String.IndexOf(char x, int start1)
String.IndexOf(char x, int start1, int start2)
String.IndexOf(string s1)
String.IndexOf(string s1, int start1)
String.IndexOf(string s1, int start1, int start2)
String.IndexOf(string s1, int start1, int start2, StringComparison cType)
String.IndexOf(string s1, int start1, StringComparison cType)
String.IndexOf(string s1, StringComparison cType)
This method returns the zero-based index of the first occurrence of the specified character within the string. In case no such character founds then it returns -1.
Syntax:
public int IndexOf(char x)
Parameters: This method takes a parameter char x of type System.Char which specified the character to be searched.
Return Type: The return type of this method is System.Int32.
Example: In the below code the User wants to know the index of character ‘F’ within the specified string “GeeksForGeeks” and as a result, this method returns respective outcome mainly the first occurrence of character ‘F’. Also in the second case, the character ‘C’ was not present so it simply returns -1.
// C# program to illustrate the // String.IndexOf(char x) methodusing System;namespace ConsoleApplication1 { class Geeks { // Main Method static void Main(string[] args) { string str = "GeeksForGeeks"; // Finding the index of character // which is present in string and // this will show the value 5 int index1 = str.IndexOf('F'); Console.WriteLine("The Index Value of character 'F' is " + index1); // Now finding the index of that character which // is not even present with the string int index2 = str.IndexOf('C'); // As expected, this will output value -1 Console.WriteLine("The Index Value of character 'C' is " + index2); }}}
Output:
The Index Value of character 'F' is 5
The Index Value of character 'C' is -1
This method returns the zero-based index of the first occurrence of the specified character within the string. However, the searching of that character will start from a specified position and if not found it returns -1.
Syntax:
public int IndexOf(char x, int start1)
Parameters: This method takes two parameters i.e char x of type System.Char which specified the character to be searched and start1 of type System.Int32 which specify the starting position in the form of integer value from where the searching to be started.
Return Type: The return type of this method is System.Int32.
Exception: This method can give ArgumentOutOfRangeException if the start1 is less than 0 (zero) or greater than the length of the string.
Example: In the below code the User wants to know the index of character ‘H’ within the specified string “HelloGeeks” and as a result, this method returns the respective index of character ‘H’. However if start1 is greater than 1 then it is obvious to return -1.
// C# program to illustrate the // String.IndexOf(char x, int start1) methodusing System;namespace ConsoleApplication2{ class Geeks { // Main Method static void Main(string[] args) { string str = "HelloGeeks"; // Finding the index of character // which is present in string // this will show the value 0 int index1 = str.IndexOf('H', 0); Console.WriteLine("The Index Value of character 'H' "+ "with start index 0 is " + index1); // Now finding the index of character // 'H' with starting position greater // than index position of 'H' int index2 = str.IndexOf('H', 5); // As expected, this will output value -1 Console.WriteLine("The Index Value of character 'H' is " + index2); }}}
Output:
The Index Value of character 'H' with start index 0 is 0
The Index Value of character 'H' is -1
This method returns the zero-based index of the first occurrence of the specified character within the string. However, the searching of that character will start from a specified position start1 till specified position i.e start2 and if not found it returns -1.
Syntax:
public int IndexOf(char x, int start1, int start2)
Parameters: This method takes three parameters i.e char x of type System.Char which specified the character to be searched, start1 of type System.Int32 which specify the starting position in the form of integer value from where the searching to be started and start2 of type System.Int32 which specify the ending position where searching is to be stopped.
Return Type: The return type of this method is System.Int32.
Exception: This method can give ArgumentOutOfRangeException if the start1 or start2 is negative or start1 is greater than the length of the current string or start2 is greater than the length of current string minus start1.
Example: In the below code the User wants to know the index of character ‘R’ within the specified string “My Life My Rules” and as a result, this method returns the index value of character ‘R’. Again for the case that start1>1 and start2<8 it again returns -1 because it didn't find any character.
// C# program to illustrate the// String.IndexOf(char x, int start1,// int start2) methodusing System;namespace ConsoleApplication3 { class Geeks { // Main Method static void Main(string[] args) { string str = "My Life My Rules"; int index1 = str.IndexOf('R', 2, 14); // Here starting index is < Index value of 'R' // Also ending index is > Index of 'R' // Hence It is obvious to return 11 Console.WriteLine("Index Value of 'R' with start"+ " Index =2 and end Index = 15 is " + index1); // Now here starting index is chosen right // However ending position is < index of 'R' // Surely it will return -1 int index2 = str.IndexOf('R', 1, 8); Console.WriteLine("Index Value of 'R' with start"+ " Index = 1 and end Index = 8 is " + index2); }}}
Output:
Index Value of 'R' with start Index =2 and end Index = 15 is 11
Index Value of 'R' with start Index = 1 and end Index = 8 is -1
This method returns the zero-based index of the first occurrence of the specified sub-string within the string. In case no such string is found then it returns -1 same as in case of characters.
Syntax:
public int IndexOf(string s1)
Parameters: This method takes a parameter s1 of type System.String which specified the substring to be searched.
Return Type: The return type of this method is System.Int32. The zero-based index position of s1 if that string is found, or -1 if it is not. If s1 is String.Empty, the return value is 0.
Exception: This method can give ArgumentNullException if the s1 is null.
Example: In the below code, it is known that string ‘How’ is present in the main string, so it will simply return the index value of its first character. However, in the next case, there is no substring with name “Chair” so, it simply returns -1.
// C# program to illustrate the// String.IndexOf(string s1) methodusing System;namespace ConsoleApplication4 { class Geeks { // Main Method static void Main(string[] args) { string str = "Hello Friends....How are you..."; int i = str.IndexOf("How"); // As this string is present in the // main string then it will obviously // output the value as 17 Console.WriteLine("First value Index of 'How' is " + i); // now the following string is not present // So as per the rules, it will return -1 int i1 = str.IndexOf("Chair"); // As this string is present in // the main string then it will // obviously output the value as -1 Console.WriteLine("First value Index of 'Chair' is " + i1); }}}
Output:
First value Index of 'How' is 17
First value Index of 'Chair' is -1
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
Destructors in C#
Extension Method in C#
C# | Constructors
C# | Abstract Classes
Introduction to .NET Framework
C# | Class and Object
C# | Data Types
C# | Encapsulation
HashSet in C# with Examples | [
{
"code": null,
"e": 24519,
"s": 24491,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 24842,
"s": 24519,
"text": "In C#, IndexOf() method is a string method. This method is used to find the zero based index of the first occurrence of a specified character or string within current instance of the string. The method returns -1 if the character or string is not found. This method can be overloaded by passing different parameters to it."
},
{
"code": null,
"e": 24865,
"s": 24842,
"text": "String.IndexOf(char x)"
},
{
"code": null,
"e": 24900,
"s": 24865,
"text": "String.IndexOf(char x, int start1)"
},
{
"code": null,
"e": 24947,
"s": 24900,
"text": "String.IndexOf(char x, int start1, int start2)"
},
{
"code": null,
"e": 24973,
"s": 24947,
"text": "String.IndexOf(string s1)"
},
{
"code": null,
"e": 25011,
"s": 24973,
"text": "String.IndexOf(string s1, int start1)"
},
{
"code": null,
"e": 25061,
"s": 25011,
"text": "String.IndexOf(string s1, int start1, int start2)"
},
{
"code": null,
"e": 25135,
"s": 25061,
"text": "String.IndexOf(string s1, int start1, int start2, StringComparison cType)"
},
{
"code": null,
"e": 25197,
"s": 25135,
"text": "String.IndexOf(string s1, int start1, StringComparison cType)"
},
{
"code": null,
"e": 25247,
"s": 25197,
"text": "String.IndexOf(string s1, StringComparison cType)"
},
{
"code": null,
"e": 25411,
"s": 25247,
"text": "This method returns the zero-based index of the first occurrence of the specified character within the string. In case no such character founds then it returns -1."
},
{
"code": null,
"e": 25419,
"s": 25411,
"text": "Syntax:"
},
{
"code": null,
"e": 25447,
"s": 25419,
"text": "public int IndexOf(char x)\n"
},
{
"code": null,
"e": 25562,
"s": 25447,
"text": "Parameters: This method takes a parameter char x of type System.Char which specified the character to be searched."
},
{
"code": null,
"e": 25623,
"s": 25562,
"text": "Return Type: The return type of this method is System.Int32."
},
{
"code": null,
"e": 25930,
"s": 25623,
"text": "Example: In the below code the User wants to know the index of character ‘F’ within the specified string “GeeksForGeeks” and as a result, this method returns respective outcome mainly the first occurrence of character ‘F’. Also in the second case, the character ‘C’ was not present so it simply returns -1."
},
{
"code": "// C# program to illustrate the // String.IndexOf(char x) methodusing System;namespace ConsoleApplication1 { class Geeks { // Main Method static void Main(string[] args) { string str = \"GeeksForGeeks\"; // Finding the index of character // which is present in string and // this will show the value 5 int index1 = str.IndexOf('F'); Console.WriteLine(\"The Index Value of character 'F' is \" + index1); // Now finding the index of that character which // is not even present with the string int index2 = str.IndexOf('C'); // As expected, this will output value -1 Console.WriteLine(\"The Index Value of character 'C' is \" + index2); }}}",
"e": 26674,
"s": 25930,
"text": null
},
{
"code": null,
"e": 26682,
"s": 26674,
"text": "Output:"
},
{
"code": null,
"e": 26759,
"s": 26682,
"text": "The Index Value of character 'F' is 5\nThe Index Value of character 'C' is -1"
},
{
"code": null,
"e": 26980,
"s": 26759,
"text": "This method returns the zero-based index of the first occurrence of the specified character within the string. However, the searching of that character will start from a specified position and if not found it returns -1."
},
{
"code": null,
"e": 26988,
"s": 26980,
"text": "Syntax:"
},
{
"code": null,
"e": 27028,
"s": 26988,
"text": "public int IndexOf(char x, int start1)\n"
},
{
"code": null,
"e": 27286,
"s": 27028,
"text": "Parameters: This method takes two parameters i.e char x of type System.Char which specified the character to be searched and start1 of type System.Int32 which specify the starting position in the form of integer value from where the searching to be started."
},
{
"code": null,
"e": 27347,
"s": 27286,
"text": "Return Type: The return type of this method is System.Int32."
},
{
"code": null,
"e": 27485,
"s": 27347,
"text": "Exception: This method can give ArgumentOutOfRangeException if the start1 is less than 0 (zero) or greater than the length of the string."
},
{
"code": null,
"e": 27748,
"s": 27485,
"text": "Example: In the below code the User wants to know the index of character ‘H’ within the specified string “HelloGeeks” and as a result, this method returns the respective index of character ‘H’. However if start1 is greater than 1 then it is obvious to return -1."
},
{
"code": "// C# program to illustrate the // String.IndexOf(char x, int start1) methodusing System;namespace ConsoleApplication2{ class Geeks { // Main Method static void Main(string[] args) { string str = \"HelloGeeks\"; // Finding the index of character // which is present in string // this will show the value 0 int index1 = str.IndexOf('H', 0); Console.WriteLine(\"The Index Value of character 'H' \"+ \"with start index 0 is \" + index1); // Now finding the index of character // 'H' with starting position greater // than index position of 'H' int index2 = str.IndexOf('H', 5); // As expected, this will output value -1 Console.WriteLine(\"The Index Value of character 'H' is \" + index2); }}}",
"e": 28570,
"s": 27748,
"text": null
},
{
"code": null,
"e": 28578,
"s": 28570,
"text": "Output:"
},
{
"code": null,
"e": 28674,
"s": 28578,
"text": "The Index Value of character 'H' with start index 0 is 0\nThe Index Value of character 'H' is -1"
},
{
"code": null,
"e": 28937,
"s": 28674,
"text": "This method returns the zero-based index of the first occurrence of the specified character within the string. However, the searching of that character will start from a specified position start1 till specified position i.e start2 and if not found it returns -1."
},
{
"code": null,
"e": 28945,
"s": 28937,
"text": "Syntax:"
},
{
"code": null,
"e": 28997,
"s": 28945,
"text": "public int IndexOf(char x, int start1, int start2)\n"
},
{
"code": null,
"e": 29353,
"s": 28997,
"text": "Parameters: This method takes three parameters i.e char x of type System.Char which specified the character to be searched, start1 of type System.Int32 which specify the starting position in the form of integer value from where the searching to be started and start2 of type System.Int32 which specify the ending position where searching is to be stopped."
},
{
"code": null,
"e": 29414,
"s": 29353,
"text": "Return Type: The return type of this method is System.Int32."
},
{
"code": null,
"e": 29638,
"s": 29414,
"text": "Exception: This method can give ArgumentOutOfRangeException if the start1 or start2 is negative or start1 is greater than the length of the current string or start2 is greater than the length of current string minus start1."
},
{
"code": null,
"e": 29937,
"s": 29638,
"text": "Example: In the below code the User wants to know the index of character ‘R’ within the specified string “My Life My Rules” and as a result, this method returns the index value of character ‘R’. Again for the case that start1>1 and start2<8 it again returns -1 because it didn't find any character."
},
{
"code": "// C# program to illustrate the// String.IndexOf(char x, int start1,// int start2) methodusing System;namespace ConsoleApplication3 { class Geeks { // Main Method static void Main(string[] args) { string str = \"My Life My Rules\"; int index1 = str.IndexOf('R', 2, 14); // Here starting index is < Index value of 'R' // Also ending index is > Index of 'R' // Hence It is obvious to return 11 Console.WriteLine(\"Index Value of 'R' with start\"+ \" Index =2 and end Index = 15 is \" + index1); // Now here starting index is chosen right // However ending position is < index of 'R' // Surely it will return -1 int index2 = str.IndexOf('R', 1, 8); Console.WriteLine(\"Index Value of 'R' with start\"+ \" Index = 1 and end Index = 8 is \" + index2); }}}",
"e": 30832,
"s": 29937,
"text": null
},
{
"code": null,
"e": 30840,
"s": 30832,
"text": "Output:"
},
{
"code": null,
"e": 30969,
"s": 30840,
"text": "Index Value of 'R' with start Index =2 and end Index = 15 is 11\nIndex Value of 'R' with start Index = 1 and end Index = 8 is -1\n"
},
{
"code": null,
"e": 31163,
"s": 30969,
"text": "This method returns the zero-based index of the first occurrence of the specified sub-string within the string. In case no such string is found then it returns -1 same as in case of characters."
},
{
"code": null,
"e": 31171,
"s": 31163,
"text": "Syntax:"
},
{
"code": null,
"e": 31202,
"s": 31171,
"text": "public int IndexOf(string s1)\n"
},
{
"code": null,
"e": 31315,
"s": 31202,
"text": "Parameters: This method takes a parameter s1 of type System.String which specified the substring to be searched."
},
{
"code": null,
"e": 31503,
"s": 31315,
"text": "Return Type: The return type of this method is System.Int32. The zero-based index position of s1 if that string is found, or -1 if it is not. If s1 is String.Empty, the return value is 0."
},
{
"code": null,
"e": 31576,
"s": 31503,
"text": "Exception: This method can give ArgumentNullException if the s1 is null."
},
{
"code": null,
"e": 31823,
"s": 31576,
"text": "Example: In the below code, it is known that string ‘How’ is present in the main string, so it will simply return the index value of its first character. However, in the next case, there is no substring with name “Chair” so, it simply returns -1."
},
{
"code": "// C# program to illustrate the// String.IndexOf(string s1) methodusing System;namespace ConsoleApplication4 { class Geeks { // Main Method static void Main(string[] args) { string str = \"Hello Friends....How are you...\"; int i = str.IndexOf(\"How\"); // As this string is present in the // main string then it will obviously // output the value as 17 Console.WriteLine(\"First value Index of 'How' is \" + i); // now the following string is not present // So as per the rules, it will return -1 int i1 = str.IndexOf(\"Chair\"); // As this string is present in // the main string then it will // obviously output the value as -1 Console.WriteLine(\"First value Index of 'Chair' is \" + i1); }}}",
"e": 32631,
"s": 31823,
"text": null
},
{
"code": null,
"e": 32639,
"s": 32631,
"text": "Output:"
},
{
"code": null,
"e": 32707,
"s": 32639,
"text": "First value Index of 'How' is 17\nFirst value Index of 'Chair' is -1"
},
{
"code": null,
"e": 32721,
"s": 32707,
"text": "CSharp-method"
},
{
"code": null,
"e": 32735,
"s": 32721,
"text": "CSharp-string"
},
{
"code": null,
"e": 32738,
"s": 32735,
"text": "C#"
},
{
"code": null,
"e": 32836,
"s": 32738,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32851,
"s": 32836,
"text": "C# | Delegates"
},
{
"code": null,
"e": 32869,
"s": 32851,
"text": "Destructors in C#"
},
{
"code": null,
"e": 32892,
"s": 32869,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 32910,
"s": 32892,
"text": "C# | Constructors"
},
{
"code": null,
"e": 32932,
"s": 32910,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 32963,
"s": 32932,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 32985,
"s": 32963,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 33001,
"s": 32985,
"text": "C# | Data Types"
},
{
"code": null,
"e": 33020,
"s": 33001,
"text": "C# | Encapsulation"
}
] |
Unix / Linux Shell - The case...esac Statement | You can use multiple if...elif statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.
Shell supports case...esac statement which handles exactly this situation, and it does so more efficiently than repeated if...elif statements.
The basic syntax of the case...esac statement is to give an expression to evaluate and to execute several different statements based on the value of the expression.
The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac
Here the string word is compared against every pattern until a match is found. The statement(s) following the matching pattern executes. If no matches are found, the case statement exits without performing any action.
There is no maximum number of patterns, but the minimum is one.
When statement(s) part executes, the command ;; indicates that the program flow should jump to the end of the entire case statement. This is similar to break in the C programming language.
#!/bin/sh
FRUIT="kiwi"
case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
esac
Upon execution, you will receive the following result −
New Zealand is famous for kiwi.
A good use for a case statement is the evaluation of command line arguments as follows −
#!/bin/sh
option="${1}"
case ${option} in
-f) FILE="${2}"
echo "File name is $FILE"
;;
-d) DIR="${2}"
echo "Dir name is $DIR"
;;
*)
echo "`basename ${0}`:usage: [-f file] | [-d directory]"
exit 1 # Command to come out of the program with status 1
;;
esac
Here is a sample run of the above program −
$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$
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": 2944,
"s": 2747,
"text": "You can use multiple if...elif statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable."
},
{
"code": null,
"e": 3087,
"s": 2944,
"text": "Shell supports case...esac statement which handles exactly this situation, and it does so more efficiently than repeated if...elif statements."
},
{
"code": null,
"e": 3252,
"s": 3087,
"text": "The basic syntax of the case...esac statement is to give an expression to evaluate and to execute several different statements based on the value of the expression."
},
{
"code": null,
"e": 3399,
"s": 3252,
"text": "The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used."
},
{
"code": null,
"e": 3698,
"s": 3399,
"text": "case word in\n pattern1)\n Statement(s) to be executed if pattern1 matches\n ;;\n pattern2)\n Statement(s) to be executed if pattern2 matches\n ;;\n pattern3)\n Statement(s) to be executed if pattern3 matches\n ;;\n *)\n Default condition to be executed\n ;;\nesac\n"
},
{
"code": null,
"e": 3916,
"s": 3698,
"text": "Here the string word is compared against every pattern until a match is found. The statement(s) following the matching pattern executes. If no matches are found, the case statement exits without performing any action."
},
{
"code": null,
"e": 3980,
"s": 3916,
"text": "There is no maximum number of patterns, but the minimum is one."
},
{
"code": null,
"e": 4169,
"s": 3980,
"text": "When statement(s) part executes, the command ;; indicates that the program flow should jump to the end of the entire case statement. This is similar to break in the C programming language."
},
{
"code": null,
"e": 4377,
"s": 4169,
"text": "#!/bin/sh\n\nFRUIT=\"kiwi\"\n\ncase \"$FRUIT\" in\n \"apple\") echo \"Apple pie is quite tasty.\" \n ;;\n \"banana\") echo \"I like banana nut bread.\" \n ;;\n \"kiwi\") echo \"New Zealand is famous for kiwi.\" \n ;;\nesac"
},
{
"code": null,
"e": 4433,
"s": 4377,
"text": "Upon execution, you will receive the following result −"
},
{
"code": null,
"e": 4466,
"s": 4433,
"text": "New Zealand is famous for kiwi.\n"
},
{
"code": null,
"e": 4555,
"s": 4466,
"text": "A good use for a case statement is the evaluation of command line arguments as follows −"
},
{
"code": null,
"e": 4873,
"s": 4555,
"text": "#!/bin/sh\n\noption=\"${1}\" \ncase ${option} in \n -f) FILE=\"${2}\" \n echo \"File name is $FILE\"\n ;; \n -d) DIR=\"${2}\" \n echo \"Dir name is $DIR\"\n ;; \n *) \n echo \"`basename ${0}`:usage: [-f file] | [-d directory]\" \n exit 1 # Command to come out of the program with status 1\n ;; \nesac "
},
{
"code": null,
"e": 4917,
"s": 4873,
"text": "Here is a sample run of the above program −"
},
{
"code": null,
"e": 5105,
"s": 4917,
"text": "$./test.sh\ntest.sh: usage: [ -f filename ] | [ -d directory ]\n$ ./test.sh -f index.htm\n$ vi test.sh\n$ ./test.sh -f index.htm\nFile name is index.htm\n$ ./test.sh -d unix\nDir name is unix\n$\n"
},
{
"code": null,
"e": 5140,
"s": 5105,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 5168,
"s": 5140,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5202,
"s": 5168,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5219,
"s": 5202,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5252,
"s": 5219,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5263,
"s": 5252,
"text": " Pradeep D"
},
{
"code": null,
"e": 5298,
"s": 5263,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5314,
"s": 5298,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 5347,
"s": 5314,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5359,
"s": 5347,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 5391,
"s": 5359,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5399,
"s": 5391,
"text": " Uplatz"
},
{
"code": null,
"e": 5406,
"s": 5399,
"text": " Print"
},
{
"code": null,
"e": 5417,
"s": 5406,
"text": " Add Notes"
}
] |
Apache Pig - Order By | The ORDER BY operator is used to display the contents of a relation in a sorted order based on one or more fields.
Given below is the syntax of the ORDER BY operator.
grunt> Relation_name2 = ORDER Relatin_name1 BY (ASC|DESC);
Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below.
student_details.txt
001,Rajiv,Reddy,21,9848022337,Hyderabad
002,siddarth,Battacharya,22,9848022338,Kolkata
003,Rajesh,Khanna,22,9848022339,Delhi
004,Preethi,Agarwal,21,9848022330,Pune
005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar
006,Archana,Mishra,23,9848022335,Chennai
007,Komal,Nayak,24,9848022334,trivendram
008,Bharathi,Nambiayar,24,9848022333,Chennai
And we have loaded this file into Pig with the relation name student_details as shown below.
grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')
as (id:int, firstname:chararray, lastname:chararray,age:int, phone:chararray, city:chararray);
Let us now sort the relation in a descending order based on the age of the student and store it into another relation named order_by_data using the ORDER BY operator as shown below.
grunt> order_by_data = ORDER student_details BY age DESC;
Verify the relation order_by_data using the DUMP operator as shown below.
grunt> Dump order_by_data;
It will produce the following output, displaying the contents of the relation order_by_data.
(8,Bharathi,Nambiayar,24,9848022333,Chennai)
(7,Komal,Nayak,24,9848022334,trivendram)
(6,Archana,Mishra,23,9848022335,Chennai)
(5,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar)
(3,Rajesh,Khanna,22,9848022339,Delhi)
(2,siddarth,Battacharya,22,9848022338,Kolkata)
(4,Preethi,Agarwal,21,9848022330,Pune)
(1,Rajiv,Reddy,21,9848022337,Hyderabad)
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": 2799,
"s": 2684,
"text": "The ORDER BY operator is used to display the contents of a relation in a sorted order based on one or more fields."
},
{
"code": null,
"e": 2851,
"s": 2799,
"text": "Given below is the syntax of the ORDER BY operator."
},
{
"code": null,
"e": 2911,
"s": 2851,
"text": "grunt> Relation_name2 = ORDER Relatin_name1 BY (ASC|DESC);\n"
},
{
"code": null,
"e": 3013,
"s": 2911,
"text": "Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below."
},
{
"code": null,
"e": 3033,
"s": 3013,
"text": "student_details.txt"
},
{
"code": null,
"e": 3378,
"s": 3033,
"text": "001,Rajiv,Reddy,21,9848022337,Hyderabad\n002,siddarth,Battacharya,22,9848022338,Kolkata\n003,Rajesh,Khanna,22,9848022339,Delhi \n004,Preethi,Agarwal,21,9848022330,Pune \n005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar \n006,Archana,Mishra,23,9848022335,Chennai \n007,Komal,Nayak,24,9848022334,trivendram \n008,Bharathi,Nambiayar,24,9848022333,Chennai\n"
},
{
"code": null,
"e": 3471,
"s": 3378,
"text": "And we have loaded this file into Pig with the relation name student_details as shown below."
},
{
"code": null,
"e": 3674,
"s": 3471,
"text": "grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')\n as (id:int, firstname:chararray, lastname:chararray,age:int, phone:chararray, city:chararray);"
},
{
"code": null,
"e": 3856,
"s": 3674,
"text": "Let us now sort the relation in a descending order based on the age of the student and store it into another relation named order_by_data using the ORDER BY operator as shown below."
},
{
"code": null,
"e": 3914,
"s": 3856,
"text": "grunt> order_by_data = ORDER student_details BY age DESC;"
},
{
"code": null,
"e": 3988,
"s": 3914,
"text": "Verify the relation order_by_data using the DUMP operator as shown below."
},
{
"code": null,
"e": 4016,
"s": 3988,
"text": "grunt> Dump order_by_data; "
},
{
"code": null,
"e": 4109,
"s": 4016,
"text": "It will produce the following output, displaying the contents of the relation order_by_data."
},
{
"code": null,
"e": 4452,
"s": 4109,
"text": "(8,Bharathi,Nambiayar,24,9848022333,Chennai)\n(7,Komal,Nayak,24,9848022334,trivendram)\n(6,Archana,Mishra,23,9848022335,Chennai) \n(5,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar)\n(3,Rajesh,Khanna,22,9848022339,Delhi) \n(2,siddarth,Battacharya,22,9848022338,Kolkata)\n(4,Preethi,Agarwal,21,9848022330,Pune) \n(1,Rajiv,Reddy,21,9848022337,Hyderabad)\n"
},
{
"code": null,
"e": 4487,
"s": 4452,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4506,
"s": 4487,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4541,
"s": 4506,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4562,
"s": 4541,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 4595,
"s": 4562,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4608,
"s": 4595,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 4643,
"s": 4608,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4661,
"s": 4643,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4694,
"s": 4661,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4712,
"s": 4694,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4745,
"s": 4712,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4763,
"s": 4745,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4770,
"s": 4763,
"text": " Print"
},
{
"code": null,
"e": 4781,
"s": 4770,
"text": " Add Notes"
}
] |
Java Program to Implement Shunting Yard Algorithm - GeeksforGeeks | 26 Jan, 2022
The shunting yard algorithm is used to convert the infix notation to reverse polish notation. The postfix notation is also known as the reverse polish notation (RPN). The algorithm was named a “Shunting yard” because its activity is similar to a railroad shunting yard. It is a method for representing expressions in which the operator symbol is placed after the arguments being operated on. Polish notation, in which the operator comes before the operands. Australian philosopher and computer scientist suggested placing the operator after the operands and hence created reverse polish notation. Dijkstra developed this algorithm
Representation and Interpretation:
Brackets are not required to represent the order of evaluation or grouping of the terms. RPN expressions are simply evaluated from left to right and this greatly simplifies the computation of the expression within computer programs. As an example, the arithmetic expression.
Interpreting from left to right the following two executions can be performed
If the value appears next in the expression push the current value in the stack.Now, if the operator appears next, pop the topmost two elements from the stack, execute the operation and push back the result into the stack.
If the value appears next in the expression push the current value in the stack.
Now, if the operator appears next, pop the topmost two elements from the stack, execute the operation and push back the result into the stack.
The order of precedence of operators is:
^
3
/
2
*
2
+
1
–
1
Illustration: RPN expression will produce the sum of 2 and 3, namely 5: 2 3 +
Input: (3+4)*5
Output: 3×4+5*
This is the postfix notation of the above infix notation
Concepts Involved:
Examples:
Infix Notation: a+b*(c^d-e)^(f+g*h)-i
Postfix Notation: abcd^e-fgh*+^*+i-
Algorithm: AE is the arithmetic expression written in infix notation PE will be the postfix expression of AE
Push “(“ onto Stack, and add “)” to the end of AE.Scan AE from left to right and repeat Step 3 to 6 for each element of AE until the Stack is empty.If an operand is encountered, append it to PE.If a left parenthesis is encountered, push it onto Stack.If an operator is encountered, then: Repeatedly pop from Stack and append to PE each operator which has the same precedence as or higher precedence than the operator. Add an operator to Stack. [End of if]If a right parenthesis is encountered, then: Repeatedly pop from Stack and append to PE each operator until a left parenthesis is encountered. Remove the left Parenthesis. [End of If] [End of If]g×h
Push “(“ onto Stack, and add “)” to the end of AE.
Scan AE from left to right and repeat Step 3 to 6 for each element of AE until the Stack is empty.
If an operand is encountered, append it to PE.
If a left parenthesis is encountered, push it onto Stack.
If an operator is encountered, then: Repeatedly pop from Stack and append to PE each operator which has the same precedence as or higher precedence than the operator. Add an operator to Stack. [End of if]
If a right parenthesis is encountered, then: Repeatedly pop from Stack and append to PE each operator until a left parenthesis is encountered. Remove the left Parenthesis. [End of If] [End of If]
g×h
Applying the same above algorithms for two examples given below:
Example 1 : Applying Shunting yard algorithm on the expression “1 + 2”
Step 1: Input “1 + 2”
Step 2: Push 1 to the output queue
Step 3: Push + to the operator stack, because + is an operator.
Step 4: Push 2 to the output queue
Step 5: After reading the input expression, the output queue and operator stack pop the expression and then add them to the output.
Step 6: Output “1 2 +”
Example 2: Applying the Shunting yard algorithm on the expression 5 + 2 / (3- 8) ^ 5 ^ 2
Implementing: Shunting Yard Algorithm
Java
// Java Implemention of Shunting Yard Algorithm // Importing stack class for stacks DSimport java.util.Stack;// Importing specific character class as// dealing with only operators and operandsimport java.lang.Character; class GFG { // Method is used to get the precedence of operators private static boolean letterOrDigit(char c) { // boolean check if (Character.isLetterOrDigit(c)) return true; else return false; } // Operator having higher precedence // value will be returned static int getPrecedence(char ch) { if (ch == '+' || ch == '-') return 1; else if (ch == '*' || ch == '/') return 2; else if (ch == '^') return 3; else return -1; } // Operator has Left --> Right associativity static boolean hasLeftAssociativity(char ch) { if (ch == '+' || ch == '-' || ch == '/' || ch == '*') { return true; } else { return false; } } // Method converts given infixto postfix expression // to illustrate shunting yard algorithm static String infixToRpn(String expression) { // Initialising an empty String // (for output) and an empty stack Stack<Character> stack = new Stack<>(); // Initially empty string taken String output = new String(""); // Iterating ovet tokens using inbuilt // .length() function for (int i = 0; i < expression.length(); ++i) { // Finding character at 'i'th index char c = expression.charAt(i); // If the scanned Token is an // operand, add it to output if (letterOrDigit(c)) output += c; // If the scanned Token is an '(' // push it to the stack else if (c == '(') stack.push(c); // If the scanned Token is an ')' pop and append // it to output from the stack until an '(' is // encountered else if (c == ')') { while (!stack.isEmpty() && stack.peek() != '(') output += stack.pop(); stack.pop(); } // If an operator is encountered then taken the // further action based on the precedence of the // operator else { while ( !stack.isEmpty() && getPrecedence(c) <= getPrecedence(stack.peek()) && hasLeftAssociativity(c)) { // peek() inbuilt stack function to // fetch the top element(token) output += stack.pop(); } stack.push(c); } } // pop all the remaining operators from // the stack and append them to output while (!stack.isEmpty()) { if (stack.peek() == '(') return "This expression is invalid"; output += stack.pop(); } return output; } // Main driver code public static void main(String[] args) { // Considering random infix string notation String expression = "5+2/(3-8)^5^2"; // Printing RPN for the above infix notation // Illustrating shunting yard algorithm System.out.println(infixToRpn(expression)); }}
5238-52^^/+
Time Complexity: O(n) This algorithm takes linear time, as we only traverse through the expression once and pop and push only take O(1).
Space Complexity: O(n) as we use a stack of size n, where n is length given of expression.
clintra
rajeev0719singh
sweetyty
tft035wt51sbq899304l51d13igth0s9g558p7k2
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
Convert a String to Character array in Java
Java Programming Examples
How to Iterate HashMap in Java?
Implementing a Linked List in Java using Class
Min Heap in Java | [
{
"code": null,
"e": 23581,
"s": 23553,
"text": "\n26 Jan, 2022"
},
{
"code": null,
"e": 24213,
"s": 23581,
"text": "The shunting yard algorithm is used to convert the infix notation to reverse polish notation. The postfix notation is also known as the reverse polish notation (RPN). The algorithm was named a “Shunting yard” because its activity is similar to a railroad shunting yard. It is a method for representing expressions in which the operator symbol is placed after the arguments being operated on. Polish notation, in which the operator comes before the operands. Australian philosopher and computer scientist suggested placing the operator after the operands and hence created reverse polish notation. Dijkstra developed this algorithm"
},
{
"code": null,
"e": 24248,
"s": 24213,
"text": "Representation and Interpretation:"
},
{
"code": null,
"e": 24523,
"s": 24248,
"text": "Brackets are not required to represent the order of evaluation or grouping of the terms. RPN expressions are simply evaluated from left to right and this greatly simplifies the computation of the expression within computer programs. As an example, the arithmetic expression."
},
{
"code": null,
"e": 24601,
"s": 24523,
"text": "Interpreting from left to right the following two executions can be performed"
},
{
"code": null,
"e": 24824,
"s": 24601,
"text": "If the value appears next in the expression push the current value in the stack.Now, if the operator appears next, pop the topmost two elements from the stack, execute the operation and push back the result into the stack."
},
{
"code": null,
"e": 24905,
"s": 24824,
"text": "If the value appears next in the expression push the current value in the stack."
},
{
"code": null,
"e": 25048,
"s": 24905,
"text": "Now, if the operator appears next, pop the topmost two elements from the stack, execute the operation and push back the result into the stack."
},
{
"code": null,
"e": 25089,
"s": 25048,
"text": "The order of precedence of operators is:"
},
{
"code": null,
"e": 25091,
"s": 25089,
"text": "^"
},
{
"code": null,
"e": 25093,
"s": 25091,
"text": "3"
},
{
"code": null,
"e": 25095,
"s": 25093,
"text": "/"
},
{
"code": null,
"e": 25097,
"s": 25095,
"text": "2"
},
{
"code": null,
"e": 25099,
"s": 25097,
"text": "*"
},
{
"code": null,
"e": 25101,
"s": 25099,
"text": "2"
},
{
"code": null,
"e": 25103,
"s": 25101,
"text": "+"
},
{
"code": null,
"e": 25105,
"s": 25103,
"text": "1"
},
{
"code": null,
"e": 25107,
"s": 25105,
"text": "–"
},
{
"code": null,
"e": 25109,
"s": 25107,
"text": "1"
},
{
"code": null,
"e": 25187,
"s": 25109,
"text": "Illustration: RPN expression will produce the sum of 2 and 3, namely 5: 2 3 +"
},
{
"code": null,
"e": 25202,
"s": 25187,
"text": "Input: (3+4)*5"
},
{
"code": null,
"e": 25217,
"s": 25202,
"text": "Output: 3×4+5*"
},
{
"code": null,
"e": 25274,
"s": 25217,
"text": "This is the postfix notation of the above infix notation"
},
{
"code": null,
"e": 25293,
"s": 25274,
"text": "Concepts Involved:"
},
{
"code": null,
"e": 25304,
"s": 25293,
"text": "Examples: "
},
{
"code": null,
"e": 25345,
"s": 25304,
"text": "Infix Notation: a+b*(c^d-e)^(f+g*h)-i "
},
{
"code": null,
"e": 25382,
"s": 25345,
"text": "Postfix Notation: abcd^e-fgh*+^*+i- "
},
{
"code": null,
"e": 25492,
"s": 25382,
"text": "Algorithm: AE is the arithmetic expression written in infix notation PE will be the postfix expression of AE "
},
{
"code": null,
"e": 26151,
"s": 25492,
"text": "Push “(“ onto Stack, and add “)” to the end of AE.Scan AE from left to right and repeat Step 3 to 6 for each element of AE until the Stack is empty.If an operand is encountered, append it to PE.If a left parenthesis is encountered, push it onto Stack.If an operator is encountered, then: Repeatedly pop from Stack and append to PE each operator which has the same precedence as or higher precedence than the operator. Add an operator to Stack. [End of if]If a right parenthesis is encountered, then: Repeatedly pop from Stack and append to PE each operator until a left parenthesis is encountered. Remove the left Parenthesis. [End of If] [End of If]g×h"
},
{
"code": null,
"e": 26202,
"s": 26151,
"text": "Push “(“ onto Stack, and add “)” to the end of AE."
},
{
"code": null,
"e": 26301,
"s": 26202,
"text": "Scan AE from left to right and repeat Step 3 to 6 for each element of AE until the Stack is empty."
},
{
"code": null,
"e": 26348,
"s": 26301,
"text": "If an operand is encountered, append it to PE."
},
{
"code": null,
"e": 26406,
"s": 26348,
"text": "If a left parenthesis is encountered, push it onto Stack."
},
{
"code": null,
"e": 26611,
"s": 26406,
"text": "If an operator is encountered, then: Repeatedly pop from Stack and append to PE each operator which has the same precedence as or higher precedence than the operator. Add an operator to Stack. [End of if]"
},
{
"code": null,
"e": 26812,
"s": 26611,
"text": "If a right parenthesis is encountered, then: Repeatedly pop from Stack and append to PE each operator until a left parenthesis is encountered. Remove the left Parenthesis. [End of If] [End of If]"
},
{
"code": null,
"e": 26816,
"s": 26812,
"text": "g×h"
},
{
"code": null,
"e": 26881,
"s": 26816,
"text": "Applying the same above algorithms for two examples given below:"
},
{
"code": null,
"e": 26953,
"s": 26881,
"text": "Example 1 : Applying Shunting yard algorithm on the expression “1 + 2” "
},
{
"code": null,
"e": 26975,
"s": 26953,
"text": "Step 1: Input “1 + 2”"
},
{
"code": null,
"e": 27010,
"s": 26975,
"text": "Step 2: Push 1 to the output queue"
},
{
"code": null,
"e": 27074,
"s": 27010,
"text": "Step 3: Push + to the operator stack, because + is an operator."
},
{
"code": null,
"e": 27109,
"s": 27074,
"text": "Step 4: Push 2 to the output queue"
},
{
"code": null,
"e": 27241,
"s": 27109,
"text": "Step 5: After reading the input expression, the output queue and operator stack pop the expression and then add them to the output."
},
{
"code": null,
"e": 27264,
"s": 27241,
"text": "Step 6: Output “1 2 +”"
},
{
"code": null,
"e": 27354,
"s": 27264,
"text": "Example 2: Applying the Shunting yard algorithm on the expression 5 + 2 / (3- 8) ^ 5 ^ 2 "
},
{
"code": null,
"e": 27393,
"s": 27354,
"text": "Implementing: Shunting Yard Algorithm "
},
{
"code": null,
"e": 27398,
"s": 27393,
"text": "Java"
},
{
"code": "// Java Implemention of Shunting Yard Algorithm // Importing stack class for stacks DSimport java.util.Stack;// Importing specific character class as// dealing with only operators and operandsimport java.lang.Character; class GFG { // Method is used to get the precedence of operators private static boolean letterOrDigit(char c) { // boolean check if (Character.isLetterOrDigit(c)) return true; else return false; } // Operator having higher precedence // value will be returned static int getPrecedence(char ch) { if (ch == '+' || ch == '-') return 1; else if (ch == '*' || ch == '/') return 2; else if (ch == '^') return 3; else return -1; } // Operator has Left --> Right associativity static boolean hasLeftAssociativity(char ch) { if (ch == '+' || ch == '-' || ch == '/' || ch == '*') { return true; } else { return false; } } // Method converts given infixto postfix expression // to illustrate shunting yard algorithm static String infixToRpn(String expression) { // Initialising an empty String // (for output) and an empty stack Stack<Character> stack = new Stack<>(); // Initially empty string taken String output = new String(\"\"); // Iterating ovet tokens using inbuilt // .length() function for (int i = 0; i < expression.length(); ++i) { // Finding character at 'i'th index char c = expression.charAt(i); // If the scanned Token is an // operand, add it to output if (letterOrDigit(c)) output += c; // If the scanned Token is an '(' // push it to the stack else if (c == '(') stack.push(c); // If the scanned Token is an ')' pop and append // it to output from the stack until an '(' is // encountered else if (c == ')') { while (!stack.isEmpty() && stack.peek() != '(') output += stack.pop(); stack.pop(); } // If an operator is encountered then taken the // further action based on the precedence of the // operator else { while ( !stack.isEmpty() && getPrecedence(c) <= getPrecedence(stack.peek()) && hasLeftAssociativity(c)) { // peek() inbuilt stack function to // fetch the top element(token) output += stack.pop(); } stack.push(c); } } // pop all the remaining operators from // the stack and append them to output while (!stack.isEmpty()) { if (stack.peek() == '(') return \"This expression is invalid\"; output += stack.pop(); } return output; } // Main driver code public static void main(String[] args) { // Considering random infix string notation String expression = \"5+2/(3-8)^5^2\"; // Printing RPN for the above infix notation // Illustrating shunting yard algorithm System.out.println(infixToRpn(expression)); }}",
"e": 30842,
"s": 27398,
"text": null
},
{
"code": null,
"e": 30855,
"s": 30842,
"text": "5238-52^^/+\n"
},
{
"code": null,
"e": 30992,
"s": 30855,
"text": "Time Complexity: O(n) This algorithm takes linear time, as we only traverse through the expression once and pop and push only take O(1)."
},
{
"code": null,
"e": 31083,
"s": 30992,
"text": "Space Complexity: O(n) as we use a stack of size n, where n is length given of expression."
},
{
"code": null,
"e": 31093,
"s": 31085,
"text": "clintra"
},
{
"code": null,
"e": 31109,
"s": 31093,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 31118,
"s": 31109,
"text": "sweetyty"
},
{
"code": null,
"e": 31159,
"s": 31118,
"text": "tft035wt51sbq899304l51d13igth0s9g558p7k2"
},
{
"code": null,
"e": 31166,
"s": 31159,
"text": "Picked"
},
{
"code": null,
"e": 31190,
"s": 31166,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31195,
"s": 31190,
"text": "Java"
},
{
"code": null,
"e": 31209,
"s": 31195,
"text": "Java Programs"
},
{
"code": null,
"e": 31228,
"s": 31209,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31233,
"s": 31228,
"text": "Java"
},
{
"code": null,
"e": 31331,
"s": 31233,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31340,
"s": 31331,
"text": "Comments"
},
{
"code": null,
"e": 31353,
"s": 31340,
"text": "Old Comments"
},
{
"code": null,
"e": 31371,
"s": 31353,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 31392,
"s": 31371,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31438,
"s": 31392,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31481,
"s": 31438,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31521,
"s": 31481,
"text": "Java Math random() method with Examples"
},
{
"code": null,
"e": 31565,
"s": 31521,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 31591,
"s": 31565,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31623,
"s": 31591,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 31670,
"s": 31623,
"text": "Implementing a Linked List in Java using Class"
}
] |
Draw ellipse in C graphics - GeeksforGeeks | 06 Dec, 2019
Program to draw ellipse in C using graphics.h header file.graphics.h library is used to include and facilitate graphical operations in program. C graphics using graphics.h functions can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h you can make graphics programs, animations, projects and games. You can draw circles, lines, rectangles, bars and many other geometrical figures. You can change their colors using the available functions and fill them.Examples:
Input : x=250, y=200, start_angle = 0,
end_angle = 360, x_rad = 100, y_rad = 50
Output :
Input : x=250, y=200, start_angle = 0,
end_angle = 180, x_rad = 80, y_rad = 150
Output :
Explanation :The header file graphics.h contains ellipse() function which is described below :
void ellipse(int x, int y, int start_angle, int end_angle, int x_radius, int y_radius)
In this function x, y is the location of the ellipse. x_radius and y_radius decide the radius of form x and y.start_angle is the starting point of angle and end_angle is the ending point of angle. The value of angle can vary from 0 to 360 degree.
// C Implementation for drawing ellipse#include <graphics.h> int main(){ // gm is Graphics mode which is a computer display // mode that generates image using pixels. // DETECT is a macro defined in "graphics.h" header file int gd = DETECT, gm; // location of ellipse int x = 250, y = 200; // here is the starting angle // and end angle int start_angle = 0; int end_angle = 360; // radius from x axis and y axis int x_rad = 100; int y_rad = 50; // initgraph initializes the graphics system // by loading a graphics driver from disk initgraph(&gd, &gm, ""); // ellipse function ellipse(x, y, start_angle, end_angle, x_rad, y_rad); getch(); // closegraph function closes the graphics // mode and deallocates all memory allocated // by graphics system . closegraph(); return 0;}
Output:
Akanksha_Rai
computer-graphics
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
Program to print ASCII Value of a character
C program to sort an array in ascending order
Program to find Prime Numbers Between given Interval
time() function in C
Flex (Fast Lexical Analyzer Generator )
C Program to Swap two Numbers | [
{
"code": null,
"e": 24204,
"s": 24176,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 24744,
"s": 24204,
"text": "Program to draw ellipse in C using graphics.h header file.graphics.h library is used to include and facilitate graphical operations in program. C graphics using graphics.h functions can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h you can make graphics programs, animations, projects and games. You can draw circles, lines, rectangles, bars and many other geometrical figures. You can change their colors using the available functions and fill them.Examples:"
},
{
"code": null,
"e": 24943,
"s": 24744,
"text": "Input : x=250, y=200, start_angle = 0,\n end_angle = 360, x_rad = 100, y_rad = 50\nOutput :\n\n\nInput : x=250, y=200, start_angle = 0, \n end_angle = 180, x_rad = 80, y_rad = 150\nOutput :\n\n"
},
{
"code": null,
"e": 25038,
"s": 24943,
"text": "Explanation :The header file graphics.h contains ellipse() function which is described below :"
},
{
"code": null,
"e": 25125,
"s": 25038,
"text": "void ellipse(int x, int y, int start_angle, int end_angle, int x_radius, int y_radius)"
},
{
"code": null,
"e": 25372,
"s": 25125,
"text": "In this function x, y is the location of the ellipse. x_radius and y_radius decide the radius of form x and y.start_angle is the starting point of angle and end_angle is the ending point of angle. The value of angle can vary from 0 to 360 degree."
},
{
"code": "// C Implementation for drawing ellipse#include <graphics.h> int main(){ // gm is Graphics mode which is a computer display // mode that generates image using pixels. // DETECT is a macro defined in \"graphics.h\" header file int gd = DETECT, gm; // location of ellipse int x = 250, y = 200; // here is the starting angle // and end angle int start_angle = 0; int end_angle = 360; // radius from x axis and y axis int x_rad = 100; int y_rad = 50; // initgraph initializes the graphics system // by loading a graphics driver from disk initgraph(&gd, &gm, \"\"); // ellipse function ellipse(x, y, start_angle, end_angle, x_rad, y_rad); getch(); // closegraph function closes the graphics // mode and deallocates all memory allocated // by graphics system . closegraph(); return 0;}",
"e": 26241,
"s": 25372,
"text": null
},
{
"code": null,
"e": 26249,
"s": 26241,
"text": "Output:"
},
{
"code": null,
"e": 26264,
"s": 26251,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26282,
"s": 26264,
"text": "computer-graphics"
},
{
"code": null,
"e": 26293,
"s": 26282,
"text": "C Programs"
},
{
"code": null,
"e": 26391,
"s": 26293,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26400,
"s": 26391,
"text": "Comments"
},
{
"code": null,
"e": 26413,
"s": 26400,
"text": "Old Comments"
},
{
"code": null,
"e": 26454,
"s": 26413,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 26489,
"s": 26454,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 26548,
"s": 26489,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 26591,
"s": 26548,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 26635,
"s": 26591,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 26681,
"s": 26635,
"text": "C program to sort an array in ascending order"
},
{
"code": null,
"e": 26734,
"s": 26681,
"text": "Program to find Prime Numbers Between given Interval"
},
{
"code": null,
"e": 26755,
"s": 26734,
"text": "time() function in C"
},
{
"code": null,
"e": 26795,
"s": 26755,
"text": "Flex (Fast Lexical Analyzer Generator )"
}
] |
Print system time in C++ (3 different ways) | There are different ways by which system day, date and time can be printed in Human Readable Form.
Using time() − It is used to find the current calendar time and have arithmetic data type that store timelocaltime() − It is used to fill the structure with date and timeasctime() − It converts Local time into Human Readable Format
Day Month Date hour:month:second Year
#include<iostream>
#include<ctime> // used to work with date and time
using namespace std;
int main() {
time_t t; // t passed as argument in function time()
struct tm * tt; // decalring variable for localtime()
time (&t); //passing argument to time()
tt = localtime(&t);
cout << "Current Day, Date and Time is = "<< asctime(tt);
return 0;
}
if we run the above program then it will generate the following output
Current Day, Date and Time is = Tue Jul 23 19:05:50 2019
Chrono library is used to measure elapsed time in seconds, milliseconds, microseconds and nanoseconds
#include <chrono>
#include <ctime>
#include <iostream>
Using namespace std;
int main() {
auto givemetime = chrono::system_clock::to_time_t(chrono::system_clock::now());
cout << ctime(&givemetime) << endl;
}
if we run the above program then it will generate the following output
Current Day, Date and Time is = Tue Jul 23 19:05:50 2019
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
time_t givemetime = time(NULL);
printf("%s", ctime(&givemetime)); //ctime() returns given time
return 0;
}
if we run the above program then it will generate the following output
Tue Jul 23 20:14:42 2019 | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "There are different ways by which system day, date and time can be printed in Human Readable Form."
},
{
"code": null,
"e": 1393,
"s": 1161,
"text": "Using time() − It is used to find the current calendar time and have arithmetic data type that store timelocaltime() − It is used to fill the structure with date and timeasctime() − It converts Local time into Human Readable Format"
},
{
"code": null,
"e": 1431,
"s": 1393,
"text": "Day Month Date hour:month:second Year"
},
{
"code": null,
"e": 1790,
"s": 1431,
"text": "#include<iostream>\n#include<ctime> // used to work with date and time\nusing namespace std;\nint main() {\n time_t t; // t passed as argument in function time()\n struct tm * tt; // decalring variable for localtime()\n time (&t); //passing argument to time()\n tt = localtime(&t);\n cout << \"Current Day, Date and Time is = \"<< asctime(tt);\n return 0;\n}"
},
{
"code": null,
"e": 1861,
"s": 1790,
"text": "if we run the above program then it will generate the following output"
},
{
"code": null,
"e": 1918,
"s": 1861,
"text": "Current Day, Date and Time is = Tue Jul 23 19:05:50 2019"
},
{
"code": null,
"e": 2020,
"s": 1918,
"text": "Chrono library is used to measure elapsed time in seconds, milliseconds, microseconds and nanoseconds"
},
{
"code": null,
"e": 2233,
"s": 2020,
"text": "#include <chrono>\n#include <ctime>\n#include <iostream>\nUsing namespace std;\nint main() {\n auto givemetime = chrono::system_clock::to_time_t(chrono::system_clock::now());\n cout << ctime(&givemetime) << endl;\n}"
},
{
"code": null,
"e": 2304,
"s": 2233,
"text": "if we run the above program then it will generate the following output"
},
{
"code": null,
"e": 2361,
"s": 2304,
"text": "Current Day, Date and Time is = Tue Jul 23 19:05:50 2019"
},
{
"code": null,
"e": 2547,
"s": 2361,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\nint main() {\n time_t givemetime = time(NULL);\n printf(\"%s\", ctime(&givemetime)); //ctime() returns given time\n return 0;\n}"
},
{
"code": null,
"e": 2618,
"s": 2547,
"text": "if we run the above program then it will generate the following output"
},
{
"code": null,
"e": 2643,
"s": 2618,
"text": "Tue Jul 23 20:14:42 2019"
}
] |
Replace string in SQL Server - GeeksforGeeks | 27 Nov, 2020
Let us suppose we need to update or replace any string value in any table, we could use the below methods –
Replace String in SQL Server Example :In below example, we have a string variable, and then we are going to replace a part of a string with a new string using the Replace Function.
SQL Server Query to Replace String –
DECLARE @String_Value varchar(50)
SET @String_Value = 'This provides free and excellent knowledge on SQL Server.'
SELECT REPLACE (@String_Value, 'This', 'Geeksforgeeks');
Output :
Geeksforgeeks provides free and excellent knowledge on SQL Server.
Let us suppose we have below table named “geek_demo” :
Replace String Example :In below example, we will replace a string in SQL Server SELECT Statement using the REPLACE Function while selecting data from the SQL Server table.
SQL Server Query to replace part of a string –
SELECT TOP 1000 [Name], [Salary], [City], [email],
REPLACE([email], 'xyz.com', 'gfg.org') AS [New EmailID]
FROM [geek_demo]
Output :
Replace String in SQL Example :In the below example, we will replace string in SQL UPDATE Statement using the REPLACE Function in Update Statement.
SQL Server Query to replace part of a string –
UPDATE [geek_demo]
SET [email] = REPLACE([email], 'xyz.com', 'gfg.org');
Result :
(8 row(s) affected)
Now let us see the Updated table –
SELECT TOP 1000 [Name], [Salary], [City], [email]
FROM [geek_demo];
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Composite Key in SQL
SQL using Python
SQL | DROP, TRUNCATE
SQL indexes
SQL | Date functions
What is Temporary Table in SQL?
Window functions in SQL
How to Concat Two Columns Into One With the Existing Column Name in MySQL? | [
{
"code": null,
"e": 23877,
"s": 23849,
"text": "\n27 Nov, 2020"
},
{
"code": null,
"e": 23985,
"s": 23877,
"text": "Let us suppose we need to update or replace any string value in any table, we could use the below methods –"
},
{
"code": null,
"e": 24166,
"s": 23985,
"text": "Replace String in SQL Server Example :In below example, we have a string variable, and then we are going to replace a part of a string with a new string using the Replace Function."
},
{
"code": null,
"e": 24203,
"s": 24166,
"text": "SQL Server Query to Replace String –"
},
{
"code": null,
"e": 24374,
"s": 24203,
"text": "DECLARE @String_Value varchar(50)\nSET @String_Value = 'This provides free and excellent knowledge on SQL Server.'\nSELECT REPLACE (@String_Value, 'This', 'Geeksforgeeks');"
},
{
"code": null,
"e": 24383,
"s": 24374,
"text": "Output :"
},
{
"code": null,
"e": 24450,
"s": 24383,
"text": "Geeksforgeeks provides free and excellent knowledge on SQL Server."
},
{
"code": null,
"e": 24505,
"s": 24450,
"text": "Let us suppose we have below table named “geek_demo” :"
},
{
"code": null,
"e": 24678,
"s": 24505,
"text": "Replace String Example :In below example, we will replace a string in SQL Server SELECT Statement using the REPLACE Function while selecting data from the SQL Server table."
},
{
"code": null,
"e": 24725,
"s": 24678,
"text": "SQL Server Query to replace part of a string –"
},
{
"code": null,
"e": 24850,
"s": 24725,
"text": "SELECT TOP 1000 [Name], [Salary], [City], [email], \nREPLACE([email], 'xyz.com', 'gfg.org') AS [New EmailID]\nFROM [geek_demo]"
},
{
"code": null,
"e": 24859,
"s": 24850,
"text": "Output :"
},
{
"code": null,
"e": 25007,
"s": 24859,
"text": "Replace String in SQL Example :In the below example, we will replace string in SQL UPDATE Statement using the REPLACE Function in Update Statement."
},
{
"code": null,
"e": 25054,
"s": 25007,
"text": "SQL Server Query to replace part of a string –"
},
{
"code": null,
"e": 25127,
"s": 25054,
"text": "UPDATE [geek_demo]\nSET [email] = REPLACE([email], 'xyz.com', 'gfg.org');"
},
{
"code": null,
"e": 25136,
"s": 25127,
"text": "Result :"
},
{
"code": null,
"e": 25156,
"s": 25136,
"text": "(8 row(s) affected)"
},
{
"code": null,
"e": 25191,
"s": 25156,
"text": "Now let us see the Updated table –"
},
{
"code": null,
"e": 25259,
"s": 25191,
"text": "SELECT TOP 1000 [Name], [Salary], [City], [email]\nFROM [geek_demo];"
},
{
"code": null,
"e": 25268,
"s": 25259,
"text": "Output :"
},
{
"code": null,
"e": 25277,
"s": 25268,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 25288,
"s": 25277,
"text": "SQL-Server"
},
{
"code": null,
"e": 25292,
"s": 25288,
"text": "SQL"
},
{
"code": null,
"e": 25296,
"s": 25292,
"text": "SQL"
},
{
"code": null,
"e": 25394,
"s": 25296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25403,
"s": 25394,
"text": "Comments"
},
{
"code": null,
"e": 25416,
"s": 25403,
"text": "Old Comments"
},
{
"code": null,
"e": 25482,
"s": 25416,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 25560,
"s": 25482,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 25581,
"s": 25560,
"text": "Composite Key in SQL"
},
{
"code": null,
"e": 25598,
"s": 25581,
"text": "SQL using Python"
},
{
"code": null,
"e": 25619,
"s": 25598,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 25631,
"s": 25619,
"text": "SQL indexes"
},
{
"code": null,
"e": 25652,
"s": 25631,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 25684,
"s": 25652,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 25708,
"s": 25684,
"text": "Window functions in SQL"
}
] |
What is a Domain Name System? | The acronym for Domain Name System is DNS. It is a naming system that works hierarchically and is decentralized for computers, servers (web servers), services, resources, network devices and components that are present on large networks such as the public Internet.
For example, in layman terms, it is a phonebook for computers on the Internet.
It translates and maps alphabetic domain names (websites' web addresses or names) to the numeric Internet Protocol (IP) addresses of computers or servers. And it also does the reverse process. DNS uses User Datagram Protocol (UDP). DNS service uses port number 53.
Technically, computers or technically the routers (default gateway) use DNS servers to contact to get any domains translated and converted to an IP address of the server hosting a website. The entry for DNS servers could be few or many, as there would be multiple DNS servers. The examples are OpenDNS servers, or Google DNS servers.
It is a system that uses at least one DNS server to resolve DNS-names. DNS is used because computers and servers do not understand human-readable alphabetic domain names, where humans do not understand and remember numeric IP addresses, which the computers and servers can.
DNS service or server is an Internet service in general, thus maps or translates human readable domain names (website names or URL, Uniform Resource Locator) into machine or Computer readable IP (Internet Protocol) addresses.
Domain name = www.example.com whose Server IP address is,
say = 253.136.27.2
The working of DNS is explained below in stepwise manner −
Step 1 − Every website has a domain name/ IP address associated with it.
Step 2 − Now IP is a bit complicated to share (as no one wants to write 192.168.224.23 or some random IP to access Tutorials point) so people came up with an idea of domain names which basically stores the IP address mapped to their name.
Step 3 − Now, a DNS translates every domain name to its IP address so every browser can access that particular website.
Step 4 − DNS has eased the process of web surfing as we write tutorialspoint.com to reach a website instead of some complicated 32-128 bit address.
Given below is the diagram of DNS − | [
{
"code": null,
"e": 1328,
"s": 1062,
"text": "The acronym for Domain Name System is DNS. It is a naming system that works hierarchically and is decentralized for computers, servers (web servers), services, resources, network devices and components that are present on large networks such as the public Internet."
},
{
"code": null,
"e": 1407,
"s": 1328,
"text": "For example, in layman terms, it is a phonebook for computers on the Internet."
},
{
"code": null,
"e": 1672,
"s": 1407,
"text": "It translates and maps alphabetic domain names (websites' web addresses or names) to the numeric Internet Protocol (IP) addresses of computers or servers. And it also does the reverse process. DNS uses User Datagram Protocol (UDP). DNS service uses port number 53."
},
{
"code": null,
"e": 2006,
"s": 1672,
"text": "Technically, computers or technically the routers (default gateway) use DNS servers to contact to get any domains translated and converted to an IP address of the server hosting a website. The entry for DNS servers could be few or many, as there would be multiple DNS servers. The examples are OpenDNS servers, or Google DNS servers."
},
{
"code": null,
"e": 2280,
"s": 2006,
"text": "It is a system that uses at least one DNS server to resolve DNS-names. DNS is used because computers and servers do not understand human-readable alphabetic domain names, where humans do not understand and remember numeric IP addresses, which the computers and servers can."
},
{
"code": null,
"e": 2506,
"s": 2280,
"text": "DNS service or server is an Internet service in general, thus maps or translates human readable domain names (website names or URL, Uniform Resource Locator) into machine or Computer readable IP (Internet Protocol) addresses."
},
{
"code": null,
"e": 2564,
"s": 2506,
"text": "Domain name = www.example.com whose Server IP address is,"
},
{
"code": null,
"e": 2583,
"s": 2564,
"text": "say = 253.136.27.2"
},
{
"code": null,
"e": 2642,
"s": 2583,
"text": "The working of DNS is explained below in stepwise manner −"
},
{
"code": null,
"e": 2715,
"s": 2642,
"text": "Step 1 − Every website has a domain name/ IP address associated with it."
},
{
"code": null,
"e": 2954,
"s": 2715,
"text": "Step 2 − Now IP is a bit complicated to share (as no one wants to write 192.168.224.23 or some random IP to access Tutorials point) so people came up with an idea of domain names which basically stores the IP address mapped to their name."
},
{
"code": null,
"e": 3074,
"s": 2954,
"text": "Step 3 − Now, a DNS translates every domain name to its IP address so every browser can access that particular website."
},
{
"code": null,
"e": 3222,
"s": 3074,
"text": "Step 4 − DNS has eased the process of web surfing as we write tutorialspoint.com to reach a website instead of some complicated 32-128 bit address."
},
{
"code": null,
"e": 3258,
"s": 3222,
"text": "Given below is the diagram of DNS −"
}
] |
Coin Change 2 in C++ | Suppose we have coins of different denominations and a total amount of money. we have to Write a module to compute the number of combinations that make up that amount. we can assume that we have infinite number of each kind of coin. So if the amount is 5 and coins are [1, 2, 5], then there are four combinations. (1+1+1+1+1), (1+1+1+2), (1+2+2), (5)
To solve this, we will follow these steps −
create one array dp of size amount + 1
dp[0] := 1
n := size of coins array
for i in range 0 to n – 1for j in range coins[i] to amountdp[j] := dp[j – coins[i]]
for j in range coins[i] to amountdp[j] := dp[j – coins[i]]
dp[j] := dp[j – coins[i]]
return dp[amount]
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int change(int amount, vector<int>& coins) {
vector <int> dp(amount + 1);
dp[0] = 1;
int n = coins.size();
for(int i = 0; i < n; i++){
for(int j = coins[i]; j <= amount; j++){
dp[j] += dp[j - coins[i]];
}
}
return dp[amount];
}
};
main(){
Solution ob;
vector<int> v = {1,2,5};
cout << (ob.change(5, v));
}
5
[1,2,5]
4 | [
{
"code": null,
"e": 1413,
"s": 1062,
"text": "Suppose we have coins of different denominations and a total amount of money. we have to Write a module to compute the number of combinations that make up that amount. we can assume that we have infinite number of each kind of coin. So if the amount is 5 and coins are [1, 2, 5], then there are four combinations. (1+1+1+1+1), (1+1+1+2), (1+2+2), (5)"
},
{
"code": null,
"e": 1457,
"s": 1413,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1496,
"s": 1457,
"text": "create one array dp of size amount + 1"
},
{
"code": null,
"e": 1507,
"s": 1496,
"text": "dp[0] := 1"
},
{
"code": null,
"e": 1532,
"s": 1507,
"text": "n := size of coins array"
},
{
"code": null,
"e": 1616,
"s": 1532,
"text": "for i in range 0 to n – 1for j in range coins[i] to amountdp[j] := dp[j – coins[i]]"
},
{
"code": null,
"e": 1675,
"s": 1616,
"text": "for j in range coins[i] to amountdp[j] := dp[j – coins[i]]"
},
{
"code": null,
"e": 1701,
"s": 1675,
"text": "dp[j] := dp[j – coins[i]]"
},
{
"code": null,
"e": 1719,
"s": 1701,
"text": "return dp[amount]"
},
{
"code": null,
"e": 1789,
"s": 1719,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1800,
"s": 1789,
"text": " Live Demo"
},
{
"code": null,
"e": 2258,
"s": 1800,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int change(int amount, vector<int>& coins) {\n vector <int> dp(amount + 1);\n dp[0] = 1;\n int n = coins.size();\n for(int i = 0; i < n; i++){\n for(int j = coins[i]; j <= amount; j++){\n dp[j] += dp[j - coins[i]];\n }\n }\n return dp[amount];\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,2,5};\n cout << (ob.change(5, v));\n}"
},
{
"code": null,
"e": 2268,
"s": 2258,
"text": "5\n[1,2,5]"
},
{
"code": null,
"e": 2270,
"s": 2268,
"text": "4"
}
] |
How to change the font color of a text using JavaScript? | To change the font color of a text, use the fontcolor() method. This method causes a string to be displayed in the specified color as if it were in a <font color="color"> tag.
You can try to run the following code to change the font color of a text using JavaScript −
Live Demo
<html>
<head>
<title>JavaScript String fontcolor() Method</title>
</head>
<body>
<script>
var str = new String("Demo Text");
document.write(str.fontcolor( "blue" ));
alert(str.fontcolor( "blue" ));
</script>
</body>
</html> | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "To change the font color of a text, use the fontcolor() method. This method causes a string to be displayed in the specified color as if it were in a <font color=\"color\"> tag. "
},
{
"code": null,
"e": 1331,
"s": 1239,
"text": "You can try to run the following code to change the font color of a text using JavaScript −"
},
{
"code": null,
"e": 1341,
"s": 1331,
"text": "Live Demo"
},
{
"code": null,
"e": 1623,
"s": 1341,
"text": "<html>\n <head>\n <title>JavaScript String fontcolor() Method</title>\n </head>\n\n <body>\n <script>\n var str = new String(\"Demo Text\");\n document.write(str.fontcolor( \"blue\" ));\n alert(str.fontcolor( \"blue\" ));\n </script>\n </body>\n</html>"
}
] |
Build a Social Media Website with Django- Part 2 | Towards Data Science | So, in the first part of the tutorial, we learnt how to set up our project and setup various authentication backends and other details regarding various installs and app setups needed in the settings file.
If you have not read the first part yet, make sure to complete it first before moving forward as we would be building on top of that in this part.
There would be lots of terms which you may be encountering for the first time, like you may have heard about views or models for the first time, so I would be briefing about them a little. I cannot talk about those in details because our focus is not to teach you basic concepts, but to build a social media website. So, I would be linking to good resources for you to refer to those specific topics and then continue with this tutorial.
So, let’s go ahead and build the Users app we created in the last tutorial. We will start by creating the models first.
In this python file, we will define our models. As you might already know, models are defined to tell Django what to save in the database and to define the relationship between different models and what characteristics they have.
To learn more about Django models, do visit this amazing tutorial on models by Mozilla Developers. It talks about models in depth.
After you are comfortable with how models work, you can proceed to make models for our social media website.
So, we will have two models — one for the user’s profile and the other for Friend Requests.
We will need to import many things before we begin writing the models. We will be using the Default User model of Django to have One to One Relationship with our Profile Model i.e. each user will have one profile.
We are also using autoslug to automatically produce slugs for the URLs based on the username.
For e.g.: A user with the name Tom would have slug as tom. This will help us make meaningful URLs as users/tom will lead to Tom’s profile rather than numbers.
So, to use autoslug we need to install it first. It can be done via a simple pip install. Refer below:
pip install django-autoslug
Also we will need to install the pillow library to handle the images in Profile model.
pip install pillow
After installing it, we can import it in models.py by using the line:
from autoslug import AutoSlugField
After finishing off all the required imports, we can begin writing the models.
So, our first model is the Profile model. It has five parameters:-
user — This is a One to One Relationship with Django User model. The on_delete=models.CASCADE means on the deletion of User, we destroy the Profile too.image — This will store the profile picture of the user. We have provided a default image also. We need to define where to save the pictures.slug — This will be the slug field. We use the AutoSlugField and will set it to make slug from the user field.bio — This will store the small introduction about the user. Here, blank=True means it can be left blank.friends — This is a Many to Many Field with Profile model and can be left blank. It means every user can have multiple friends and can be friends to multiple people.
user — This is a One to One Relationship with Django User model. The on_delete=models.CASCADE means on the deletion of User, we destroy the Profile too.
image — This will store the profile picture of the user. We have provided a default image also. We need to define where to save the pictures.
slug — This will be the slug field. We use the AutoSlugField and will set it to make slug from the user field.
bio — This will store the small introduction about the user. Here, blank=True means it can be left blank.
friends — This is a Many to Many Field with Profile model and can be left blank. It means every user can have multiple friends and can be friends to multiple people.
Next, we describe the __str__ which decides how Django will show our model in the admin panel. We have set it to show the username as the Query object.
We also define the get_absolute_url to get the absolute URL for that profile.
Next, we define a function to make a profile as soon as we create the user so that the user doesn't have to manually create a profile.
Next, we define our Friends Model. It will have three parameters:-
to_user — This denotes the user to whom the friend request will be sent. It will have the same on_delete parameter which decides when the user is deleted, we delete the friend request too.from_user — This denotes the user who is sending the friend request. It will also be deleted if the user is deleted.timestamp — It is not really necessary to add. It stores the time when the request was sent.
to_user — This denotes the user to whom the friend request will be sent. It will have the same on_delete parameter which decides when the user is deleted, we delete the friend request too.
from_user — This denotes the user who is sending the friend request. It will also be deleted if the user is deleted.
timestamp — It is not really necessary to add. It stores the time when the request was sent.
As you can notice both to_user and from_user uses the same ForeignKey so to differentiate we need to use the related_name field.
So, that finishes our models.py file. Have a look at the code below which shows the models.py file.
After models.py file, we move forward to admin.py file.
It will be short and it will consist of a few lines only. It denotes the models which we will be registering to our admin panel. We will be registering both our models here.
Next, we move to forms.py.
To know more about working of forms in Django, do visit this official tutorial by Django itself. Then proceed into the tutorial.
We define three forms in our forms.py file.
UserRegisterForm — This is for registration of a new user. We user the Django’s default UserCreationForm and we define what should be in the forms. We set the email to be Django’s EmailField. Then we tell Django that model is User and the fields that we would ask the user to fill while registering.UserUpdateForm — This form will let users update their profile. It will have all the same fields as Registration form but we would use the Django Model form instead of UserCreationForm.ProfileUpdateForm — This form will let users update their profile.
UserRegisterForm — This is for registration of a new user. We user the Django’s default UserCreationForm and we define what should be in the forms. We set the email to be Django’s EmailField. Then we tell Django that model is User and the fields that we would ask the user to fill while registering.
UserUpdateForm — This form will let users update their profile. It will have all the same fields as Registration form but we would use the Django Model form instead of UserCreationForm.
ProfileUpdateForm — This form will let users update their profile.
So, adding these three forms would complete our forms.py file. Look at the code below:
So, after this, we have our forms.py file created. Next, we would be seeing views.py file.
Now, we will define the views.py file. It would contain all our views (how to render the files in the web browser). It directly passes data to the templates.
Read this official tutorial by Django to understand views in a better way. After reading the tutorial, we move forward.
Since the views file is too large, we can make it as we like, so I would give a simple overview of what each view does, and you can read the code below for better understanding. So, let’s go through them one by one:
users_list — This view will form the user list to be recommended to any user to help them discover new users to make friends with. We will filter out our friends from that list and will exclude us too. We will make this list by first adding our friend’s friends who are not our friends. Then if our user list has still low members, we will add random people to recommend (mostly for a user with no friends).friend_list — This view will display all the friends of the user.send_friend_request — This will help us create a friend request instance and will send a request to the user. We take in the id the user we are sending a request to so that we can send him the request.cancel_friend_request — It will cancel the friend request we sent to the user.accept_friend_request — It will be used to accept the friend request of the user and we add user1 to user2’s friend list and vice versa. Also, we will delete the friend request.delete_friend_request — It will allow the user to delete any friend request he/she has received.delete_friend — This will delete the friend of that user i.e. we would remove user1 from user2 friend list and vice versa.profile_view — This will be the profile view of any user. It will showcase the friend's count and posts count of the user and their friend list. Also, it would showcase the friend request received and sent by the user and can accept, decline or cancel the request. Obviously, we would add conditions and checks, so that only the concerned user is shown the requests and sent list and they only have the power to accept or reject requests and not anyone viewing his/her profile.register — This will let users register on our website. It will render the registration form we created in forms.py file.edit_profile — This will let the users edit their profile with help of the forms we created.search_users — This will handle the search function of the users. It takes in the query and then filters out relevant users.my_profile — This is same as profile_view but it will render your profile only.
users_list — This view will form the user list to be recommended to any user to help them discover new users to make friends with. We will filter out our friends from that list and will exclude us too. We will make this list by first adding our friend’s friends who are not our friends. Then if our user list has still low members, we will add random people to recommend (mostly for a user with no friends).
friend_list — This view will display all the friends of the user.
send_friend_request — This will help us create a friend request instance and will send a request to the user. We take in the id the user we are sending a request to so that we can send him the request.
cancel_friend_request — It will cancel the friend request we sent to the user.
accept_friend_request — It will be used to accept the friend request of the user and we add user1 to user2’s friend list and vice versa. Also, we will delete the friend request.
delete_friend_request — It will allow the user to delete any friend request he/she has received.
delete_friend — This will delete the friend of that user i.e. we would remove user1 from user2 friend list and vice versa.
profile_view — This will be the profile view of any user. It will showcase the friend's count and posts count of the user and their friend list. Also, it would showcase the friend request received and sent by the user and can accept, decline or cancel the request. Obviously, we would add conditions and checks, so that only the concerned user is shown the requests and sent list and they only have the power to accept or reject requests and not anyone viewing his/her profile.
register — This will let users register on our website. It will render the registration form we created in forms.py file.
edit_profile — This will let the users edit their profile with help of the forms we created.
search_users — This will handle the search function of the users. It takes in the query and then filters out relevant users.
my_profile — This is same as profile_view but it will render your profile only.
Go through the code below for better understanding.
It sums up our Users app. We are left with the urls.py which we won’t include in users app. We will add it directly to our photoshare app.
You can view this simple tutorial to understand more about URLs in Django.
This file contains all the URLs for the website. It has an include(‘feed.urls’) which includes all URLs from the Feed app which we will build in the next tutorial.
And we include all the URLs for the photoshare app directly in the main urls.py file. Have a look at the file below:
If you would like to see the complete code, view the project’s Github Repo. Also, you can try out this app by visiting this link. It is hosted on Heroku and the media and static files on Google Cloud Storage.
A similar Django focused series (Building a Job Search Portal) which will teach you some amazing new concepts is:
shubhamstudent5.medium.com
The next part of this tutorial is:
medium.com
shubhamstudent5.medium.com
towardsdatascience.com
A collection of resources to learn Web Development can be found here:- | [
{
"code": null,
"e": 377,
"s": 171,
"text": "So, in the first part of the tutorial, we learnt how to set up our project and setup various authentication backends and other details regarding various installs and app setups needed in the settings file."
},
{
"code": null,
"e": 524,
"s": 377,
"text": "If you have not read the first part yet, make sure to complete it first before moving forward as we would be building on top of that in this part."
},
{
"code": null,
"e": 962,
"s": 524,
"text": "There would be lots of terms which you may be encountering for the first time, like you may have heard about views or models for the first time, so I would be briefing about them a little. I cannot talk about those in details because our focus is not to teach you basic concepts, but to build a social media website. So, I would be linking to good resources for you to refer to those specific topics and then continue with this tutorial."
},
{
"code": null,
"e": 1082,
"s": 962,
"text": "So, let’s go ahead and build the Users app we created in the last tutorial. We will start by creating the models first."
},
{
"code": null,
"e": 1312,
"s": 1082,
"text": "In this python file, we will define our models. As you might already know, models are defined to tell Django what to save in the database and to define the relationship between different models and what characteristics they have."
},
{
"code": null,
"e": 1443,
"s": 1312,
"text": "To learn more about Django models, do visit this amazing tutorial on models by Mozilla Developers. It talks about models in depth."
},
{
"code": null,
"e": 1552,
"s": 1443,
"text": "After you are comfortable with how models work, you can proceed to make models for our social media website."
},
{
"code": null,
"e": 1644,
"s": 1552,
"text": "So, we will have two models — one for the user’s profile and the other for Friend Requests."
},
{
"code": null,
"e": 1858,
"s": 1644,
"text": "We will need to import many things before we begin writing the models. We will be using the Default User model of Django to have One to One Relationship with our Profile Model i.e. each user will have one profile."
},
{
"code": null,
"e": 1952,
"s": 1858,
"text": "We are also using autoslug to automatically produce slugs for the URLs based on the username."
},
{
"code": null,
"e": 2111,
"s": 1952,
"text": "For e.g.: A user with the name Tom would have slug as tom. This will help us make meaningful URLs as users/tom will lead to Tom’s profile rather than numbers."
},
{
"code": null,
"e": 2214,
"s": 2111,
"text": "So, to use autoslug we need to install it first. It can be done via a simple pip install. Refer below:"
},
{
"code": null,
"e": 2242,
"s": 2214,
"text": "pip install django-autoslug"
},
{
"code": null,
"e": 2329,
"s": 2242,
"text": "Also we will need to install the pillow library to handle the images in Profile model."
},
{
"code": null,
"e": 2348,
"s": 2329,
"text": "pip install pillow"
},
{
"code": null,
"e": 2418,
"s": 2348,
"text": "After installing it, we can import it in models.py by using the line:"
},
{
"code": null,
"e": 2453,
"s": 2418,
"text": "from autoslug import AutoSlugField"
},
{
"code": null,
"e": 2532,
"s": 2453,
"text": "After finishing off all the required imports, we can begin writing the models."
},
{
"code": null,
"e": 2599,
"s": 2532,
"text": "So, our first model is the Profile model. It has five parameters:-"
},
{
"code": null,
"e": 3273,
"s": 2599,
"text": "user — This is a One to One Relationship with Django User model. The on_delete=models.CASCADE means on the deletion of User, we destroy the Profile too.image — This will store the profile picture of the user. We have provided a default image also. We need to define where to save the pictures.slug — This will be the slug field. We use the AutoSlugField and will set it to make slug from the user field.bio — This will store the small introduction about the user. Here, blank=True means it can be left blank.friends — This is a Many to Many Field with Profile model and can be left blank. It means every user can have multiple friends and can be friends to multiple people."
},
{
"code": null,
"e": 3426,
"s": 3273,
"text": "user — This is a One to One Relationship with Django User model. The on_delete=models.CASCADE means on the deletion of User, we destroy the Profile too."
},
{
"code": null,
"e": 3568,
"s": 3426,
"text": "image — This will store the profile picture of the user. We have provided a default image also. We need to define where to save the pictures."
},
{
"code": null,
"e": 3679,
"s": 3568,
"text": "slug — This will be the slug field. We use the AutoSlugField and will set it to make slug from the user field."
},
{
"code": null,
"e": 3785,
"s": 3679,
"text": "bio — This will store the small introduction about the user. Here, blank=True means it can be left blank."
},
{
"code": null,
"e": 3951,
"s": 3785,
"text": "friends — This is a Many to Many Field with Profile model and can be left blank. It means every user can have multiple friends and can be friends to multiple people."
},
{
"code": null,
"e": 4103,
"s": 3951,
"text": "Next, we describe the __str__ which decides how Django will show our model in the admin panel. We have set it to show the username as the Query object."
},
{
"code": null,
"e": 4181,
"s": 4103,
"text": "We also define the get_absolute_url to get the absolute URL for that profile."
},
{
"code": null,
"e": 4316,
"s": 4181,
"text": "Next, we define a function to make a profile as soon as we create the user so that the user doesn't have to manually create a profile."
},
{
"code": null,
"e": 4383,
"s": 4316,
"text": "Next, we define our Friends Model. It will have three parameters:-"
},
{
"code": null,
"e": 4780,
"s": 4383,
"text": "to_user — This denotes the user to whom the friend request will be sent. It will have the same on_delete parameter which decides when the user is deleted, we delete the friend request too.from_user — This denotes the user who is sending the friend request. It will also be deleted if the user is deleted.timestamp — It is not really necessary to add. It stores the time when the request was sent."
},
{
"code": null,
"e": 4969,
"s": 4780,
"text": "to_user — This denotes the user to whom the friend request will be sent. It will have the same on_delete parameter which decides when the user is deleted, we delete the friend request too."
},
{
"code": null,
"e": 5086,
"s": 4969,
"text": "from_user — This denotes the user who is sending the friend request. It will also be deleted if the user is deleted."
},
{
"code": null,
"e": 5179,
"s": 5086,
"text": "timestamp — It is not really necessary to add. It stores the time when the request was sent."
},
{
"code": null,
"e": 5308,
"s": 5179,
"text": "As you can notice both to_user and from_user uses the same ForeignKey so to differentiate we need to use the related_name field."
},
{
"code": null,
"e": 5408,
"s": 5308,
"text": "So, that finishes our models.py file. Have a look at the code below which shows the models.py file."
},
{
"code": null,
"e": 5464,
"s": 5408,
"text": "After models.py file, we move forward to admin.py file."
},
{
"code": null,
"e": 5638,
"s": 5464,
"text": "It will be short and it will consist of a few lines only. It denotes the models which we will be registering to our admin panel. We will be registering both our models here."
},
{
"code": null,
"e": 5665,
"s": 5638,
"text": "Next, we move to forms.py."
},
{
"code": null,
"e": 5794,
"s": 5665,
"text": "To know more about working of forms in Django, do visit this official tutorial by Django itself. Then proceed into the tutorial."
},
{
"code": null,
"e": 5838,
"s": 5794,
"text": "We define three forms in our forms.py file."
},
{
"code": null,
"e": 6389,
"s": 5838,
"text": "UserRegisterForm — This is for registration of a new user. We user the Django’s default UserCreationForm and we define what should be in the forms. We set the email to be Django’s EmailField. Then we tell Django that model is User and the fields that we would ask the user to fill while registering.UserUpdateForm — This form will let users update their profile. It will have all the same fields as Registration form but we would use the Django Model form instead of UserCreationForm.ProfileUpdateForm — This form will let users update their profile."
},
{
"code": null,
"e": 6689,
"s": 6389,
"text": "UserRegisterForm — This is for registration of a new user. We user the Django’s default UserCreationForm and we define what should be in the forms. We set the email to be Django’s EmailField. Then we tell Django that model is User and the fields that we would ask the user to fill while registering."
},
{
"code": null,
"e": 6875,
"s": 6689,
"text": "UserUpdateForm — This form will let users update their profile. It will have all the same fields as Registration form but we would use the Django Model form instead of UserCreationForm."
},
{
"code": null,
"e": 6942,
"s": 6875,
"text": "ProfileUpdateForm — This form will let users update their profile."
},
{
"code": null,
"e": 7029,
"s": 6942,
"text": "So, adding these three forms would complete our forms.py file. Look at the code below:"
},
{
"code": null,
"e": 7120,
"s": 7029,
"text": "So, after this, we have our forms.py file created. Next, we would be seeing views.py file."
},
{
"code": null,
"e": 7278,
"s": 7120,
"text": "Now, we will define the views.py file. It would contain all our views (how to render the files in the web browser). It directly passes data to the templates."
},
{
"code": null,
"e": 7398,
"s": 7278,
"text": "Read this official tutorial by Django to understand views in a better way. After reading the tutorial, we move forward."
},
{
"code": null,
"e": 7614,
"s": 7398,
"text": "Since the views file is too large, we can make it as we like, so I would give a simple overview of what each view does, and you can read the code below for better understanding. So, let’s go through them one by one:"
},
{
"code": null,
"e": 9654,
"s": 7614,
"text": "users_list — This view will form the user list to be recommended to any user to help them discover new users to make friends with. We will filter out our friends from that list and will exclude us too. We will make this list by first adding our friend’s friends who are not our friends. Then if our user list has still low members, we will add random people to recommend (mostly for a user with no friends).friend_list — This view will display all the friends of the user.send_friend_request — This will help us create a friend request instance and will send a request to the user. We take in the id the user we are sending a request to so that we can send him the request.cancel_friend_request — It will cancel the friend request we sent to the user.accept_friend_request — It will be used to accept the friend request of the user and we add user1 to user2’s friend list and vice versa. Also, we will delete the friend request.delete_friend_request — It will allow the user to delete any friend request he/she has received.delete_friend — This will delete the friend of that user i.e. we would remove user1 from user2 friend list and vice versa.profile_view — This will be the profile view of any user. It will showcase the friend's count and posts count of the user and their friend list. Also, it would showcase the friend request received and sent by the user and can accept, decline or cancel the request. Obviously, we would add conditions and checks, so that only the concerned user is shown the requests and sent list and they only have the power to accept or reject requests and not anyone viewing his/her profile.register — This will let users register on our website. It will render the registration form we created in forms.py file.edit_profile — This will let the users edit their profile with help of the forms we created.search_users — This will handle the search function of the users. It takes in the query and then filters out relevant users.my_profile — This is same as profile_view but it will render your profile only."
},
{
"code": null,
"e": 10062,
"s": 9654,
"text": "users_list — This view will form the user list to be recommended to any user to help them discover new users to make friends with. We will filter out our friends from that list and will exclude us too. We will make this list by first adding our friend’s friends who are not our friends. Then if our user list has still low members, we will add random people to recommend (mostly for a user with no friends)."
},
{
"code": null,
"e": 10128,
"s": 10062,
"text": "friend_list — This view will display all the friends of the user."
},
{
"code": null,
"e": 10330,
"s": 10128,
"text": "send_friend_request — This will help us create a friend request instance and will send a request to the user. We take in the id the user we are sending a request to so that we can send him the request."
},
{
"code": null,
"e": 10409,
"s": 10330,
"text": "cancel_friend_request — It will cancel the friend request we sent to the user."
},
{
"code": null,
"e": 10587,
"s": 10409,
"text": "accept_friend_request — It will be used to accept the friend request of the user and we add user1 to user2’s friend list and vice versa. Also, we will delete the friend request."
},
{
"code": null,
"e": 10684,
"s": 10587,
"text": "delete_friend_request — It will allow the user to delete any friend request he/she has received."
},
{
"code": null,
"e": 10807,
"s": 10684,
"text": "delete_friend — This will delete the friend of that user i.e. we would remove user1 from user2 friend list and vice versa."
},
{
"code": null,
"e": 11285,
"s": 10807,
"text": "profile_view — This will be the profile view of any user. It will showcase the friend's count and posts count of the user and their friend list. Also, it would showcase the friend request received and sent by the user and can accept, decline or cancel the request. Obviously, we would add conditions and checks, so that only the concerned user is shown the requests and sent list and they only have the power to accept or reject requests and not anyone viewing his/her profile."
},
{
"code": null,
"e": 11407,
"s": 11285,
"text": "register — This will let users register on our website. It will render the registration form we created in forms.py file."
},
{
"code": null,
"e": 11500,
"s": 11407,
"text": "edit_profile — This will let the users edit their profile with help of the forms we created."
},
{
"code": null,
"e": 11625,
"s": 11500,
"text": "search_users — This will handle the search function of the users. It takes in the query and then filters out relevant users."
},
{
"code": null,
"e": 11705,
"s": 11625,
"text": "my_profile — This is same as profile_view but it will render your profile only."
},
{
"code": null,
"e": 11757,
"s": 11705,
"text": "Go through the code below for better understanding."
},
{
"code": null,
"e": 11896,
"s": 11757,
"text": "It sums up our Users app. We are left with the urls.py which we won’t include in users app. We will add it directly to our photoshare app."
},
{
"code": null,
"e": 11971,
"s": 11896,
"text": "You can view this simple tutorial to understand more about URLs in Django."
},
{
"code": null,
"e": 12135,
"s": 11971,
"text": "This file contains all the URLs for the website. It has an include(‘feed.urls’) which includes all URLs from the Feed app which we will build in the next tutorial."
},
{
"code": null,
"e": 12252,
"s": 12135,
"text": "And we include all the URLs for the photoshare app directly in the main urls.py file. Have a look at the file below:"
},
{
"code": null,
"e": 12461,
"s": 12252,
"text": "If you would like to see the complete code, view the project’s Github Repo. Also, you can try out this app by visiting this link. It is hosted on Heroku and the media and static files on Google Cloud Storage."
},
{
"code": null,
"e": 12575,
"s": 12461,
"text": "A similar Django focused series (Building a Job Search Portal) which will teach you some amazing new concepts is:"
},
{
"code": null,
"e": 12602,
"s": 12575,
"text": "shubhamstudent5.medium.com"
},
{
"code": null,
"e": 12637,
"s": 12602,
"text": "The next part of this tutorial is:"
},
{
"code": null,
"e": 12648,
"s": 12637,
"text": "medium.com"
},
{
"code": null,
"e": 12675,
"s": 12648,
"text": "shubhamstudent5.medium.com"
},
{
"code": null,
"e": 12698,
"s": 12675,
"text": "towardsdatascience.com"
}
] |
Election Special: Detect Fake News using Transformers | by Priya Dwivedi | Towards Data Science | The 2020 elections in the US are around the corner. Fake News published on social media is a HUGE problem around the election time. While some of the Fake News is produced purposefully for skewing election results or to make a quick buck through advertisement, false information can also be shared by misinformed individuals in their social media posts. These posts can quickly become viral blurring. Most people believe posts liked by many others must be true.
Detecting Fake News is not an easy task for a machine learning model. Many of these stories are very well written. Still machine learning can help because:
It can detect the writing style as being similar to what has been marked as fake in its database
The version of events in the story conflicts with what is known as true
In this blog we build a fake news detector using BERT and T5 Transformer models. The T5 model does quite well with an impressive 80% accuracy in detecting actual fake news published around 2016 elections.
The full code for the “Fake News Detector” is made public on my Github here.
At Deep Learning Analytics, we are very passionate about using data science and machine learning to solve real world problems. Please reach out to us to discuss an NLP project with us.
For this blog, we have used the Kaggle data set — Getting Real about Fake News. It contains news and stories marked as fake or biased by the BS Detector, a Chrome Extension by Daniel Sieradski. The BS detector labels some websites as fake and then any news scraped from them is marked as fake news.
The data set contains about 1500 news stories of which about 1000 are fake and 500 are real. What I like about this data set is that it has stories captured in the final days of the 2016 election which makes it very relevant to detecting fake news around election time. However one of the challenges in labelling fake news is that time and effort needs to be spent to vet the story and its correctness. The approach taken here is to consider all stories from websites marked as BS to be fake. This may not always be the case.
An example of a story marked as real is:
ed state \nfox news sunday reported this morning that anthony weiner is cooperating with the fbi which has reopened yes lefties reopened the investigation into hillary clintons classified emails watch as chris wallace reports the breaking news during the panel segment near the end of the show \nand the news is breaking while were on the air our colleague bret baier has just sent us an email saying he has two sources who say that anthony weiner who also had coownership of that laptop with his estranged wife huma abedin is cooperating with the fbi investigation had given them the laptop so therefore they didnt need a warrant to get in to see the contents of said laptop pretty interesting development \ntargets of federal investigations will often cooperate hoping that they will get consideration from a judge at sentencing given weiners wellknown penchant for lying its hard to believe that a prosecutor would give weiner a deal based on an agreement to testify unless his testimony were very strongly corroborated by hard evidence but cooperation can take many forms and as wallace indicated on this mornings show one of those forms could be signing a consent form to allow the contents of devices that they could probably get a warrant for anyway well see if weiners cooperation extends beyond that more related
And a fake story is:
for those who are too young or too unwilling to remember a trip down memory lane \n debut hillary speaks at wellesley graduation insults edward brooke senates lone black member \n watergate committee says chief counsel jerry zeifman of hillarys performance she was a liar she was an unethical dishonest lawyer she conspired to violate the constitution the rules of the house the rules of the committee and the rules of confidentiality \n cattlegate as wife of arkansas governor she invests in cattle futures makes \n whitewater clintons borrow money to launch whitewater development corporations several people go to prison over it clintons dont \n bimbo eruptions bill and hillary swear to steve kroft on minutes bill had nothing to do with gennifer flowers \n private investigators we reached out to them hillary tells cbs steve kroft of bills women i met with two of them to reassure them they were friends of ours they also hire pis to bribe andor threaten as many as twodozen of them \n health care reform hillary heads secret healthcare task force sued successfully for violating open meeting laws subsequent plan killed by democraticcontrolled house \n ....
The stories have on an average 311 words with some stories being more than 1000 words long.
For this exercise, we trained two models from HuggingFace — 1. BERT with Sequence Classification head and second a T5 Transformer model with conditional generation head. The BERT model got an accuracy of 75% in detecting fake news on the validation set whereas the T5 model was able to achieve an accuracy of 80%. So we will focus the rest of the blog on how a T5 model can be trained.
T5 is a text to text model meaning it can be trained to go from input text of one format to output text of one format. This makes this model very versatile. I have personally used it to train for text summarization. Check my blog here. And also used it to build a trivia bot which can retrieve answers from memory without any provided context. Check this blog here.
Huggingface T5 implementation contains a Conditional Generation head that can be used for any task. For our task, our input is the actual news story and output is text — Real/Fake.
For the input text we set the max token length to 512. If stories are smaller than 512 then a <PAD> token will be added to the end. If stories are larger then they will get truncated. For the output the token length is set as 3. Code snippet for this is below. Please find the full code on my Github here.
source = self.tokenizer.batch_encode_plus([input_], max_length=self.input_length, padding='max_length', truncation=True, return_tensors="pt") targets = self.tokenizer.batch_encode_plus([target_], max_length=3, padding='max_length', truncation=True, return_tensors="pt")
Next we define the T5 model fine tuner class. The model forward pass is the same as other Transformer models. Since T5 is a text-text model, both the input and targets tokenized as well as their attention mask is passed to the model.
def forward(self, input_ids, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, lm_labels=None): return self.model( input_ids, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, labels=lm_labels )
In the generation step, the output of the decoder is limited to a token length of 3 as shown below:
def _generative_step(self, batch) : t0 = time.time() # print(batch) inp_ids = batch["source_ids"] generated_ids = self.model.generate( batch["source_ids"], attention_mask=batch["source_mask"], use_cache=True, decoder_attention_mask=batch['target_mask'], max_length=3 ) preds = self.ids_to_clean_text(generated_ids) target = self.ids_to_clean_text(batch["target_ids"]
The model measures accuracy score by checking if the generated label — fake/real matches the actual label or not.
T5 small was trained for 30 epochs using a batch size of 8. The model took about an hour to train. Weights and Biases was used to monitor training. The online Github code has wandb integrated into Pytorch Lightning for training.
I trained a T5 small on token length of 512 and 1024. Both the models performed similar and got to an accuracy score of close to 80%
Testing out the T5 on the val set shows that the model has an impressive ability to detect fake news.
Input Text: classify: russias most potent weapon hoarding gold shtfplancom this article was written by jay syrmopoulos and originally published at the free thought project editors comment he who holds the gold makes the rules fresh attempts at containing russia and continuing the empire have been met with countermoves russia appears to be building strength in every way putin and his country have no intention of being under the american thumb and are developing rapid resistance as the us petrodollar loses its grip and china russia and the east shift into new currencies and shiftingworld order what lies ahead it will be a strong hand for the countries that have the most significant backing in gold and hard assets and china and russia have positioned themselves verywell prepare for a changing economic landscape and one in which selfreliance might be all we have russia is hoarding gold at an alarming rate the next world war will be fought with currencies by jay syrmopoulos with all eyes on russias unveiling their latest nuclear intercontinental ballistic missile icbm which nato has dubbed the satan missile as tensions with the us increase moscows most potent weapon may be something drastically different the rapidly evolving geopolitical weapon brandished by russia is an ever increasing stockpile of gold as well as russias native currency theruble take a look at the symbol below as it could soon come to change the entire hierarchy of the international order potentially ushering in a complete international paradigm shift...Actual Class: FakePredicted Class from T5: Fake
T5 is an awesome model. It has made it easy to fine tune a Transformer for any NLP problem with sufficient data. This blog shows that T5 can do an impressive job of detecting fake news.
I hope you give the code a try and train your own models. Please share your experience in the comments below.
At Deep Learning Analytics, we are extremely passionate about using Machine Learning to solve real-world problems. We have helped many businesses deploy innovative AI-based solutions. Contact us through our website here if you see an opportunity to collaborate.
T5 Transformer
Huggingface Transformers
Real vs Fake News | [
{
"code": null,
"e": 634,
"s": 172,
"text": "The 2020 elections in the US are around the corner. Fake News published on social media is a HUGE problem around the election time. While some of the Fake News is produced purposefully for skewing election results or to make a quick buck through advertisement, false information can also be shared by misinformed individuals in their social media posts. These posts can quickly become viral blurring. Most people believe posts liked by many others must be true."
},
{
"code": null,
"e": 790,
"s": 634,
"text": "Detecting Fake News is not an easy task for a machine learning model. Many of these stories are very well written. Still machine learning can help because:"
},
{
"code": null,
"e": 887,
"s": 790,
"text": "It can detect the writing style as being similar to what has been marked as fake in its database"
},
{
"code": null,
"e": 959,
"s": 887,
"text": "The version of events in the story conflicts with what is known as true"
},
{
"code": null,
"e": 1164,
"s": 959,
"text": "In this blog we build a fake news detector using BERT and T5 Transformer models. The T5 model does quite well with an impressive 80% accuracy in detecting actual fake news published around 2016 elections."
},
{
"code": null,
"e": 1241,
"s": 1164,
"text": "The full code for the “Fake News Detector” is made public on my Github here."
},
{
"code": null,
"e": 1426,
"s": 1241,
"text": "At Deep Learning Analytics, we are very passionate about using data science and machine learning to solve real world problems. Please reach out to us to discuss an NLP project with us."
},
{
"code": null,
"e": 1725,
"s": 1426,
"text": "For this blog, we have used the Kaggle data set — Getting Real about Fake News. It contains news and stories marked as fake or biased by the BS Detector, a Chrome Extension by Daniel Sieradski. The BS detector labels some websites as fake and then any news scraped from them is marked as fake news."
},
{
"code": null,
"e": 2251,
"s": 1725,
"text": "The data set contains about 1500 news stories of which about 1000 are fake and 500 are real. What I like about this data set is that it has stories captured in the final days of the 2016 election which makes it very relevant to detecting fake news around election time. However one of the challenges in labelling fake news is that time and effort needs to be spent to vet the story and its correctness. The approach taken here is to consider all stories from websites marked as BS to be fake. This may not always be the case."
},
{
"code": null,
"e": 2292,
"s": 2251,
"text": "An example of a story marked as real is:"
},
{
"code": null,
"e": 3618,
"s": 2292,
"text": "ed state \\nfox news sunday reported this morning that anthony weiner is cooperating with the fbi which has reopened yes lefties reopened the investigation into hillary clintons classified emails watch as chris wallace reports the breaking news during the panel segment near the end of the show \\nand the news is breaking while were on the air our colleague bret baier has just sent us an email saying he has two sources who say that anthony weiner who also had coownership of that laptop with his estranged wife huma abedin is cooperating with the fbi investigation had given them the laptop so therefore they didnt need a warrant to get in to see the contents of said laptop pretty interesting development \\ntargets of federal investigations will often cooperate hoping that they will get consideration from a judge at sentencing given weiners wellknown penchant for lying its hard to believe that a prosecutor would give weiner a deal based on an agreement to testify unless his testimony were very strongly corroborated by hard evidence but cooperation can take many forms and as wallace indicated on this mornings show one of those forms could be signing a consent form to allow the contents of devices that they could probably get a warrant for anyway well see if weiners cooperation extends beyond that more related"
},
{
"code": null,
"e": 3639,
"s": 3618,
"text": "And a fake story is:"
},
{
"code": null,
"e": 4815,
"s": 3639,
"text": "for those who are too young or too unwilling to remember a trip down memory lane \\n debut hillary speaks at wellesley graduation insults edward brooke senates lone black member \\n watergate committee says chief counsel jerry zeifman of hillarys performance she was a liar she was an unethical dishonest lawyer she conspired to violate the constitution the rules of the house the rules of the committee and the rules of confidentiality \\n cattlegate as wife of arkansas governor she invests in cattle futures makes \\n whitewater clintons borrow money to launch whitewater development corporations several people go to prison over it clintons dont \\n bimbo eruptions bill and hillary swear to steve kroft on minutes bill had nothing to do with gennifer flowers \\n private investigators we reached out to them hillary tells cbs steve kroft of bills women i met with two of them to reassure them they were friends of ours they also hire pis to bribe andor threaten as many as twodozen of them \\n health care reform hillary heads secret healthcare task force sued successfully for violating open meeting laws subsequent plan killed by democraticcontrolled house \\n ...."
},
{
"code": null,
"e": 4907,
"s": 4815,
"text": "The stories have on an average 311 words with some stories being more than 1000 words long."
},
{
"code": null,
"e": 5293,
"s": 4907,
"text": "For this exercise, we trained two models from HuggingFace — 1. BERT with Sequence Classification head and second a T5 Transformer model with conditional generation head. The BERT model got an accuracy of 75% in detecting fake news on the validation set whereas the T5 model was able to achieve an accuracy of 80%. So we will focus the rest of the blog on how a T5 model can be trained."
},
{
"code": null,
"e": 5659,
"s": 5293,
"text": "T5 is a text to text model meaning it can be trained to go from input text of one format to output text of one format. This makes this model very versatile. I have personally used it to train for text summarization. Check my blog here. And also used it to build a trivia bot which can retrieve answers from memory without any provided context. Check this blog here."
},
{
"code": null,
"e": 5840,
"s": 5659,
"text": "Huggingface T5 implementation contains a Conditional Generation head that can be used for any task. For our task, our input is the actual news story and output is text — Real/Fake."
},
{
"code": null,
"e": 6146,
"s": 5840,
"text": "For the input text we set the max token length to 512. If stories are smaller than 512 then a <PAD> token will be added to the end. If stories are larger then they will get truncated. For the output the token length is set as 3. Code snippet for this is below. Please find the full code on my Github here."
},
{
"code": null,
"e": 6524,
"s": 6146,
"text": "source = self.tokenizer.batch_encode_plus([input_], max_length=self.input_length, padding='max_length', truncation=True, return_tensors=\"pt\") targets = self.tokenizer.batch_encode_plus([target_], max_length=3, padding='max_length', truncation=True, return_tensors=\"pt\")"
},
{
"code": null,
"e": 6758,
"s": 6524,
"text": "Next we define the T5 model fine tuner class. The model forward pass is the same as other Transformer models. Since T5 is a text-text model, both the input and targets tokenized as well as their attention mask is passed to the model."
},
{
"code": null,
"e": 7135,
"s": 6758,
"text": "def forward(self, input_ids, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, lm_labels=None): return self.model( input_ids, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, labels=lm_labels )"
},
{
"code": null,
"e": 7235,
"s": 7135,
"text": "In the generation step, the output of the decoder is limited to a token length of 3 as shown below:"
},
{
"code": null,
"e": 7722,
"s": 7235,
"text": "def _generative_step(self, batch) : t0 = time.time() # print(batch) inp_ids = batch[\"source_ids\"] generated_ids = self.model.generate( batch[\"source_ids\"], attention_mask=batch[\"source_mask\"], use_cache=True, decoder_attention_mask=batch['target_mask'], max_length=3 ) preds = self.ids_to_clean_text(generated_ids) target = self.ids_to_clean_text(batch[\"target_ids\"]"
},
{
"code": null,
"e": 7836,
"s": 7722,
"text": "The model measures accuracy score by checking if the generated label — fake/real matches the actual label or not."
},
{
"code": null,
"e": 8065,
"s": 7836,
"text": "T5 small was trained for 30 epochs using a batch size of 8. The model took about an hour to train. Weights and Biases was used to monitor training. The online Github code has wandb integrated into Pytorch Lightning for training."
},
{
"code": null,
"e": 8198,
"s": 8065,
"text": "I trained a T5 small on token length of 512 and 1024. Both the models performed similar and got to an accuracy score of close to 80%"
},
{
"code": null,
"e": 8300,
"s": 8198,
"text": "Testing out the T5 on the val set shows that the model has an impressive ability to detect fake news."
},
{
"code": null,
"e": 9891,
"s": 8300,
"text": "Input Text: classify: russias most potent weapon hoarding gold shtfplancom this article was written by jay syrmopoulos and originally published at the free thought project editors comment he who holds the gold makes the rules fresh attempts at containing russia and continuing the empire have been met with countermoves russia appears to be building strength in every way putin and his country have no intention of being under the american thumb and are developing rapid resistance as the us petrodollar loses its grip and china russia and the east shift into new currencies and shiftingworld order what lies ahead it will be a strong hand for the countries that have the most significant backing in gold and hard assets and china and russia have positioned themselves verywell prepare for a changing economic landscape and one in which selfreliance might be all we have russia is hoarding gold at an alarming rate the next world war will be fought with currencies by jay syrmopoulos with all eyes on russias unveiling their latest nuclear intercontinental ballistic missile icbm which nato has dubbed the satan missile as tensions with the us increase moscows most potent weapon may be something drastically different the rapidly evolving geopolitical weapon brandished by russia is an ever increasing stockpile of gold as well as russias native currency theruble take a look at the symbol below as it could soon come to change the entire hierarchy of the international order potentially ushering in a complete international paradigm shift...Actual Class: FakePredicted Class from T5: Fake"
},
{
"code": null,
"e": 10077,
"s": 9891,
"text": "T5 is an awesome model. It has made it easy to fine tune a Transformer for any NLP problem with sufficient data. This blog shows that T5 can do an impressive job of detecting fake news."
},
{
"code": null,
"e": 10187,
"s": 10077,
"text": "I hope you give the code a try and train your own models. Please share your experience in the comments below."
},
{
"code": null,
"e": 10449,
"s": 10187,
"text": "At Deep Learning Analytics, we are extremely passionate about using Machine Learning to solve real-world problems. We have helped many businesses deploy innovative AI-based solutions. Contact us through our website here if you see an opportunity to collaborate."
},
{
"code": null,
"e": 10464,
"s": 10449,
"text": "T5 Transformer"
},
{
"code": null,
"e": 10489,
"s": 10464,
"text": "Huggingface Transformers"
}
] |
C++ String Library - clear | It erases the contents of the string, which becomes an empty string.
Following is the declaration for std::string::clear.
void clear();
void clear() noexcept;
none
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::clear.
#include <iostream>
#include <string>
int main () {
char c;
std::string str;
std::cout << "Please type some lines of text. Enter a start (*) to finish:\n";
do {
c = std::cin.get();
str += c;
if (c=='\n') {
std::cout << str;
str.clear();
}
} while (c!='*');
return 0;
}
The sample output should be like this −
Please type some lines of text. Enter a start (*) to finish:
sairam.krishna *
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2672,
"s": 2603,
"text": "It erases the contents of the string, which becomes an empty string."
},
{
"code": null,
"e": 2725,
"s": 2672,
"text": "Following is the declaration for std::string::clear."
},
{
"code": null,
"e": 2739,
"s": 2725,
"text": "void clear();"
},
{
"code": null,
"e": 2762,
"s": 2739,
"text": "void clear() noexcept;"
},
{
"code": null,
"e": 2767,
"s": 2762,
"text": "none"
},
{
"code": null,
"e": 2772,
"s": 2767,
"text": "none"
},
{
"code": null,
"e": 2835,
"s": 2772,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 2876,
"s": 2835,
"text": "In below example for std::string::clear."
},
{
"code": null,
"e": 3206,
"s": 2876,
"text": "#include <iostream>\n#include <string>\n\nint main () {\n char c;\n std::string str;\n std::cout << \"Please type some lines of text. Enter a start (*) to finish:\\n\";\n do {\n c = std::cin.get();\n str += c;\n if (c=='\\n') {\n std::cout << str;\n str.clear();\n }\n } while (c!='*');\n return 0;\n}"
},
{
"code": null,
"e": 3246,
"s": 3206,
"text": "The sample output should be like this −"
},
{
"code": null,
"e": 3325,
"s": 3246,
"text": "Please type some lines of text. Enter a start (*) to finish:\nsairam.krishna *\n"
},
{
"code": null,
"e": 3332,
"s": 3325,
"text": " Print"
},
{
"code": null,
"e": 3343,
"s": 3332,
"text": " Add Notes"
}
] |
Aptitude - Tables | Tables are very commonly used to represent the set of related data. Tabulation is a very popular technique of data interpretation in which a set of questions are derived from a given table of data/ observations.
For example, using the above table, you want to check in percentage of sugar in April.
Quantity of suger used in April = 210 Kg
Total quantity of food items used in april month = (260+290+210+245+375+460) kg
= 1860 kg
Required % = (210/1840*100)% = 11.4%
87 Lectures
22.5 hours
Programming Line
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 4104,
"s": 3892,
"text": "Tables are very commonly used to represent the set of related data. Tabulation is a very popular technique of data interpretation in which a set of questions are derived from a given table of data/ observations."
},
{
"code": null,
"e": 4191,
"s": 4104,
"text": "For example, using the above table, you want to check in percentage of sugar in April."
},
{
"code": null,
"e": 4360,
"s": 4191,
"text": "Quantity of suger used in April = 210 Kg\nTotal quantity of food items used in april month = (260+290+210+245+375+460) kg\n= 1860 kg\nRequired % = (210/1840*100)% = 11.4%\n"
},
{
"code": null,
"e": 4396,
"s": 4360,
"text": "\n 87 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 4414,
"s": 4396,
"text": " Programming Line"
},
{
"code": null,
"e": 4421,
"s": 4414,
"text": " Print"
},
{
"code": null,
"e": 4432,
"s": 4421,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.